SoFunction
Updated on 2025-04-12

Javascript some details that need to be paid attention to (must-read)

1. Use === instead of ==

JavaScript uses 2 different equivalence operators: ===|!== and ==|!=. It is best practice to use the former in comparison operations.

"If the operands on both sides have the same type and value, ===Return true, !==Return false." - JavaScript: Language Essence

However, when using == and! When =, you may encounter different types. In this case, the operand type will be cast into the same before comparing, which may not be the result you want.

== Evil

When we weren't familiar at first, "eval" gave us access to JavaScript's compiler. Essentially, we can pass a string to eval as a parameter and execute it.

This not only greatly reduces the performance of the script (translator's note: the JIT compiler cannot predict the string content and cannot precompile and optimize), but it also brings huge security risks, because it pays too high permissions to execute text and avoids it.

3. Omitting may not save trouble

Technically, you can omit most curly braces and semicolons. Most browsers can correctly understand the following code:

if(someVariableExists) 
  x = false 

Then, if like this:

if(someVariableExists) 
  x = false 
  anotherFunctionCall(); 

Some people might think that the above 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 can easily give the illusion of curly braces. It is beyond reproach, this is a terrible practice that should be avoided at all costs. There is only one case, that is, when there is only one line, curly braces can be omitted, but this is controversial.

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

Prepare for the future

Most likely, one day you need to add more statements to the if statement block. In this way, you have to rewrite this code. Bottom line - omission is a minefield.

4. Place the script at the bottom of the page

Remember - the primary goal is to make the page present to the user as quickly as possible. The script is blocked and the browser cannot continue to render the following content until the script is loaded and executed. Therefore, users will be forced to wait longer.

If your js is just used to enhance the effect—for example, the button click event—right-place the script before the body ends. This is definitely a best practice.

5. Avoid declaring variables in For statements

When executing lengthy for statements, keep the statement block as concise as possible, for example:

Oops:

for(var i = 0; i < ; i++) { 
  var container = ('container'); 
   += 'my number: ' + i; 
  (i); 
} 

Note that each loop has to calculate the length of the array, and every time it has to traverse the dom to query the "container" element - it is very efficient!

suggestion:

var container = ('container'); 
for(var i = 0, len = ; i < len; i++) { 
   += 'my number: ' + i; 
  (i); 
} 

6. The best way to build strings

When you need to traverse arrays or objects, don't always think about the "for" statement. Be creative and you can always find a better way, for example, like below.

var arr = ['item 1', 'item 2', 'item 3', ...]; 
var list = '<ul><li>' + ('</li><li>') + '</li></ul>';

I am not the God in your heart, but please believe me (if you don’t believe, you test it yourself) – this is the fastest way so far!

Using native code (such as join()), no matter what is done inside the system, it is usually much faster than non-native.

7. Reduce global variables

“As long as multiple global variables are sorted into one namespace, it is intended to significantly reduce the possibility of bad mutual influence with other applications, components or class libraries.”—Douglas Crockford

var name = 'Jeffrey'; 
var lastName = 'Way'; 
function doSomething() {...} 
(name); // Jeffrey -- or// Better practicevar DudeNameSpace = { 
  name : 'Jeffrey', 
  lastName : 'Way', 
  doSomething : function() {...} 
} 
(); // Jeffrey

Note: Here we just simply named "DudeNameSpace", which should be given a more reasonable name in practice.

8. Add comments to the code

It seems unnecessary, when trust me, try to add more reasonable comments to your code. When you re-look at your project a few months later, you may not remember what you thought at the beginning. Or, what if one of your colleagues needs to modify your code? All in all, adding comments to your code is an important part.

// Loop the array and output each name (Translator's note: Such an annotation seems a bit redundant)for(var i = 0, len = ; i &lt; len; i++) {
  (array[i]); 
} 

9. Embrace gradual enhancement

Ensure that JavaScript can degrade smoothly when it is disabled. We are always attracted by the idea that “most of my visitors have JavaScript enabled, so I don’t have to worry.” However, this is a big misunderstanding.

Have you ever spent a moment checking out what your beautiful page looks like when JavaScript is closed? (Download the Web Developer tool easily (Translator's note: Chrome users download it themselves in the app store, and ie users set it in the Internet options)), which can potentially fragment your website. As a rule of thumb, design your website assuming JavaScript is disabled and then, based on this, gradually enhance your website.

10. Do not pass string parameters to "setInterval" or "setTimeout"

Consider the following code:

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

Not only is it inefficient, but this approach is exactly the same as "eval". Never pass strings as parameters to setInterval and setTimeout, but function names are passed like below.

setInterval(someFunction, 3000);

11.Don't use the "with" statement

At first glance, the "with" statement looks like a clever idea. The basic idea is that it can provide abbreviation for accessing deep nested objects, such as...

with () { 
  arms = true; 
  legs = true; 
}

Instead of like this:

 = true; 
= true; 

Unfortunately, after testing, I found that this time "setting new members is doing very badly. As a substitute, you should use variables, like below.

var o = ; 
 = true; 
 = true; 

12. Use {} instead of new Object()

There are many ways to create objects in JavaScript. Maybe the traditional method is to use "new" to add a constructor, like this:

ar o = new Object(); 
 = 'Jeffrey'; 
 = 'Way'; 
 = function() { 
  (); 
}

However, this method has not received much criticism than it actually is. Instead, I suggest you use a more robust object literal approach.

A better way to do it

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

Note that if you just want to create an empty object, {} is better.

13. Use [] instead of new Array()

The same applies to creating a new array.

For example:

var a = new Array(); 
a[0] = "Joe"; 
a[1] = 'Plumber';

// Better practice:var a = ['Joe','Plumber'];

"A common mistake in javascript programs is to use arrays when you need objects, and use objects when you need them. The rule is simple: when the property name is a continuous integer, you should use arrays. Otherwise, please use objects" - Douglas Crockford

14. When defining multiple variables, omit the var keyword and replace it with commas.

var someItem = 'some string'; 
var anotherItem = 'another string'; 
var oneMoreItem = 'one more string';
// Better practicevar someItem = 'some string', 
  anotherItem = 'another string', 
  oneMoreItem = 'one more string';

It is self-evident. I suspect there is really a speedup here, but it can be more clear to your code.

15. Optimize your code using Firebug's "timer" function

Looking for a quick and easy way to determine how long it takes to operate? Use Firebug's "timer" function to record results.

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

16. Read, read, read repeatedly

Although there is nothing more suitable than a book after lunch or before going to bed, insist on putting a web development book on your bedside table.

The above details that need to be paid attention to in Javascript (must-read) are all the content I share with you. I hope you can give you a reference and I hope you can support me more.