Why are all of our codeacademy Javascript exercises written using either const or let


#1

Ok. Just learning about scope, but if var is best practice, why are all of our codeacademy Javascript exercises written using either const or let to create variables? I realize this is very basic, but researching the topic online provides other answers - people who no longer use var, and mozilla references which always use var.


Return and console.log , variable declaration with and without using 'var' in javascript
#2

var used to be the only keyword for declaring variables. A long held complaint about ES5 was the lack of block scope in loop constructs which was rectified in ES2015 with the introduction of let.

 > var a;
 > for (let i = 1, a = 0; i < 10; i++) {
       a += i ;
   }
 > console.log(i)
<- Uncaught ReferenceError: i is not defined
 > console.log(a)
   undefined
<- undefined

In the above, a is declared, but not defined. In the block scope of the loop, a is a locally defined variable (of the let expression). This is not the same variable as outside of the loop. As we can see, i cannot be polled outside of the loop, and a is still undefined.

 > var a = 0;
 > for (let i = 1; i < 10; i++) {
       a += i ;
   }
 > console.log(i)
<- Uncaught ReferenceError: i is not defined
 > console.log(a)
   45
<- undefined

Above, only the iterator is block scoped and a is globally accessible so pollable after the loop, showing the updates done on the variable.

The const keyword is for declaring variables that are immutable.

 > const pi = 3.1416
<- undefined
 > pi = Math.PI
<- Uncaught TypeError: Assignment to constant variable

That’s the error that will be raised if we try to change the value. If the constant is a data structure such as an array or object, the data is mutable, but we cannot delete the object or reassign the variable.

Since the JavaScript course uses our browser’s own scripting engine, and most browsers these days support ES2015 and later, all the new syntax is supported. What the author asks for is what we should use. At this stage it is not critical that we grasp their reasoning.


#3

Thank you! I don’t actually understand your reply but I hope to by the end of the course.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.