JavaScript variables
JavaScript variable declaration
JavaScript variables are used to store characters, numbers, arrays, and even object resources, etc., so that they can be used where we need them.
Declare (create) a variable through the var keyword:
var variable name;
JavaScript variable naming rules
Variable names start with letters (a-z, A-Z) or underscores _, and can be followed by any letters or numbers and underscores, but not spaces. Additionally, variable names are case-sensitive.
The following variable names are valid:
var_char
varChar
_varChar
char5
Tip
# Regarding variable naming, we recommend that the variable name should be a combination that indicates its actual semantics, such as my_name or myName format.
JavaScript variable assignment
You can assign a value to a variable while declaring it:
var my_name = "Jack"; // Text character variable, enclosed in double quotes
var number = 2; // Numeric variable
In fact, JavaScript also supports directly assigning variables Assign a value without declaring the variable in advance:
my_name = "Jack";
number = 2;
The assigned variable will be automatically declared, But declaring a variable in advance is a good programming habit.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script type="text/javascript"> var a = 3; var b = 4+a; window.alert(b); </script> </head> <body> </body> </html>
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";
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;
JavaScript arithmetic
You can do arithmetic with JavaScript variables, using operators like = and +:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script type="text/javascript"> var a = 3; var b = 4+a; window.alert("b =" + b); </script> </head> <body> </body> </html>