In JavaScript you can use a function before declaring it (hoisting). Example:
javascriptlet random = getRandomValue(); function getRandomValue(){ return Math.random(); } console.log(random); // 0.8120294008505673
The function declarations are bound before anything is executed.
But if you try to declare a function assigning it to a variable and call it before declaration:
javascriptlet random = getRandomValue(); let getRandomValue = () => Math.random();
You'll get the following error:
Uncaught ReferenceError: Cannot access 'getRandomValue' before initialization
The declaration looks similar, but assigning the function to a variable causes the error. In ES6, the correct way to do it is to define the function before calling it:
javascriptlet getRandomValue = () => Math.random(); let random = getRandomValue(); console.log(random); // 0.9083141971995645
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.