Home >Web Front-end >JS Tutorial >Do JavaScript variables need to be declared?

Do JavaScript variables need to be declared?

青灯夜游
青灯夜游Original
2021-09-07 11:45:354830browse

In non-strict mode, JavaScript allows direct assignment of variables without declaring them. This is because the JavaScript interpreter can automatically declare variables implicitly. In strict mode, variables must be declared before they can be used.

Do JavaScript variables need to be declared?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

A variable is equivalent to a container, and its value is equivalent to what is contained in the container. The variable name is the label attached to the container. The variable can be found through the label so that the value it stores can be read and written.

Do JavaScript variables need to be declared?

  • In strict mode, variables must be declared before they can be used.

  • In non-strict mode, JavaScript allows direct assignment of variables without declaring them. This is because the JavaScript interpreter can automatically declare variables implicitly. Implicitly declared variables are always used as global variables.

Declaring variables

In JavaScript, declare variables using the var statement.

Example 1

In a var statement, you can declare one or more variables, or assign values ​​to variables. Unassigned variables are initialized to undefined (undefined) values. When declaring multiple variables, they should be separated using the comma operator.

var a;  //声明一个变量
var a,b,c;  //声明多个变量
var b = 1; //声明并赋值
document.write(a);  //返回 undefined
document.write(b);  //返回 1

Example 2

In JavaScript, you can declare the same variable repeatedly, or you can initialize the value of the variable repeatedly.

var a = 1;
var a = 2;
var a = 3;
document.write(a);  //返回 3

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of Do JavaScript variables need to be declared?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn