In this lesson, we will learn about JavaScript variables and constants, how they work, and see examples of how to initialize them and use them.
Javascript Variables
Variables are dynamic in JavaScript, there are names associated with values and they may be reallocated in the program to values of different types: numbers, strings, arrays, etc. A variable must have a unique name.
In Javascript, variables are declared with either the var
or let
keyword. For example,
let x ;
var y ;
In the above example, x
and y
are variables.
let keyword
A variable defined using a let
the statement is only known in the block it is defined in, from the moment it is defined onward. Variables declared using the let keyword are block-scoped, which means that they are available only in the block in which they were declared and not outside.
The assignment operator =
is used to assign a value to a variable.
let x ;
x = 10 ;
let y = 10 ;
Here, in the First scenario variable x is initialized and then a value of 10 is assigned to it. Before the value is assigned to the variable, it will have undefined
value. In the second scenario, a value of 10 is assigned to the variable y
during its initialization.
In javascript, we can declare multiple variables in a single statement.
let x = 1 , y = 2 , z = 3 ;
You can change the value of a variable declared using the let
keyword.
let x = 1 ;
console.log(x) ; // 1
x = 5 ;
console.log(x) ; // 5
Here, the variable x
is assigned a value of 1 and then the same variable x is assigned a value of 5;
JavaScript Constants
Constants are block-scoped, much like variables declared using the let
keyword. Constants cannot have their value changed by assigning them or redeclaring them. The keyword const
is used to declare a variable constant. By convention, the constant identifiers are in uppercase. For example,
const NUM = 5;
Here, the value of 5 is assigned to the constant NUM
whose value cannot be changed or redeclared in the same block where it is assigned.
const NUM = 5 ;
console.log(NUM); // 5
NUM = 6 ; // Error
The above code return error as we are trying to reassign the value of the constant.
While declaring a constant its value should be assigned at the time of initialization. Otherwise, it will return an error.
const NUM;
NUM = 5 ; // Error
Conclusion
In this article, you have learned how to declare and use variables and constants.