Variables
Variables are containers that store values. You start by declaring a variable with the let
keyword, followed by the name you give to the variable.
let
The let
declaration declares re-assignable, block-scoped local variables, optionally initializing each to a value.
let myVariable = "Lite";
// change vars without a declaration
myVariable = 'Rank';
// slight shortcut for multiple vars
let a = 'hello', b = 'world'
const
The const
declaration declares block-scoped local constant variables.
The value of a constant can't be changed through reassignment, but if a constant is an object, its properties can be added, updated, or removed.
const number = 42;
// [Error]: Assignment to constant variable.
number = 99;
Scope
The scope is the current context of execution in which values and expressions are "visible" or can be referenced. If a variable or expression is not in the current scope, it will not be available for use.
JavaScript has the following kinds of scopes:
- Global scope: The default scope for all code running in script mode.
- Module scope: The scope for code running in module mode.
- Function scope: The scope created with a function.
In addition, variables declared with let
or const
can belong to an additional scope:
- Block scope: The scope created with a pair of curly braces (a block).
// Variables in Global scope are accessible everywhere
let g = 'global';
function updateVars() {
g = 'useVars';
}
updateVars();
console.log(g); // useVars
// A new local function scope is established in functions
// Local variables are only accessible inside their scope
function f1() {
let v1 = 'apple';
{
// A new block scope is established in curly braces
let v1 = 'banana';
let v2 = 'cherry';
console.log(v1); // banana
}
// Block scope ends here, come back to function scope
console.log(v1); // apple
// [Error]: v2 is not defined
console.log(v2);
}
Code Challenge
Try to swap two variables' values without using a third variable.