search
HomeWeb Front-endJS TutorialAnalyzing 8 common pitfalls in JavaScript

Analyzing 8 common pitfalls in JavaScript

8 Common Traps in JavaScript

Share:

Translator Note: In the long journey of programming, there are always some pitfalls that will make you burst into tears.

English original: Who said javascript was easy?

Translator: Fundebug

Here we give some tips and list some pitfalls for JavaScript beginners. If you are already a bricklayer, you can also read it.

1. Have you tried sorting the array elements?

JavaScript uses alphanumeric order by default. Therefore, the result of [1,2,5,10].sort() is [1, 10, 2, 5].

If you want to sort correctly, you should do this: [1,2,5,10].sort((a, b) => a - b)

2. new Date() is very easy to use

The usage methods of new Date() are:

Does not receive any parameters: returns the current time; receives a parameter x: returns January 1, 1970 x milliseconds value. new Date(1, 1, 1) returns February 1, 1901. However..., new Date(2016, 1, 1) will not add 2016 to 1900, but only represents 2016.

3. The replacement function does not really replace?

let s = "bob"
const replaced = s.replace('b', 'l')
replaced === "lob" // 只会替换掉第一个b
s === "bob" // 并且s的值不会变

If you want to replace all b, use regular expressions:

"bob".replace(/b/g, 'l') === 'lol'

4. Be careful with comparison operations

// 这些可以'abc' === 'abc' // true1 === 1 // true// 然而这些不行[1,2,3] === [1,2,3]
 // false{a: 1} === {a: 1} // false{} === {} // false

Because [1,2,3] and [1,2,3] are two different arrays, but their elements happen to be the same. Therefore, it cannot be judged simply by ===. ·

5. Array is not a basic type

typeof {} === 'object' // true
typeof 'a' === 'string' // true
typeof 1 === number // true
// 但是....
typeof [] === 'object' // true

If you want to determine whether a variable var is an array, you need to use Array.isArray(var).

6. Closure

This is a classic JavaScript interview question:

const Greeters = []
for (var i = 0 ; i < 10 ; i++) {
Greeters.push(function () { return console.log(i) })
}
Greeters[0]() // 10
Greeters[1]() // 10
Greeters[2]() // 10

Although it is expected to output 0,1,2,..., it actually does not. Do you know how to debug?
There are two methods:

Use let instead of var. Note: You can refer to another blog of Fundebug. Can "let" replace "var" in ES6? Use the bind function. Note: You can refer to Fundebug’s other blog. A must-read for JavaScript beginners is “this” Greeters.push(console.log.bind(null, i))

Of course, there are many solutions. These two are my favorite!

7. About bind

What will the following code output?

class Foo {
    constructor(name) {
        this.name = name
    }
    greet() {
        console.log(&#39;hello, this is &#39;, this.name)
    }
    someThingAsync() {
        return Promise.resolve()
    }
    asyncGreet() {
        this.someThingAsync().then(this.greet)
    }
}
new Foo(&#39;dog&#39;).asyncGreet()

If you say that the program will crash and report an error: Cannot read property ‘name’ of undefined.

1. Because the geet on line 16 is not executed in the correct environment. Of course, there are many ways to solve this BUG!

I like to use the bind function to solve the problem:

//code from http://caibaojian.com/8-javascript-attention.html
asyncGreet () {
this.someThingAsync()
.then(this.greet.bind(this))
}

This will ensure that greet will be called by the instance of Foo, not this of the local function.

2. If you want greet to never be bound to the wrong scope, you can use bind in the constructor.

class Foo {
    constructor(name) {
        this.name = name this.greet = this.greet.bind(this)
    }
}

3. You can also use arrow functions (=>) to prevent the scope from being modified. Note: You can refer to Fundebug's other blog "Arrow Function", a must-read for JavaScript beginners.

asyncGreet() {
    this.someThingAsync().then(() = >{
        this.greet()
    })
}

8. Math.min() is larger than Math.max()

Math.min() < Math.max() // false

Because Math.min() returns Infinity, and Math.max()Return -Infinity.

Recommended tutorial: "js basic tutorial"

The above is the detailed content of Analyzing 8 common pitfalls in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:webhek. If there is any infringement, please contact admin@php.cn delete
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)