본문 바로가기

JavaScriptVeryBeiginning

Using let keyword in relation to reassignment and scope pollution

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.

'JavaScriptVeryBeiginning' 카테고리의 다른 글

DOM(doc obj model)  (0) 2020.07.09
HTML opening default  (0) 2020.07.01
What's the difference between return and console.log?  (0) 2020.06.27
var과 let의 차이?  (0) 2020.06.18
function(name) name must be input as a string  (0) 2020.06.17