Let vs var

2 snippets in JavaScript

Also written as var vs let

JSJavaScript

let Declaration

JS · Variables & Constants
Syntax
let variableName = value;
Example
let score = 0;
score = 10;
console.log(score);
Output
10

Note Block-scoped. Cannot be re-declared in the same scope. Preferred for values that change.

var Declaration (Legacy)

JS · Variables & Constants
Syntax
var variableName = value;
Example
function demo() {
  if (true) {
    var leaked = "visible outside block";
  }
  console.log(leaked);
}
demo();
Output
"visible outside block"

Note Function-scoped, not block-scoped. Hoisted to the top of the function. Avoid in modern code -- use let or const instead.

Frequently asked questions

How does JavaScript handle let vs var?
JavaScript covers this with 2 copy-ready snippets on this page. The "let Declaration" snippet in JavaScript uses `let variableName = value;`.
Which code does the JavaScript example use?
The "let Declaration" snippet uses `let variableName = value;`, from the Variables & Constants section of the JavaScript cheat sheet.
What other JavaScript snippets are shown for "let vs var"?
Besides "let Declaration", this page also shows "var Declaration (Legacy)".
Is there anything to watch out for?
Yes. For "let Declaration": Block-scoped. Cannot be re-declared in the same scope. Preferred for values that change.