If by JavaScript you also include versions newer than version 1.5, then you could also see the following:
Expression closures:
JavaScript 1.7 and older:
var square = function(x) { return x * x; }
JavaScript 1.8 added a shorthand Lambda notation for writing simple functions with expression closures:
var square = function(x) x * x;
reduce() method:
JavaScript 1.8 also introduces the reduce() method to Arrays:
var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; });
// total == 6
Destructuring assignment:
In JavaScript 1.7, you can use the destructuring assignment, for example, to swap values avoiding temporary variables:
var a = 1;
var b = 3;
[a, b] = [b, a];
Array Comprehensions and the filter() method:
Array Comprehensions were introduced in JavaScript 1.7 which can reduce the following code:
var numbers = [1, 2, 3, 21, 22, 30];
var evens = [];
for (var i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
evens.push(numbers[i]);
}
}
To something like this:
var numbers = [1, 2, 3, 21, 22, 30];
var evens = [i for each(i in numbers) if (i % 2 === 0)];
Or using the filter()
method in Arrays which was introduced in JavaScript 1.6:
var numbers = [1, 2, 3, 21, 22, 30];
var evens = numbers.filter(function(i) { return i % 2 === 0; });