search
HomeWeb Front-endJS TutorialMy NodeJs learning summary (1)_node.js

In this first article, let’s talk about some programming details of NodeJs.

1. Traverse the array

for (var i=0, l=arr.length; i<l; i++)

One advantage of writing this way is that each loop saves one step to obtain the length of the array object. The longer the array length, the more obvious the value.

2. Determine whether the variable is true or false

if (a) {...} //a='', a='0', a=[], a={}

The results of if conditional judgment are: false, true, true, true. This result is different from PHP's result, don't be confused. It is also necessary to distinguish between situations where it is similar to non-identity judgments.

3. Judgment of non-identity of 0 value

1 if (0 == '0') {...} //true
2 if (0 == []) {...} //true
3 if (0 == [0]) {...} //true
4 if (0 == {}) {...} //false
5 if (0 == null) {...} //false
6 if (0 == undefined) {...} //false

In fact, there are many such weird judgments, I only listed the more common ones. If you want to understand the rules, please refer to my other blog post: [JavaScript] In-depth analysis of JavaScript’s relational operations and if statements.

4. The trap of parseInt

var n = parseInt(s); //s='010'

After this statement is executed, the value of n is 8, not 10. Although many people know this, mistakes are inevitable in programming, and I know it very well. Therefore, it is best to write in the following way and you will not make mistakes.

var n = parseInt(s, 10);

5. Variables must be declared before use

Although there is no error in using variables directly without declaring them, writing this way is very error-prone. Because the interpreter will interpret it as a global variable, it can easily have the same name as other global variables and cause errors. Therefore, we must develop a good habit of declaring variables before using them.

6. There is asynchronous situation in the loop

for (var i=0, l=arr.length; i<l; i++) {
   var sql = "select * from nx_user";
  db.query(sql, function(){
    sys.log(i + ': ' + sql);
  }); //db.query为表查询操作,是异步操作
}

You will find that the output results are the same, and they are the output content when i=arr.length-1. Because JavaScript is single-threaded, it will first execute the synchronous content of the entire loop before executing the asynchronous operations. The anonymous callback function in the code is an asynchronous callback. When this function is executed, the for loop and some subsequent synchronization operations have been completed. Due to the closure principle, this function will retain the contents of the sql variable and i variable in the last loop of the for loop, so it will lead to wrong results.

So what should we do? There are two solutions. One is to use an immediate function, as follows:

for (var i=0, l=arr.length; i<l; i++) {
  var sql = "select * from nx_user";
  (function(sql, i){
    db.query(sql, function(){
      sys.log(i + ': ' + sql);
    }); //db.query为表查询操作,是异步操作
  })(sql, i);
}

Another method is to extract the asynchronous operation part and write a function as follows:

var outputSQL = function(sql, i){
   db.query(sql, function(){
      sys.log(i + ': ' + sql);
  }); //db.query为表查询操作,是异步操作
}

for (var i=0, l=arr.length; i<l; i++) {
  var sql = "select * from nx_user";
  outputSQL(sql, i); 
}


7. When processing large amounts of data, try to avoid nested loops.

Because the processing time of nested loops will increase exponentially as the amount of data increases, it should be avoided as much as possible. In this situation, if there is no better way, the general strategy is to trade space for time, that is, to establish a Hash mapping table of secondary cyclic data. Of course, specific circumstances must be analyzed on a case-by-case basis. Another point to mention is that some methods themselves are a loop body, such as Array.sort() (this method should be implemented using two layers of loops), so you need to pay attention when using it.

8. Try to avoid recursive calls.

The advantage of recursive calling is that the code is concise and the implementation is simple, but its disadvantages are very important and are explained as follows:

(1) The size of the function stack will grow linearly with the recursion level, and the function stack has an upper limit. When the recursion reaches a certain number of levels, the function stack will overflow, causing program errors;

(2) Each recursive level will add additional stack push and pop operations, that is, saving the scene and restoring the scene during the function call.

Therefore, recursive calls should be avoided as much as possible.

9. Regarding scope isolation of module files.

When Node compiles the JavaScript module file, its content has been packaged head and tail, as follows:

(function(exports, require, module, __filename, __dirname){
  你的JavaScript文件代码
});

This allows scope isolation between each module file. Therefore, when you write NodeJs module files, you do not need to add a layer of scope isolation encapsulation yourself. The following code format only adds an extra layer of function calls, which is not recommended:

(function(){
  ... ...
})();

10. Don’t mix arrays and objects

The following is an example of an error code:

var o = [];
o['name'] = 'LiMing';

Mixing arrays and objects may lead to unpredictable errors. One of my colleagues encountered a very strange problem. Let’s look at the code first:

var o = [];
o['name'] = 'LiMing';
var s = JSON.stringify(o);

He originally thought that the name attribute of object o would be in the JSON string, but the result was that it was not. I was also very surprised at the time, but I had a hunch that it was a problem of mixing arrays and objects. I tried it and it turned out to be the problem. Later, I found out in the ECMA specification that arrays are serialized according to JA rules. Therefore, it is necessary to develop a good programming habit, use arrays and objects correctly, and do not mix them.

11. Elegant Promise Programming

I believe anyone who has come into contact with nodeJs has had this experience. When asynchronous callbacks are nested within asynchronous callbacks, the code becomes confusing and lacks readability. This dilemma of nodeJs can be overcome with the help of promises. Promise is like a carver, making your code elegant and beautiful. Promise has an A specification, and there are several implementation methods online, you can refer to it.

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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

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.

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment