The quirks of JavaScript listed here are ones that I techniques that I employ with frequency, possibly with the exception of the last one. Some people criticize JavaScript because of its misunderstood semantics, but once you put these quirks to use, you will see what a powerful language JavaScript can be.
Infinity and its counterpart -Infinity are numbers in JavaScript. Try it out:
>> 1/0
Infinity
>> typeof(1/0)
"Number"
The easiest way to convert a string into a base-10 integer isn’t with parseInt(). It’s actually:
>> +"234"
234
The three-part tenary operator is very useful for quick one-liners when more if-blocks is the last thing you need:
if (store.isOpen){
return "Hi!";
} else {
return "Bye!";
}return (store.isOpen)?"Hi!":"Bye!";
You can define a function with a variable number of arguments by utilizing the built-in arguments variable. See the following example:
function average(){
var total = 0;
for(var i=0;i<arguments.length;i++){
total += arguments[i];
}
return total/arguments.length;
}
Functions in JavaScript can be passed to and returned from a function. Examine the following:
function a(b){
return function(c){
return c%b == 0;
};
}>> var d = a(3);
undefined
>> d(4);
false
>> d(9);
true
This way, you can dynamically generate functions whose execution control is based on runtime variables. Read more about closures on Wikipedia.