DEV Community

Who was that masked variable?

Joe Erickson on October 31, 2019

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 th...
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
}