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:
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.
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
.
let
instead of var
although var
isn't deprecated or bad in terms of performance.let
is used to create block-scoped variables whilevar
is used to create local or global-scoped variables.let
hoisting forms a temporal dead zone before the declaration point whilevar
hoisting simply takes the value of the underlying variable asundefined
.
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:
// Temporal dead zone for x
console.log(x);
let x;