Make some small performance improvements for JavaScript!
This article lists 24 suggestions to make your coding process easier and more efficient. Maybe you are still a JavaScript beginner and have just finished writing your own Hello World. There are many tips here that will be very useful for your work. Maybe you already know some of the tips, so try a quick browse and see if you can find them. Something new!
Note: This article uses Firebug’s console object many times, please refer to Firebug Console API . For a more detailed introduction to firebug, please click here .
1. Use === instead of == There are two different equality operators in JavaScript: ===|!== and ==|!=. In comparison, the former is more worthy of recommendation. Please try to use the former.
"If the two comparison objects have the same type and value, === returns true and !== returns false."
– JavaScript: The Good Parts
However, if you use == and !=, you may encounter some unexpected problems when operating different data types. JavaScript will try to convert them into strings, numbers, or Boolean quantities before making an equality judgment.
2. Avoid using the Eval function
The Eval function takes a string as a parameter, executes the string as a JavaScript statement, and returns the result (reference).
Not only does this function reduce the execution efficiency of your script, but it also greatly increases the security risk because it gives too much power to the parameter that is a text. Don't use it!
3. Don’t use quick writing
Technically, you can omit most of the curly braces and trailing semicolons, and most browsers will execute the following statement correctly:
.if(someVariableExists)
x = false
However, what if this is the case:
.if(someVariableExists)
x = false
anotherFunctionCall();
You might think of it as equivalent to the following statement:
if(someVariableExists) {
x = false;
anotherFunctionCall();
}
Unfortunately, this is not the case. The reality is that it is equivalent to:
As you'll notice, no amount of fancy indentation can take the place of fancy braces. In all cases please write clear curly braces and final semicolons. It can occasionally be omitted when there is only one line, although this is highly discouraged:
if(2 + 2 === 4) return 'nicely done';
Think more about the future. Suppose, in the future development process, you need to add more commands to this if statement? Don’t you have to add parentheses then?
if(someVariableExists) {
x = false;
}
anotherFunctionCall();