DEV Community

Discussion on: 30 JavaScript Tricky Hacks

Collapse
 
joolsmcfly profile image
Julien Dephix • Edited

Nice list, even though I wouldn't call these code snippets hacks but shortcuts?

Couple of things to note.

Hack # 1: !! is called a double bang. I don't use it as it looks a bit weird. I prefer to use Boolean().

Hack # 11. example you provided for tagged template literals could be better as it just outputs what was passed. Looks like a copy of Wes Bos' article back in 2016:

function highlight(strings, ...values) {
  let str = '';
  strings.forEach((string, i) => {
    str += `${string} <span class='hl'>${values[i] || ''}</span>`;
  });
  return str;
}
Enter fullscreen mode Exit fullscreen mode

Hack #21. swapping values is much easier this way:

let a = 2, b = 1;
[a, b] = [b, a];
Enter fullscreen mode Exit fullscreen mode

Hack #23. converting the way you do it can cause issues if variable holds non numerical characters. Prefer .parseInt over plus.

let n = "123A";
console.log(+n); // NaN
console.log(parseInt(n, 10)); // 123
Enter fullscreen mode Exit fullscreen mode

Hope this helps!

Collapse
 
xi_sharky_ix profile image
shArky

Simply note, that #21 is more readable (for me both is good), but not easier for PC.
In case of XOR swap we working with numbers as bits represented in memory. In case of array swap we created 2 arrays.

Collapse
 
joolsmcfly profile image
Julien Dephix

You're right but it only creates one array actually: a temp array [b, a].
JS then destructures it to assign values to a and be respectively.

This is what code looks like after being transpiled:

    var a = 12;
    var b = 13;
    var _b;
    _b = [b, a], a = _b[0], b = _b[1];
Enter fullscreen mode Exit fullscreen mode

Yes, it uses more memory but we're talking about 2 numbers here so the diff in memory footprint is very minimal and not worth loosing readability.