Home > Web Front-end > JS Tutorial > body text

Do JavaScript variables need to be declared?

青灯夜游
Release: 2022-10-10 16:21:10
Original
4797 people have browsed it

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
Copy after login

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
Copy after login

[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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template