What are the 4 ways to declare variables in javascript
Four ways to declare variables in JavaScript: 1. Use "var" to declare variables, such as "var a;"; 2. Use "function" to declare variables, such as "function Fun (num) {}"; 3. Use "let" to declare variables; 4. Use "const" to declare variables.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
How to declare variables
There are several ways to declare variables in JavaScript:
- Before ES6, it was var and function
- New in ES6 Is adding let and const
function a way to declare variables?
Let’s verify it
Verification method one:
function repeatFun (num) { return num; } repeatFun(10); // 10 var repeatFun = 1; repeatFun(2); // Uncaught TypeError: repeatFun is not a function
This method uses var to repeatedly declare variables, but the latter will overwrite the former feature
Let’s take a look at what happened here:
- First, a function is declared, his name is repeatFun
- , and then called once, the result is 10
- After that, repeatFun is declared again with var, and initialized to 1
- The function repeatFun is called one last time
- The result is an error, content: repeatFun is not a function
According to the execution results, we can infer that there is a repeatFun variable in the browser's memory. It was a function before and was later redeclared by a var keyword and initially changed to 1.
Verification method two:
{ let repeatFun = 1; function repeatFun (num) { return num } } // Uncaught SyntaxError: Identifier 'repeatFun' has already been declared
The second method is to use a syntax of
ES6: using the feature of let that cannot be declared repeatedly to prove that function is also a declared variable The difference between
var, let and const:
-
Variable declaration promotion
- var has variable declaration promotion Functions can be used first and then declared, and vice versa.
- let and const do not have the function of variable declaration promotion. They must be declared first before they can be used.
-
Repeated declaration
- var can be declared repeatedly, and the latter covers the former
- let and const cannot be repeatedly declared
-
scope The scope of
- var's scope is bounded by functions
- let and const are block scope
- var can define global variables and local variables, let and const can only define local variables
-
The special thing about const
- cannot be modified after declaration (there are some differences in the behavior of reference types and basic types) Different)
Variable declaration promotion
- var has the function of variable declaration promotion, which can be used first and then declared
- let and const do not have the function of variable declaration promotion. They must be declared first before they can be used.
Example 1, verify var variable promotion:
var b = a + 1; // b: NaN var a = 1; // a: 1
First, declare it A variable b is initially recognized, and the initialized value is a 1 (what is the value of a?) <br> Then a variable a is declared, and the initial recognition is 1 <br> This is what the code looks like on the surface When doing these things, what is actually done is this:
- Every time a variable is declared, their declaration is placed at the top of the code, and they are all performed once Initialization, the value is: undefined, but the assignment position will not change,
- Then perform other operations
The following writing method can also achieve the same effect
var b; var a; b = a +1; // b: NaN a = 1; // a: 1
let and const behave differently from var
Example 2, verify whether there is variable promotion in let:
let b = a + 1; // Uncaught ReferenceError: a is not defined let a = 1;
A scope error will be thrown directly when running. If you change it like this, There is no error:
let a = 1; // a: 1 let b = a + 1; // b: 2
const and let perform the same in terms of variable promotion
Duplicate declaration
- var can be declared repeatedly, and the latter overrides The former
-
let and const cannot be declared repeatedly
Example 1, verify the repeated declaration of var:
var a = 1; var a = 2; var b = a + 1; // 3
- First, declare the variable a, initialized as 1
- Then declare variable a again, initialized to 2
- Finally declare variable b, its initial value is a 1
Example 2, verify the repetition of let Statement:
let a = 1; let a = 2; // Uncaught SyntaxError: Identifier 'a' has already been declared
var a = 1; let a = 2; //Uncaught SyntaxError: Identifier 'a' has already been declared
- Obviously, variables declared using let in the same execution environment cannot be declared repeatedly, otherwise an error will be thrown <br> const and let behave the same in terms of repeated declarations
The scope of the scope
- The scope of var is bounded by the function
- let and const are Block scope
- var can define global variables and local variables, let and const can only define local variables
encapsulates a factorial function as an example, without using tail recursion, just use for Implementation with if <br> Example 1, factorial function verifies the scope:
var num = 5; function factorial(num) { var result = 1,resultValue = 0; for (let i = num - 1; i >= 1; i--) { if (i === num - 1) { resultValue = num * i; }else{ resultValue = num * i / num; } result *= resultValue; } // i 是用 let 进行定义它的作用域仅仅被限制在 for 循环的区域内 // i++;// Uncaught ReferenceError: i is not defined return result; } // result 是用 var 进行定义,他的活动区域在 factorial 函数内 // result++; // var的作用域.html:34 Uncaught ReferenceError: result is not defined factorial(num); // 120
const behaves the same as let in the scope
Example 2, verifies const Scope:
{ const NUM_1 = 10; } let b = NUM_1 + 1; // Uncaught ReferenceError: NUM_1 is not defined
Example 3, verify that var can define global variables, let and const can only define local variables
// 可以挂载到全局作用域上 // var name = 'window scoped'; let name = 'let scoped'; //是不挂载到全局作用域中 let obj = { name: 'myName', sayName () { return function () { console.log(this.name); // 打印出来为空 }; } } obj.sayName()(); console.log(window); //name 这个属性的值没有,如下图
若这样改一下就可以得到我们想要的值:
- 把用 var 定义的 name 的代码取消注释,把用 let 定义的 name 的代码注释。
这个同时也涉及到新问题 this 的指向。后面的文章再详细举例验证
const 的特殊之处
const 与 let , var 其实还是有些地方不一样的
例子1:验证 const 的特殊之处(一)<br>
const NUM = 100; NUM = 1000; // Uncaught TypeError: Assignment to constant variable
- 经过 const 方式进行声明,之后赋值完毕,则不可以进行改变,否则会报错
但是也有例外
例子二:验证 const 的特殊之处(二)
const obj = { name: 'xiaoMing', sayName () { return this.name } }; obj.sayName(); // xiaoMing obj.name = 'xiaoHong'; obj.sayName(); // xiaoHong
- 使用 const 首先声明一个变量 obj , 并且这个变量指向我们在内存中创建的对象,你会发现我们改变里面的属性是没有任何问题
若这样改一下: <br> 例子三:验证 const 的特殊之处(三)
const obj = { name:'xiaoMing', sayName(){ return this.name } }; obj = {}; // Uncaught TypeError: Assignment to constant variable
- 若改变该变量的指向的对象,则就会报错。这种错误和 「 验证 const 的特殊之处(一)」的错误是一样的
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of What are the 4 ways to declare variables in javascript. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Linux new version
SublimeText3 Linux latest version