search
HomeWeb Front-endJS TutorialWhat are the details that need to be paid attention to in Javascript?

1. Use === instead of ==
JavaScript uses 2 different equality operators: ===|!== and ==|!=, in comparison operations Using the former is best practice.
"If the operands on both sides have the same type and value, === returns true, !== returns false." - JavaScript: Language Essence
However, when using == and! =, you may encounter a situation where the types are different. In this case, the types of the operands will be forced to be the same and then compared, which may not be the result you want.
2.Eval == Evil
When not familiar at first, "eval" gives us access to the JavaScript compiler (Annotation: This seems very powerful). Essentially, we can pass a string to eval as a parameter while executing it.
Not only does this greatly reduce the performance of the script (Annotation: The JIT compiler cannot predict the content of the string and cannot precompile and optimize), but it also brings huge security risks, because the text to be executed is too large. High authority, stay away.

3. Omission may not save trouble
Technically, you can omit most curly braces and semicolons. Most browsers will understand the following code correctly:

if(someVariableExists) 
    x = false

Then, if it looks like this:

if(someVariableExists) 
   x = false 
   anotherFunctionCall();

one might think the above The code is equivalent to the following:

if(someVariableExists) { 
   x = false; 
   anotherFunctionCall(); 
}

Unfortunately, this understanding is wrong. The actual meaning is as follows:

if(someVariableExists) { 
   x = false; 
} 
anotherFunctionCall();

You may have noticed that the indentation above easily gives the illusion of curly braces. Justifiably so, this is a terrible practice and should be avoided at all costs. There is only one case in which the curly braces can be omitted, that is, when there is only one line, but this is controversial.

if(2 + 2 === 4) return 'nicely done';

Plan Ahead
Chances are, one day you will need to add more statements to the if statement block. In this case, you must rewrite this code. Bottom line – omissions are a minefield.

4. Place the script at the bottom of the page
Remember - the primary goal is to make the page presented to the user as quickly as possible. The inclusion of the script is blocking. The browser cannot continue to render the following content until it is loaded and executed. Therefore, users will be forced to wait longer.
If your js is only used to enhance the effect-for example, a button click event-put the script immediately before the end of the body. This is definitely best practice.

5. Avoid declaring variables within a For statement
When executing a lengthy for statement, keep the statement block as concise as possible, for example:
Oops:

for(var i = 0; i 

Note that each loop must calculate the length of the array, and each time it must traverse the dom to query the "container" element - the efficiency is seriously low!
Suggestion:

var container = document.getElementById('container'); 
for(var i = 0, len = someArray.length; i 


6. The best way to construct a string
When you need to iterate over an array or object, don’t Always think of "for" statements, be creative, you can always find a better way, for example, like below.

var arr = ['item 1', 'item 2', 'item 3', ...]; 
var list = '
  • ' + arr.join('
  • ') + '
';

I am not your god, but please believe me (if you don’t believe it, test it yourself) - this is by far the fastest method!
Using native code (such as join()), regardless of what the system does internally, is usually much faster than non-native.

7. Reduce global variables
As long as multiple global variables are organized under one namespace, it will significantly reduce the interaction with other applications, components or classes. The possibility of bad interaction between libraries "——Douglas Crockford

var name = 'Jeffrey'; 
var lastName = 'Way'; 
function doSomething() {...} 
console.log(name); // Jeffrey -- 或 window.name// 更好的做法var DudeNameSpace = { 
   name : 'Jeffrey', 
   lastName : 'Way', 
   doSomething : function() {...} 
} 
console.log(DudeNameSpace.name); // Jeffrey

Note: This is simply named "DudeNameSpace", which should be more reasonable in practice. name.

8. Add comments to the code
It seems unnecessary, but please believe me, try to add more reasonable comments to your code. When you look back at your project a few months later, you may not remember your original thoughts. Or what if one of your colleagues needs to make changes to your code? All in all, adding comments to your code is an important part.

// 循环数组,输出每项名字(译者注:这样的注释似乎有点多余吧)for(var i = 0, len = array.length; i 


9. Embrace progressive enhancement
Ensure smooth degradation when javascript is disabled. We're always tempted to think, "Most of my visitors already have JavaScript enabled, so I don't have to worry." However, this is a big misconception.
Have you ever taken a moment to see what your beautiful page looks like with javascript turned off? (This is easy to do by downloading the Web Developer tool (Translator's Note: Chrome users download it in the app store, IE users set it in Internet Options)), but this may break your website. As a rule of thumb, design your site assuming JavaScript is disabled, and then, based on that, gradually enhance your site.

10. Do not pass string parameters to "setInterval" or "setTimeout"
Consider the following code:

setInterval( 
"document.getElementById('container').innerHTML += 'My new number: ' + i", 3000 );

不仅效率低下,而且这种做法和"eval"如出一辙。从不给setInterval和setTimeout传递字符串作为参数,而是像下面这样传递函数名。

setInterval(someFunction, 3000);

11.不要使用"with"语句
乍一看,"with"语句看起来像一个聪明的主意。基本理念是,它可以为访问深度嵌套对象提供缩写,例如……

with (being.person.man.bodyparts) { 
   arms = true; 
   legs = true; 
}

而不是像下面这样:

being.person.man.bodyparts.arms = true; 
being.person.man.bodyparts.legs= true;

不幸的是,经过测试后,发现这时“设置新成员时表现得非常糟糕。作为代替,您应该使用变量,像下面这样。

var o = being.person.man.bodyparts; 
o.arms = true; 
o.legs = true;

12.使用{}代替 new Ojbect()
在JavaScript中创建对象的方法有多种。可能是传统的方法是使用"new"加构造函数,像下面这样:

ar o = new Object(); 
o.name = 'Jeffrey'; 
o.lastName = 'Way'; 
o.someFunction = function() { 
   console.log(this.name); 
}

然而,这种方法的受到的诟病不及实际上多。作为代替,我建议你使用更健壮的对象字面量方法。
更好的做法

var o = { 
   name: 'Jeffrey', 
   lastName = 'Way', 
   someFunction : function() { 
      console.log(this.name); 
   } 
};

注意,果你只是想创建一个空对象,{}更好。
13.使用[]代替 new Array()
这同样适用于创建一个新的数组。
例如:

var a = new Array(); 
a[0] = "Joe"; 
a[1] = 'Plumber';// 更好的做法:var a = ['Joe','Plumber'];

“javascript程序中常见的错误是在需要对象的时候使用数组,而需要数组的时候却使用对象。规则很简单:当属性名是连续的整数时,你应该使用数组。否则,请使用对象”——Douglas Crockford
14.定义多个变量时,省略var关键字,用逗号代替

var someItem = 'some string'; 
var anotherItem = 'another string'; 
var oneMoreItem = 'one more string';// 更好的做法var someItem = 'some string', 
    anotherItem = 'another string', 
    oneMoreItem = 'one more string';

应而不言自明。我怀疑这里真的有所提速,但它能是你的代码更清晰。
15.使用Firebug的"timer"功能优化你的代码
在寻找一个快速、简单的方法来确定操作需要多长时间吗?使用Firebug的“timer”功能来记录结果。

function TimeTracker(){ 
 console.time("MyTimer"); 
 for(x=5000; x > 0; x--){} 
 console.timeEnd("MyTimer"); 
}

The above is the detailed content of What are the details that need to be paid attention to in Javascript?. 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: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

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.

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

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.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor