Skip to content

Instantly share code, notes, and snippets.

@kevinchisholm
Last active January 3, 2018 00:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinchisholm/4cb2292d5e3b8193c34999b5540f650b to your computer and use it in GitHub Desktop.
Save kevinchisholm/4cb2292d5e3b8193c34999b5540f650b to your computer and use it in GitHub Desktop.
What is the difference between LET and CONST in JavaScript?
var i = 100;
{
console.log('(A) i = ' + i); //100
}
console.log('(B) i = ' + i); //100
// const-example-1: output
(A) i = 50
(B) i = 100
var i = 100;
{
const i = 50;
console.log('(A) i = ' + i); //50
}
console.log('(B) i = ' + i); //100
// const-example-2: output
Uncaught TypeError: Assignment to constant variable.
var i = 0,
j = 100;
for (; i < 10; i++) {
//j is now private to this block
const j = 50;
//attempt to increment j (throws a TypeError)
j++;
//this code never even has a chance to execute
console.log('i =' + i + ' | j = ' + j);
}
i = 0 | j = 50
i = 1 | j = 50
i = 2 | j = 50
i = 3 | j = 50
i = 4 | j = 50
i = 5 | j = 50
i = 6 | j = 50
i = 7 | j = 50
i = 8 | j = 50
i = 9 | j = 50
var i = 0,
j = 100;
for (; i < 10; i++) {
//j is now private to this block
const j = 50;
//j will always be 50 in the console
console.log('i = ' + i + ' | j = ' + j);
}
//let-example-1: output
(A) i = 50
(B) i = 100
var i = 100;
{
let i = 50;
console.log('(A) i = ' + i); //50
}
console.log('(B) i = ' + i); //100
i = 0 | j = 51
i = 1 | j = 51
i = 2 | j = 51
i = 3 | j = 51
i = 4 | j = 51
i = 5 | j = 51
i = 6 | j = 51
i = 7 | j = 51
i = 8 | j = 51
i = 9 | j = 51
var i = 0,
j = 100;
for (; i < 10; i++) {
//j is now private to this block
let j = 50;
//increment j
j++;
//j will always be 51 in the console
console.log('i = ' + i + ' | j = ' + j);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment