← #58 Format a number as a currency string

Pass an array as function arguments

Topics: JavaScript

JavaScript has some built-in functions that accept a list of individuals arguments, but passing an array doen't work. Math.max, Math.min are some of them.

They are used to find the biggest and smallest numbers in the passed arguments, repectively.

Math.max(1, 2, 3, 4);       // 4

// Doesn't work because it treats the array as a single parameter
// That parameter isn't a number, so the function returns `NaN`
Math.max([1, 2, 3, 4]); // NaN

If we want to pass a dynamic array of numbers, then the ES6 spread operator (...) can help. It turns a varible to a list of individual parameters:

const array = [1, 2, 3, 4];
Math.max(...array); // 4

JavaScript engines implemented by different browsers have the limited number of parameters. Using the ... operator doesn't work if you have a big array. Using the reduce method doesn't have this problem.

const max = arr => arr.reduce((a, b) => Math.max(a, b));
max([1, 2, 3, 4]); // 4


Fix a typo or suggest an improvement
#60 Use CSS fallback properties