search
HomeWeb Front-endJS TutorialTips and traps that js beginners should know

Tips and traps that js beginners should know

Jun 21, 2017 am 09:39 AM
javascriptjsSimple

Here are some tips and pitfalls that Javascript beginners should know. If you're already an expert, brush up on this.

Javascript is just a programming language. How could it possibly go wrong?

1. Have you ever tried to sort a set of numbers?

Javascript's sort() function sorts alphanumeric (String Unicode code points) by default.

So [1,2,5,10].sort() will output [1, 10, 2, 5].

To correctly sort an array, you can use [1,2,5,10].sort((a, b) => a — b)

A very simple solution Solution, the premise is that you have to know that there is such a pit

2. new Date() is great

new Date() Acceptable:

  • No parameters: Returns the current time

  • One parameter x: Returns January 1, 1970 + x milliseconds. Those who know Unix know why.

  • new Date(1, 1, 1) returns 1901, February, 1st\. Because, the first parameter represents 1900 plus 1 year, the second parameter represents the second month of this year (so February) — People with normal brain circuits will start indexing from 1 — , and the third parameter is very Obviously it's the first day of the month, so 1 — sometimes the index does start at 1 — .

  • new Date(2016, 1, 1) will not add 2016 to 1900. It only represents 2016.

3. Replace does not "replace"

let s = "bob"const replaced = s.replace('b', 'l')
replaced === "lob"
s === "bob"

I think this is a good thing because I don't like function changes their input. You should also know that replace will only replace the first matching string:

If you want to replace all matching strings, you can use it with the /g flag Regular expression:

"bob".replace(/b/g, 'l') === 'lol' // 替换所有匹配的字符串

4. When comparing, please pay attention to

// These are ok'abc' === 'abc' // true1 === 1         // true// These are not
[1,2,3] === [1,2,3] // false
{a: 1} === {a: 1}   // false
{} === {}           // false

Reason: [1,2,3] and [1,2,3] are two independent arrays. They just happen to contain the same value. They have different references and cannot be compared with ===.

5. Array is not a primitive data type

typeof {} === 'object'  // truetypeof 'a' === 'string' // truetypeof 1 === number     // true// But....typeof [] === 'object'  // true

If you want to know if your variable is an array, you can still use Array.isArray(myVar)

6. Closure

This is a well-known 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

Do you think it will output 0, 1, 2...? Do you know why it doesn't output like this? How would you modify it so that it outputs 0, 1, 2...?

There are two possible solutions here:

Replace var with let. Boom. Solved.

# The difference between

##let and var is the scope. The scope of var is the nearest function block, and the scope of let is the nearest enclosing block. The enclosing block can be smaller than the function block (if it is not in any block, then let and var are both global). (Source)

Alternative Method: Use

bind:

Greeters.push(console.log.bind(null, i))

There are many other ways. These are just my two top picks

7. Speaking of bind

what do you think this will 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 think this program will crash and prompt

Cannot read property 'name' of undefined, give you one point.

Cause:

greet is not running in the correct context. Again, there are still many solutions to this problem.

I personally like

asyncGreet () {this.someThingAsync()
.then(this.greet.bind(this))
}

This ensures that the instance of the class is called as the context

greet.

If you think

greet should not run outside the instance context, you can bind it in the class's constructor:

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

You should also know about arrow functions (

=> ) can be used to preserve context. This method will also work:

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

Although I think the last method is not elegant.

I'm glad we solved this problem.

Summary

Congratulations, you can now safely put your program on the Internet. It might not even run wrong (but it usually does) Cheers \o/

If there's anything else I should mention, please let me know!

The above is the detailed content of Tips and traps that js beginners should know. 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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

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.

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.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version