Skip to content

Instantly share code, notes, and snippets.

@brauliodiez
Created June 4, 2017 09:10
Show Gist options
  • Save brauliodiez/8df3f05463a2a0ac39dead3c364c79b8 to your computer and use it in GitHub Desktop.
Save brauliodiez/8df3f05463a2a0ac39dead3c364c79b8 to your computer and use it in GitHub Desktop.
javascript var vs const vs let

Const / Let

Let:

  • Variables that can change (be reassigned).
  • Take in account block scope instead of function scope (e.g. issue var for or if).

Const:

  • Variables that cannot be reassigned ()

More info: https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75

Steps

  • Let's open codepen and click on create >> new Pen

https://codepen.io/

  • On Settings let's untick the option Behavior >> Auto-updatingPreview (we want to have a run button).

  • Let's add the following code snippet:

function myFunction() {
  var myVar = 2;

  if(myVar < 3) {
    var myVar = 3;
    console.log(`** Inside if statement: ${myVar}`);
  }

  console.log(`** Outside if statement: ${myVar}`);
}

myFunction();
  • Check that we get in both console logs the value '3', this is caused because var works at function scope.
** Inside if statement: 3
** Outside if statement: 3
  • Let's replace this "var" based code with a "let" based code.
function myFunction() {
-   var myVar = 2;
+   let myVar = 2;
  if(myVar < 3) {
-    var myVar = 3;
+    let myVar = 3;
    console.log(`** Inside if statement: ${myVar}`);
  }

  console.log(`** Outside if statement: ${myVar}`);
}

myFunction();
  • Now we get the expected block scope behavior.
"** Inside if statement: 3"
"** Outside if statement: 2"
  • Let's start with another simple sample, using let and reasigning:
function myFunction() {
  let myVar = 2;
  myVar = 3;    
  
  console.log(`** Outside if statement: ${myVar}`);
}

myFunction();
  • So far so good, it works.

  • What would happen if we use const ?

function myFunction() {
-  let myVar = 2;
+  const myVar = 2;
  myVar = 3;    
  
  console.log(`** Outside if statement: ${myVar}`);
}

myFunction();
  • Now if we open the console (browsre console, F12) we get the following error:
Uncaught TypeError: Assignment to constant variable.
    at myFunction (pen.js:10:9)
    at pen.js:15:1

That's because using const, it doesn't allow to reassign the variable.

Important 'const' is not about immutability, is about immutable binding: https://mathiasbynens.be/notes/es6-const

@pablonete
Copy link

Two nice points to extend:

  • Shadowing variables is a bad practice, even with let.
  • const list = []; list.push("a"); is the best example of immutable binding but mutable instance.

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