JavaScriptVeryBeiginning
Using let keyword in relation to reassignment and scope pollution
jyshimmy
2020. 6. 20. 14:23
let num = 50;
const logNum = () => {
num = 100; // Take note of this line of code
console.log(num);
};
logNum(); // Prints 100
console.log(num); // Prints 100
In here:
- We have a variable num.
- Inside the function body of logNum(), we want to declare a new variable but forgot to use the let keyword. ??Why does it matter? What difference does it make when we use let keyword?
- When we call logNum(), num gets reassigned to 100.
- The reassignment inside logNum() affects the global variable num.
- Even though the reassignment is allowed and we won’t get an error, if we decided to use num later, we’ll unknowingly use the new value of num.
When I used the let keyword within the logNum function block, the only difference it showed was “SyntaxError” that says Identifier 'logNum' has already been declared. I don’t understand why it used the word “forgot”, when it seems the let was not supposed to be used again anyway.