JavaScript variables
Just like algebra
x=5
y=6
z=x+y
In algebra , we use letters (such as x) to hold values (such as 5).
Through the above expression z=x+y, we can calculate the value of z to be 11.
In JavaScript, these letters are called variables.
Note: You can think of variables as containers for storing data.
JavaScript Variables
Like algebra, JavaScript variables can be used to store Values (such as x=5) and expressions (such as z=x+y).
Variables can use short names (such as x and y) or more descriptive names (such as age, sum, totalvolume).
Variables must start with a letter
Variables can also start with $ and _ symbols (but we do not recommend this)
Variable names are case-sensitive (y and Y are different variables)
Note: JavaScript statements and JavaScript Variables are case-sensitive.
Declaring (creating) JavaScript variables
Creating variables in JavaScript is usually called "declaring" a variable.
We use the var keyword to declare variables:
var carname;
Variable declaration After that, the variable is empty (it has no value).
To assign a value to a variable, use the equal sign:
carname="Volvo";
However, you can also declare a variable when Assign a value to it:
var carname="Volvo";
In the following example, we create a variable named carname and assign it the value "Volvo" ", and then put it into the HTML paragraph with id="demo":
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>PHP中文网(php.cn)</title> </head> <body> <p>点击这里来创建变量,并显示结果。</p> <button onclick="myFunction()">点击这里</button> <p id="demo"></p> <script> function myFunction(){ var carname="Volvo"; document.getElementById("demo").innerHTML=carname; } </script> </body> </html>
Run and try it
One statement, multiple variables
You can declare many variables in one statement. The statement starts with var and uses commas to separate variables:
var lastname="Doe", age=30, job="carpenter";
Statement It can also span multiple lines:
var lastname="Doe",
age=30,
job="carpenter";
Value = undefined
In computer programs, variables without value are often declared. The value of a variable declared without a value is actually undefined.
After executing the following statement, the value of variable carname will be undefined:
var carname;