A primer on understanding JavaScript's variables

  • 2020-07-21 06:50:06
  • OfStack

Variables are containers for storing information:


x=5; length=66.10;


Remember algebra in school?


When you think back to your algebra classes in school, you probably think of x=5, y=6, z=x+y, and so on.

Remember, 1 letter can hold 1 value (such as 5), and you can use the information above to calculate the value of z as 11.

You haven't forgotten, have you?

These letters are called variables and variables can be used to hold values (x=5) or expressions (z=x+y).


JavaScript variable


As in algebra 1, the JavaScript variable is used to hold values or expressions.

You can give a variable a short name, such as x, or a more descriptive name, such as length.

The JavaScript variable can also hold text values, such as carname="Volvo".

Rules for JavaScript variable names:


Variables are case sensitive (y and Y are two different variables)


Variables must begin with a letter or underscore


Note: Since JavaScript is case sensitive, variable names are case sensitive.


The instance


You can change the value of a variable during the execution of the script. You can refer to a variable by its name to display or change its value.

This example shows you how.


Declare (create) the JavaScript variable


Creating variables in JavaScript is often referred to as "declaring" variables.

You can declare the JavaScript variable with the var statement:


var x;
var carname;


Variables do not have values after the above declaration, but you can assign values to variables when you declare them:


var x=5;
var carname="Volvo";


Note: When assigning a text value to a variable, put the value in quotes.


Assign a value to the JavaScript variable


Assign a value to the JavaScript variable through an assignment statement:


x=5;
carname="Volvo";


The variable name is to the left of the = symbol, and the value to be assigned to the variable is to the right of the =.

After the above statement, the value saved in the variable x is 5, while the value of carname is Volvo.
Assign a value to the undeclared JavaScript variable


If the variable you assign has not been declared, the variable is automatically declared.

These statements:


x=5;
carname="Volvo";


The same effect as these statements:


var x=5;
var carname="Volvo";


Redeclare the JavaScript variable


If you declare the JavaScript variable again, it will not lose its original value.


var x=5;
var x;


After the above statement is executed, the value of the variable x is still 5. The value of x is not reset or cleared when the variable is redeclared.


JavaScript arithmetic


As with algebra 1, you can do the math using the JavaScript variable:


y=x-5;
z=y+5; 


Related articles: