Today I Learned - Rocky Kev

TIL function hoisting in JS

POSTED ON:

TAGS:

We know hoisting creates unintended side effect within JS.

It's why we switch from var to let & const.
There's also side efects with functions.

Via Type of NaN - A quiz system to test your JS

Consider the following declarations and expression. What gets logged?

Example 1:

immaBeOnTop();

var immaBeOnTop;

function immaBeOnTop() {
  console.log('first');
}

immaBeOnTop = function() {
  console.log('second');
};

result:

first
  1. The var is hoisted.
  2. The function immaBEOnTop() is hoisted.
  3. Then we start going down the list of commands.
  4. We then run the immaBeOnTop();

Example 2:

spitNumbers();

function spitNumbers() {
  console.log("first");
}

var spitNumbers = function() {
  console.log("second");
};

function spitNumbers() {
  console.log("third");
}

spitNumbers();

result:

third
second
  1. the first gets hoisted.
  2. The third gets hoisted, and overrides.
  3. spitNumbers(); is called, and returns third.
  4. We then move down to the next function, var spitNumbers = function(). That overrides the result.
  5. spitNumbers(); is called again, and returns second.

Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.