[Tips, Tricks, Best Practices] (http://modernweb.com/2013/12/23/45-useful-javascript-tips-tricks-and-best-practices/) | [Style Guide] (https://github.com/airbnb/javascript) | [Resources Collection] (https://gist.github.com/Neener54/3774166) |
2 – use === instead of ==
The == (or !=) operator performs an automatic type conversion if needed. The === (or !==) operator will not perform any conversion. It compares the value and the type, which could be considered faster than ==.
[10] === 10 // is false
[10] == 10 // is true
'10' == 10 // is true
'10' === 10 // is false
[] == 0 // is true
[] === 0 // is false
'' == false // is true but true == "a" is false
'' === false // is false
3 – undefined, null, 0, false, NaN, '' (empty string) are all falsy.
6 – Be careful when using typeof
typeof : a JavaScript unary operator used to return a string that represents the primitive type of a variable, don’t forget that typeof null will return “object”, and for the majority of object types (Array, Date, and others) will return also “object”.
14 – Append an array to another array
var array1 = [12 , "foo" , {name "Joe"} , -2458];
var array2 = ["Doe" , 555 , 100];
Array.prototype.push.apply(array1, array2);
/* array1 will be equal to [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */
15 – Transform the arguments object into an array
var argArray = Array.prototype.slice.call(arguments);
16 – Verify that a given argument is a number
function isNumber(n){
return !isNaN(parseFloat(n)) && isFinite(n);
}
17 – Verify that a given argument is an array
function isArray(obj){
return Object.prototype.toString.call(obj) === '[object Array]' ;
}
Note that if the toString() method is overridden, you will not get the expected result using this trick.
Or use…
Array.isArray(obj); // its a new Array method
You could also use instanceof if you are not working with multiple frames. However, if you have many contexts, you will get a wrong result.
var myFrame = document.createElement('iframe');
document.body.appendChild(myFrame);
var myArray = window.frames[window.frames.length-1].Array;
var arr = new myArray(a,b,10); // [a,b,10]
// instanceof will not work correctly, myArray loses his constructor
// constructor is not shared between frames
arr instanceof Array; // false
18 – Get the max or the min in an array of numbers
var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
var maxInNumbers = Math.max.apply(Math, numbers);
var minInNumbers = Math.min.apply(Math, numbers);
19 – Empty an array
var myArray = [12 , 222 , 1000 ];
myArray.length = 0; // myArray will be equal to [].
20 – Don’t use delete to remove an item from array
Use splice instead of using delete to delete an item from an array. Using delete replaces the item with undefined instead of the removing it from the array.
Instead of…
var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];
items.length; // return 11
delete items[3]; // return true
items.length; // return 11
/* items will be equal to [12, 548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */
Use…
var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];
items.length; // return 11
items.splice(3,1) ;
items.length; // return 10
/* items will be equal to [12, 548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */
The delete method should be used to delete an object property.
21 – Truncate an array using length
Like the previous example of emptying an array, we truncate it using the length property.
var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];
myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].
As a bonus, if you set the array length to a higher value, the length will be changed and new items will be added with undefined as a value. The array length is not a read only property.
myArray.length = 10; // the new array length is 10
myArray[myArray.length - 1] ; // undefined
22 – Use logical AND/ OR for conditions
var foo = 10;
foo == 10 && doSomething(); // is the same thing as if (foo == 10) doSomething();
foo == 5 || doSomething(); // is the same thing as if (foo != 5) doSomething();
The logical OR could also be used to set a default value for function argument.
function doSomething(arg1){
arg1 = arg1 || 10; // arg1 will have 10 as a default value if it’s not already set
}
23 – Use the map() function method to loop through an array’s items
var squares = [1,2,3,4].map(function (val) {
return val * val;
});
// squares will be equal to [1, 4, 9, 16]
24 – Rounding number to N decimal place
var num =2.443242342;
num = num.toFixed(4); // num will be equal to 2.4432
NOTE : the toFixed() function returns a string and not a number.
39 – An HTML escaper function
function escapeHTML(text) {
var replacements= {"<": "<", ">": ">","&": "&", """: """};
return text.replace(/[<>&"]/g, function(character) {
return replacements[character];
});
}
#JavaScript