JavaScript    Foundation  Questions: Variables

Foundation Bundle 4

Questions: JavaScript Variables

let could be used to only declare a single variable:

let x;

Or multiple variables could be declared in one go:

let x, y, z;

The variables could also be initialized to given values:

let x = 10;
let y = 2, z = 3;

A variable's name can't begin with a digit; it can't have symbols in it except for $ and _; it can't have spaces in it; and it can't be a keyword.

The camel casing convention.

Using the typeof operator, as in:

JavaScript
if (typeof x !== 'undefined') {
   // The variable x exists
}

Even if x doesn't exist in the program, this code won't throw an error despite the fact that typeof x refers to a non-existent variable. This is because JavaScript specially treats typeof when used on variables.

The only case where this check fails is when a variable exists but holds the value undefined, for e.g. when we declare a variable but don't initialize it.

Processing all variable declarations in their respective scopes before executing any other code is referred to as variable hoisting. Both let and var declarations are hoisted but in different ways.

The var keyword is the old way of defining variables in JavaScript. There were some issues with the semantics of var in earlier JavaScript that were ultimately addressed by let.

In modern-day code, it's a good idea to stick to using let instead of var although var isn't deprecated or bad in terms of performance.
  • let is used to create block-scoped variables while var is used to create local or global-scoped variables.
  • let hoisting forms a temporal dead zone before the declaration point while var hoisting simply takes the value of the underlying variable as undefined.

The temporal dead zone of a let-declared variable refers to the region before the variable's declaration in the source code (in the current scope) where it's invalid to access the variable:

JavaScript
// Temporal dead zone for x
console.log(x);

let x;
Uncaught ReferenceError: Cannot access 'x' before initialization