DEV Community

Dima Prohorenko
Dima Prohorenko

Posted on

Super useful JavaScript tips

Here is a list of useful tricks for JavaScript developers that will definitely help you one day.

Removing Falsy Values From Arrays

Falsy values are values in JavaScript which evaluate to FALSE. There are only six falsy values in JavaScript and they are:

  • undefined
  • null
  • NaN
  • '' (empty string)
  • 0
  • false The easiest way to filter out these falsy values is to use the below function.
array.filter(Boolean);
Enter fullscreen mode Exit fullscreen mode

Keep in mind that filter returns new array and does not modify the original array.

The difference between target and currentTarget in the event context.

target refers to the DOM element that triggers an event. Otherwise, currentTarget refers to the DOM element that the event listener is listening on.

<ul class="list">
  <li class="list__item">Study JavaScript</li>
</ul>
Enter fullscreen mode Exit fullscreen mode
const list = document.querySelector('.list');

list.addEventListener('click', (e) => {
    console.log(e.target); 
        // Output: "<li class='list__item'>Study JavaScript</li>"
    console.log(e.currentTarget); 
       // Output: "<ul class="list"><li class="list__item">Study JavaScript</li></ul>
});
Enter fullscreen mode Exit fullscreen mode

Copy to Clipboard

It’s easy, the bad thing is that we must add an with the text to be copied to the DOM. Then, we selected the content and execute the copy command with execCommand. execCommand('copy') will copy the actual selected content.

<input type="text">
<button>Copy to Clipboard</button>
Enter fullscreen mode Exit fullscreen mode
button.addEventListener('click', () => {
    input.select();
    document.execCommand('copy');
});
Enter fullscreen mode Exit fullscreen mode

Or if you don't want to use input, there's a way to copy content from div, span, p.

<p>Some text to copy</p>
<button>Copy to Clipboard</button>
Enter fullscreen mode Exit fullscreen mode
function copyToClipboard (el) {
    const r = document.createRange();
    r.selectNode(el);
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(r);
    document.execCommand('copy');
    window.getSelection().removeAllRanges();
}

button.addEventListener('click', () => {
    copyToClipboard(paragraph);
});
Enter fullscreen mode Exit fullscreen mode

Truncate an Array

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array.length = 4;
console.log(array); // Result: [0, 1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

That's it for today. Hope you learned something new:)

Top comments (2)

Collapse
 
nikhilmwarrier profile image
nikhilmwarrier

Awesome!

Collapse
 
sasscrafter profile image
Dima Prohorenko

Thanks ;)