DEV Community

Marcos Freitas
Marcos Freitas

Posted on

JavaScript Variables

What is a variable in JavaScript? A variable is a location where you can store values (strings, number, boolean, etc) to be used later. After passing this data and storing in JavaScript engine, you can access it when needed. By assigning a name to our variable, we can tell the engine which specific stored data we want access. Variables' names must be unique identifiers and cannot be numbers, they must be in lower case unless it is made of multiple words then you can use camelCase.

The main variables declarations are const, let, and var. The var declaration was the only one used in the past until the language update in 2015 adding const and let to variable declaration.

JavaScript let statement:
let x = 1;
if (x === 1) {
let x = 2;
console.log(x);
// expected output: 2
}
console.log(x);
// expected output: 1

JavaScript const statement:
const number = 42;
try {
number = 99;
} catch (err) {
console.log(err);
// expected output: TypeError: invalid assignment to const `number'
// Note - error messages will vary depending on browser
}
console.log(number);
// expected output: 42

JavaScript var statement:
var x = 1;
if (x === 1) {
var x = 2;
console.log(x);
// expected output: 2
}
console.log(x);
// expected output: 2

However, since the update, it is recommended for good practice not to use var and use const and let instead. Let is used when you know the value is going to change and const for other variables not changing value.
It is better to use const because it prevents the variable to be assigned to another value. If the value changes later on, you can replace the value to let.

Top comments (0)