JavaScript Functions
// Function declaration (hoisted)
function add(a, b = 0) { return a + b; }
// Function expression
const sub = function (a, b) { return a - b; };
// Arrow function
const square = x => x * x;
const sum = (...nums) => nums.reduce((t, n) => t + n, 0); // rest parameters
console.log(add(5), sub(9, 4), square(7), sum(1, 2, 3, 4));
5 5 49 10
Arrow Functions and this
Arrow functions don't have their own this; they use the this of the surrounding code. That makes them convenient for callbacks, but they shouldn't be used as object methods that rely on this.
Closures
A closure is a function that remembers the variables of the scope it was created in, even after that scope has finished running.
function makeCounter() {
let count = 0; // private
return () => ++count;
}
const next = makeCounter();
console.log(next(), next(), next());
1 2 3
Higher-Order Functions
const nums = [1, 2, 3, 4, 5, 6];
console.log(nums.map(n => n * 2));
console.log(nums.filter(n => n % 2 === 0));
console.log(nums.reduce((a, b) => a + b, 0));
[ 2, 4, 6, 8, 10, 12 ]
[ 2, 4, 6 ]
21
Track your progress through the JavaScript course