Saturday, 8 April 2017

JavaScript: Difference in hoisting for let, const?

Background

I have a functions that is responsible for generating a random number and making it available.

"use strict";

module.exports = function(args) {
    let {
        min,
        max,
    } = args;

    let currNumber = genRandom(min, max);

    const genRandom = (min, max) => Math.floor(Math.random() * max) + min;

    const getNumber = () => currNumber;    

    return Object.freeze({
        getNumber
    });
};

Problem

For a reason I don't understand, when I run this code with Node.js 7.8, I get the error that genRandom is not defined.

But if I change the code from:

let currNumber = genRandom(min, max);

const genRandom = (min, max) => Math.floor(Math.random() * max) + min;

to:

const genRandom = (min, max) => Math.floor(Math.random() * max) + min;

let currNumber = genRandom(min, max);

then it works!

I don't understand why this happens. I thought that const and let were hoisted just like var, but this leads me to believe I am wrong.

Question

Can someone explain me this behavior ?



via Flame_Phoenix

No comments:

Post a Comment