What "Hidden Features" of JavaScript do you think every programmer should know?
After having seen the excellent quality of the answers to the following questions I thought it was time to ask it for JavaScript.
- Hidden Features of HTML
- Hidden Features of CSS
- Hidden Features of PHP
- Hidden Features of ASP.NET
- Hidden Features of C#
- Hidden Features of Java
- Hidden Features of Python
Even though JavaScript is arguably the most important Client Side language right now (just ask Google) it's surprising how little most web developers appreciate how powerful it really is.
I could quote most of Douglas Crockford's excellent book JavaScript: The Good Parts.
But I'll take just one for you, always use
===
and!==
instead of==
and!=
==
is not transitive. If you use===
it would give false for all of these statements as expected.Private Methods
An object can have private methods.
Some would call this a matter of taste, but:
The trinary operator can be chained to act like Scheme's (cond ...):
can be written as...
This is very "functional", as it branches your code without side effects. So instead of:
You can write:
Works nice with recursion, too :)
Numbers are also objects. So you can do cool stuff like:
Be sure to use the hasOwnProperty method when iterating through an object's properties:
This is done so that you will only access the direct properties of anObject, and not use the properties that are down the prototype chain.
You can access object properties with
[]
instead of.
This allows you look up a property matching a variable.
You can also use this to get/set object properties whose name is not a legal identifier.
Some people don't know this and end up using eval() like this, which is a really bad idea:
This is harder to read, harder to find errors in (can't use jslint), slower to execute, and can lead to XSS exploits.