MENU
Parameters
Functions can now accept default parameters.
function f(a, b, c = 10) {
console.log(a);
console.log(b);
console.log(c);
}
f(1, 2);1
2
10
An arbitrary number of parameters can now easily be passed and processed with the 'rest parameter'. Prefixed with ... , the 'rest parameter' must be the last formal parameter. Additional type checking can be performed with 'typeof'. Note that the ... operator is also applicable to an object and an iterable.
function f(a, b, ...r) {
console.log(a);
console.log(b);
for (v of r) console.log(v);
console.log(Array.isArray(r));
}
f(1, 2, 3, 4, 5);1
2
3
4
5
true
Arguments can now be 'destructured' as they are passed into a function, following the same principles in 8.2.3 and 8.12.5.
function f({a, b: [c, d], e = 100}) {
console.log(a);
// console.log(b); // ReferenceError
console.log(c);
console.log(d);
console.log(e);
}
f({a: 10, b: [20, 30]});
function g({a = "foo", b} = {}) {
console.log(a, b);
}
g({a: 1, b: 2});
g();10
20
30
100
1 2
foo undefined
Javascript passes by value or reference. When a passed variable references an object such as an array, the value passed is a reference(memory address) to the object. Hence, a function can modify the properties of an object passed into it, but not the 'entire object as a whole' for the variable. Primitives are always passed by value.
function changeStuff(n, o1, o2) {
n = n * 10;
o1.item = "changed";
o2 = {item: "changed"};
}
var num = 10;
var obj1 = {item: "unchanged"};
var obj2 = {item: "unchanged"};
changeStuff(num, obj1, obj2);
console.log(num);
console.log(obj1.item);
console.log(obj2.item);10 (unchanged)
changed
unchanged