Skip to content

Instantly share code, notes, and snippets.

@romain130492
Last active April 7, 2020 02:26
Show Gist options
  • Save romain130492/09e1a396f0f2729be474224ef31d719e to your computer and use it in GitHub Desktop.
Save romain130492/09e1a396f0f2729be474224ef31d719e to your computer and use it in GitHub Desktop.
Const vs Let vs Var - #Javascript
  • Redefining :

Const ==> Constant : Cannot be reassign. Example :

const name='Romain';
name='Thomas'
console.log(name) ==> Error   

Const cannot be reassigned but can be manipulated Let, var : Can be reassign Example :

let name='Romain'
name='Thomas'
  • Function Scope :
function myFn() {
  var foo = 'peekaboo!';
  
  console.log(foo); // 'peekaboo!'
}

console.log(foo); // ReferenceError: foo is not defined
  • Block Scope :
if (true) {
  var foo = 'peekaboo!';
  let bar = 'i see u';
  const baz = 'baby blue!';

  console.log(foo); // 'peekaboo!';
  console.log(bar); // 'i see u';
  console.log(baz); // 'baby blue!';
      }

console.log(foo); // 'peekaboo!';
console.log(bar); // ReferenceError: bar is not defined
console.log(baz); // ReferenceError: baz is not defined
  • For loop scope :
for (var i = 0; i < 3; i++) {
  console.log(i);
}
console.log(i);

Var is accessible outside of for loop, confitionnal Block but not accessible outside of a function. Let, Const are not accessible outside loop, conditionnal blocks and function.

Avoid var because function-scope Source : https://alligator.io/js/var-let-const/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment