JavaScript Variables

up:: JavaScript

Variables

Var versus let

let is block-scoped. var is global scoped.

In JavaScript, the keyword ==let== is used to declare a changeable variable in the block-scope.

In JavaScript, the keyword ==var== is used to declare a variable in the global scope.

var camper = "James";
var camper = "David"; // Doesn't throw an error
 
let camper = "James";
let camper = "David"; // Does throw an error

var and let

Unless you know what you’re doing, keep var afar and bet on let.

In You Don’t Know JS Yet, he pushes back on this advice a bit. You should use all features of a language. var has it’s uses.

  • var: assigns
  • without var: assigns with global scope
  • let: want to change
  • const: anything else
  • = to assign
  • + for concatenation
  • Primitives
  • Compound
    • Arrays [1, 2, 3]
    • Objects {} - Key + Name
  • myVar += 5 – Add and assign