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.
Know how many parameters are expected by a function
Know how many parameters are received by the function
Private variables with a Public Interface
It uses a neat little trick with a self-calling function definition. Everything inside the object which is returned is available in the public interface, while everything else is private.
If you're Googling for a decent JavaScript reference on a given topic, include the "mdc" keyword in your query and your first results will be from the Mozilla Developer Center. I don't carry any offline references or books with me. I always use the "mdc" keyword trick to directly get to what I'm looking for. For example:
Google: javascript array sort mdc
(in most cases you may omit "javascript")
Update: Mozilla Developer Center has been renamed to Mozilla Developer Network. The "mdc" keyword trick still works, but soon enough we may have to start using "mdn" instead.
Functions are objects and therefore can have properties.
Also mentioned in Crockford's "Javascript: The Good Parts":
parseInt()
is dangerous. If you pass it a string without informing it of the proper base it may return unexpected numbers. For exampleparseInt('010')
returns 8, not 10. Passing a base to parseInt makes it work correctly:How about closures in JavaScript (similar to anonymous methods in C# v2.0+). You can create a function that creates a function or "expression".
Example of closures: