A variable is a container for storing information.
Instance
var x=2;var y=3;var Z=x+y;
It's like algebra.
X=2y=3z=x+y
In algebra, we use letters (such as x) to hold values (such as 2).
By the above expression Z=x+y, we can calculate the value of Z as 5.
In JavaScript, these letters are called variables.
Tip: You can think of variables as containers for storing data.
JavaScript variables
Like algebra, JavaScript variables can be used to hold values (such as x=2) and Expressions (z=x+y).
Variables can use short names (x and y) or a better descriptive name (such as age sum total)
Variables must start with a letter
Variables can also start with the ¥ and _ symbols (but we don't recommend this)
Variable names are case sensitive
JavaScript Data types
JavaScript variables can also hold other data types, such as text values (name = "Bill Gates").
A text like "Bill Gates" in JavaScript is called a string
There are many types of JavaScript variables when you assign text values to variables, you should enclose the value in double or single quotes. Values are not required.
var pi=3.14;var name= "Bill Gates"; var answer= ' Yes I am! ';
Declaring the creation of JavaScript variables
We use the keyword var to declare variables
var name = "Bill Gates";
In the following example, we create a variable named Carname and assign it a value of "Volvo" and put it in an HTML paragraph id= "Demo":
<id= "Demo"></p>var carname= "Volvo"; document.getElementById ("Demo"). Innerhtml=carname;
A good programming habit is to declare the required variables uniformly at the beginning of the code.
You can also declare many variables in a single statement the statement starts with VAR and separates the variables with commas.
var name = "Bill", age = +, job = "CEO";
Value = undefined
In computer programs, variables that are not valued are often declared. A variable that is not declared with a value, whose value is actually undefined.
After the following statement has been executed, the value of the variable carname will be undefined:
var carname;
Re-declaring JavaScript variables
If you re-declare a JavaScript variable, the value of the variable is not lost
var carname= "Volvo"; var carname;
JavaScript arithmetic
You can use JavaScript variables to do arithmetic using the operators such as = and +.
Example
y=5;x=y+2;
HTML Learning Note JavaScript (variable)