Home >Web Front-end >JS Tutorial >Introduction to JavaScript variables (with code)

Introduction to JavaScript variables (with code)

不言
不言forward
2019-03-05 15:00:352850browse

This article brings you an introduction to JavaScript variables (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Just like algebra, JavaScript variables are used to hold values ​​or expressions.

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

JavaScript variables 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 start with a letter or an underscore

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

Declare (Create) JavaScript Variables

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

You can declare JavaScript variables through the var statement:

var x;
var carname;

After the above declaration, the variables have no value, but you can assign values ​​to the variables while declaring them. :

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

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

Assigning values ​​to JavaScript variables

Assigning values ​​to JavaScript variables through assignment statements:

x=5;
carname="Volvo";

The variable name is on the left side of the = symbol, and you need to assign to the variable The value of is to the right of =.

After the above statement is executed, the value saved in the variable x is 5, and the value of carname is Volvo .

Assigning a value to an undeclared JavaScript variable

If the variable you assign a value has not been declared, it will be automatically declared.

These statements:

x=5;
carname="Volvo";

Have the same effect as these statements:

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

Redeclare JavaScript variables

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

var x=5;
var x;

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

The above is the detailed content of Introduction to JavaScript variables (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete