JavaScript variables
JavaScript variables
Just like algebra
x=5
y=6
z=x+y
In algebra, we use letters (like x) to hold values (like 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.
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)
#JavaScript statements and JavaScript variables are case-sensitive.
JavaScript Data Type
JavaScript variables can also hold other data types, such as text values (name="Bill Gates").
In JavaScript, a text like "Bill Gates" is called a string.
JavaScript variables come in many types, but for now, we’ll just focus on numbers and strings.
When you assign a text value to a variable, you should surround the value with double or single quotes.
Do not use quotation marks when the value you assign to a variable is a numeric value. If you surround a numeric value with quotes, the value is treated as text.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <script> var pi=3.14; var name="Bill Gates"; var answer='Yes I am!'; document.write(pi + "<br>"); document.write(name + "<br>"); document.write(answer + "<br>"); </script> </body> </html>
Declaring (Creating) JavaScript Variables
Creating a variable in JavaScript is often called "declaring" a variable.
We use the var keyword to declare variables:
var carname;
After a variable is declared, 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 assign a value to a variable when you declare it:
var carname="Volvo";
In the following example, we create a variable named carname, assign it the value "Volvo", and then put it into the HTML paragraph with id="demo"
Warm reminder: a A good programming practice is to declare the required variables uniformly at the beginning of the code.
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";
The statement can also span multiple lines :
var lastname="Doe",
age=30,
job="carpenter";
var carname;
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <p>假设 y=5,计算 x=y+2,并显示结果。</p> <button onclick="myFunction()">点击这里</button> <p id="demo"></p> <script> function myFunction(){ var y=5; var x=y+2; var demoP=document.getElementById("demo") demoP.innerHTML="x=" + x; } </script> </body> </html>