Skip to content
sergio edited this page Jan 11, 2021 · 5 revisions

let and const. Both solve all of var scope issues. Both also throw an error if you try to declare the same variable a second time:

let pi = 3.14159;
//=> undefined
 
let pi = "the ratio between a circle's circumference and diameter";
//=> Uncaught SyntaxError: Identifier 'pi' has already been declared

Declaring a variable with the const reserved word means that not only can it not be redeclared but it also cannot be reassigned.

  • Use var... never.
  • Use let... when you know the value of a variable will change. For example, a counter variable that starts at 0 and is subsequently incremented to 1, 2, 3, and so on. In the lessons on looping and iteration in JavaScript, let will have its moment in the spotlight.
  • Use const... for every other variable.

Best practice is to always declare variables with const and then, if you later realize that the value has to change over the course of your program, circle back to change it to let.


Clone this wiki locally