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.