Home>Article>Web Front-end> How to define variables in JavaScript
This article will give you a detailed introduction to the method of defining variables in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
var messageAsBoolean = "HHO";
How to define variables
var message = "qqqq"; message = "qqqq" let message = "qqqq"; const message = "aaaaa";
var Defining variables will automatically be promoted to the top scope, let The defined variables will not be promoted to the first line
function a() { console.log(a); // 不会报错,a作用域会自动提升至顶行,内容为 undefined var a = "aaaaaa"; }
Equivalent to:
function a() { var a; console.log(a); a = "aaaaaa"; }
The scope of variables declared by let and var
The scope of variables declared by let is block scope Domain
function fun() { //函数块作用域的开始 if(true){ //if语句块作用域的开始 } //if语句块作用域的结束 } //函数块作用域的结束
The variable scope declared by ˆvar is the function scope
function fun(){ //函数作用域的开始 } //函数作用域的结束
Global declaration method
/* 1. 不使用 let、var等修饰,直接定义的变量 */ message = "aaaaaaaa"; /* 2. 在全局变量区申请的变量 */ var message = "aaaaaa"; let message = "aaaaa"; /* 注: js 文件的开始部分,不在任何函数内 */
Conditional declaration
The variable defined by ˆvar will increase the value At the top of the function, duplicate definitions will be replaced*/
function fun(){ var name = "lili"; if(true){ var name = "hho"; //不会报错,代码类似name = "hho"; console.log(name); //打印结果为hho } console.log(name); //打印结果为hho }
Let-defined variables will not be promoted to the top of the function
function fun(){ let name = "lili"; if(true){ let name = "hho"; //新定义变量name console.log(name); // 打印结果为hho } console.log(name); // 打印结果为lili }
const-defined variables
Defined variables The attributes are similar to let, but the variable value defined by const cannot be modified
const name = "hho"; //只可使用,不可修改name变量的值
The scope of the defined variable is the block scope, the same as let
The variable defined by const must be initialized
const name; // 报错
【Recommended learning:javascript advanced tutorial】
The above is the detailed content of How to define variables in JavaScript. For more information, please follow other related articles on the PHP Chinese website!