Use a function before its declaration in JavaScript, is it possible?

In JavaScript you can use a function before declaring it (hoisting). Example:

javascript
let random = getRandomValue();

function getRandomValue(){
    
    return Math.random();
    
}

console.log(random);
// 0.8120294008505673

The function declarations are bound before anything is executed.

Assigning function to a variable

But if you try to declare a function assigning it to a variable and call it before declaration:

javascript
let 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:

javascript
let 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.