The 'var' Keyword
var x = 5;var y = 6;var sum = x + y;console.log(sum); // 11
In this example, we declare three variables
Note: Variables declared with
varare function-scoped, meaning they exist within the function they were declared in, or globally if declared outside a function. One peculiar behaviour of
varis 'hoisting', where variables can be referenced before they're declared.
The 'let' Keyword
let keyword was introduced in ECMAScript 2015, also known as ES6.
let provides block scoping, which means the variable is only available within the block where it's declared. This can be more predictable and easier to work with compared to
let a = 5;let b = 6;let product = a * b;console.log(product); // 30
In this code snippet,
product are variables declared with
let. If we tried to reference
product outside of their block, we would get an error.
The 'const' Keyword
const keyword, also introduced in ES6, is used to declare variables that are constant, or immutable. Once a
const variable is assigned, it cannot be reassigned.
const PI = 3.14159;console.log(PI); // 3.14159
In this example,
PI is a constant variable that holds the value of pi. If you try to reassign PI to another value, you would get an error.
constvariables are immutable, this doesn't apply to their properties if the variable is an object. So,
constobjects can have properties changed or added.
Variable Naming Rules
- They should begin with a letter, dollar sign ($), or an underscore (_). They cannot start with a number.
- They can include alphanumeric characters, but no spaces or special characters, except for $ and _.
- Variable names are case sensitive.
$myVar are all valid variable names, but
my-var are not.