This is going to be an unsorted list about the nicest Javascript features. Look closely at the title: Javascript! Thus this list may contain features only present in the Mozilla-implementation and not standardized in ECMAScript! I am going to update this list every now and then.
Block scoping with let
Support: ECMAScript Harmony, Javascript 1.7, Mozilla-only (as of September 2010)
Finally lexical scoping / block scoping in Javascript. Declare variables with let
instead of var
. May come in handy when you are creating closures in a loop.
Logical operators &&
and ||
Support: should work in all modern browsers
Logical operators are nothing spectecular in programming languages. But Javascript handles them a little different. &&
and ||
don’t necessarily return boolean values, but can also return other types (objects, etc). Here are some examples from Angus Croll’s JavaScript blog:
1 2 3 4 5 |
|
But you should be careful, when using this with values that evaluate to false. See the following example:
1 2 3 |
|
0
will evaluate to false
and thus delayBy
will be called with 20
.
||
is often used for setting default-values for functions parameters (well, harmony may contain that natively), but as shown that may not always lead to the expected behaviour, thus I wouldn’t recommend setting default values that way.
Destructuring
Support: ECMAScript Harmony, Javascript 1.7, Mozilla-only (as of September 2010)
Don’t confuse this with destructors known from languages like Java or C++. Destructuring assignment makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals
This allows things like swapping variables without a temporary variable, multiple return values and more. Here is an example for multiple return values from MDN:
1 2 3 4 5 6 7 |
|
The function simply returns an array, but the destructuring syntax allows to split this into multiple variables.
Labeling statements
Support: should work in all modern browsers
By labeling statements you can give them an identifier that you can refer to from somewhere else. That may come in handy when using loops with continue
or break
.
1 2 3 4 5 6 7 8 9 10 |
|