轉載自:
Superpower your JavaScript with 10 quick tips - For Beginners
Who doesn't love to write better code? In this article I will list 10 simple and quick JavaScript tips that will help beginners improve their code quality. You might know some of these already. In case you didn't feel free to buy me a beer later.
#1 - Use && and || Operators Like a Boss
Well, JavaScript gives you two awesome logical operators :
&&
and
||
. In other languages like Java or C++ they always return a boolean value. But things get a bit interesting when it comes to JavaScript. The
&&
and
||
operators return the last evaluated operand. Have a look at the following
function getMeBeers(count){
if(count){
return count;
}
else{
return 1;
}
}
Well, our function is simple and returns the required number of beers. If you specify no argument, it simply gives you a single beer. Here, you can use
||
to refactor the code as following:
function getMeBeers(count){
return count || 1;
}
In case of
||
if the first operand is falsy, JavaScript will evaluate the next operand. So, if no count is specified while calling the function, 1 will be returned. On the other hand, if count is specified then it will be returned (as the first operand is truthy in this case).
Note: null
,
false
,
0
(the number),
undefined
,
NaN
, and
''
(empty string) are falsy values. Any other value is considered truthy.
Now if you want to allow adults only, you can use
&&
as following:
function getMeBeers(age, count){
return (age>=18) && (count || 1);
}
Instead of :
function getMeBeers(age, count){
if(age>=18){
return count || 1;
}
}
In the above case if age < 18, JavaScript won't even bother evaluating the next operand. So, our function will return. But if the age is actually >= 18, the first operand will evaluate to
true
and then the next operand will be evaluated.
By the way you should be a careful here. If you pass count as 0, the function will return 1 (as 0 is falsy). So, in a real world app you should be careful while handling numeric values.
#2 - Use === and !== Instead of == and !=
The operators
==
and
!=
do automatic type conversion, if needed. But
===
and
!==
will consider both value and type while comparing and won't do any automatic type conversion. So, to reliably compare two values for equality/non-equality always use
===
and
!==
.
10 == '10' //true
10 === '10' //false
10 === 10 //true
#3 - Use Strict mode while writing JS
Strict mode was introduced in ECMA 5. It allows you to put a function or an entire script into strict operating context. The benefits are:
- It eliminates some of the silent JavaScript errors by throwing the errors explicitly.
- It throws exceptions when relatively unsafe actions take place.
- Sometimes strict mode code can run faster than non strict mode code.
<script type="text/javascript">
'use strict'
//Strict mode code goes here
</script>
Or,
function strictCode(){
'use strict'
//This is a strict mode function
}
As currently all the major browsers
support this feature you should start using strict mode.
#4 - Use splice() to remove an array element
If you want to remove an element from an array use
splice()
instead of
delete
.
delete
sets the particular array item to
undefined
while
splice()
actually removes the item.
var array=[1,2,3];
delete array[1]; // now array= [1,undefined,3]
array.splice(1,1); //now array=[1,3]
#5 - Use [] to create new array
Use
[]
to create a new array. Writing
var a=[1,2,3]
will create a 3-element array whereas
new Array(N)
will create a physically empty array of N logical length.
Similarly, use
var a={}
to create an object rather than
new Object()
. The former one is compact, readable and takes less space. You can also instantly populate the object like:
var a = {
name: 'John Doe',
email: 'john@doe.com'
}
#6 - Use String.link() to create Hyperlinks
Many times in JavaScript you will need to generate HTML anchors on the fly. For that you will need some concatenation which may look ugly and messy.
var text="Cool JS Tips";
var url="http://www.htmlxprs.com";
var block='<a href="'+url+'">'+ text +'</a>';
Instead, how about this:
var block=text.link(url); // <a href="http://www.htmlxprs.com">Cool JS Tips</a>
#7 - Cache the length while looping
While looping through a JavaScript array you can cache the length so that the overall performance is better:
for (var i=0,length=array.length; i<length; i++){
//awesome code goes here
}
Be careful while creating an inner loop. You need to name the length variable differently in the inner one.
#8 - Put 'var' before your variable name
While creating variables don't forget to use the
var
keyword. If you forget then the variable gets added to the global scope which is definitely a bad thing.
var localVar=12; //this is a local variable
globalVar=12; //variable goes to 'window' global
#9 - Use Closures and Self Executing Functions
Closures, if used carefully and precisely, can take your JS code to a whole new level. There are plenty of tutorials available which can teach you about
closures. I will just give an example of closures and self executing functions for creating modular code:
var car=(function(){
var _name='Benz Velo';
return {
getName: function(){
return _name;
}
}
})(); //function created and invoked
console.log(car.getName()); //Logs Benz Velo
As you see we just created a function and immediately invoked it. These are called self executing functions or Immediately Invoked Function Expression (IIFE). The function returns an object which is stored in variable
car
. We also used closure because the object being returned can access the variable
_name
defined by the parent function. This is helpful for creating modules and emulating private variables.
#10 - There is always room for Optimization
Use jsHint or jsLint to check your code quality and improve further. Also don't forget to minify and concatenate your JS files while deploying your app. Finally, use
SourceMaps to make debugging a breeze.
Conclusion
Tips can be unlimited. But I hope these 10 quick tips will help you write better code and superpower your JS-Foo. If you loved this you will love our newsletter as well. Don't forget to subscribe.