DEV Community

Joe Erickson
Joe Erickson

Posted on

Who was that masked variable?

Who is that masked variable?

We were running through some of our curriculum at Tech Elevator and ran across a piece of code that said that you couldn't define the same variable name in two different scopes in JavaScript.

This struck me as a little strange. JavaScript will let you do anything it just might not be what you wanted. Surely, it wouldn't throw an error if you define the same variable again in a child scope? So I wrote this code in my browser's console to test it out:

{
    let i = 3;
    {
        let i = 29;  // <-- This is a new variable and masks the original
        console.log(i);  // <-- Will print 29
    }
    console.log(i); // <-- Back to the original variable, will print 3
}
Enter fullscreen mode Exit fullscreen mode

So the second variable just masks the first one until it falls out of scope. Interesting!

At first I thought that this might be useful, but then I couldn't think of a single useful thing to use this with.

So, my question to you, can you think of a useful way of using this feature in an algorithm in JavaScript?

Top comments (2)

Collapse
 
khuongduybui profile image
Duy K. Bui

Not really masking, but I have used this feature to safely reuse the variable name, such as

parentArray.forEach((entity) => {
  // do a lot of things with entity
  const something = aTotallyIrrelavantArray.map((entity) => entity.someQuickTransformation());
  // do more things with original entity
}
Collapse
 
firstclown profile image
Joe Erickson

My first thought was, wouldn't it be cool to have a formula that stays the same but you could mask some of the variables with new values before running it! But if that masking happens conditionally in an if statement, then the variable will just revert back to their original values when the execution leaves the if and we're right back to where we started.

BTW, the above code works with const too!

{
    const i = 3;
    {
        const i = 29;  // <-- This is a new variable and masks the original
        console.log(i);  // <-- Will print 29
    }
    console.log(i); // <-- Back to the original variable, will print 3
}