Variables in JavaScript
Variables in JavaScript are commonly declared by using a var
keyword, followed by a variable name, assignment operator (equals sign =
), and a corresponding value. For example, a variable of type int
is declared as follows.
1var number = 10;
Since this code line was a statement, it will produce no output. It only created the variable number
in memory and assigned it the value 10
. To check if the value was stored in the variable number
, we use console.log()
, which displays the variable value on the console.
1var number = 10;
2console.log(number);
This will display the value 10
, and we can see that the value was correctly assigned.
Note! We can declare variables in JavaScript without using the
var
keyword before the variable name as well. However, in that case, the variable, regardless of where you define it, will become aglobal variable
.
Interesting! Let's explore further.
A
global variable
means that they can be accessed anywhere in the program-- that is, they can also be modified anywhere in the program (inside functions and classes, which we'll learn about in the next lessons). This may lead to a change in the value of the variable in places where you don't want to change it. Hence, to ensure that this does not happen, JavaScript provides additional keywords to declare variables. Sincevar
keyword is more prone to errors, there are two other keywordslet
andconst
that can also be used for variable declaration.