DEV Community

Discussion on: JS functions that I learned this week

Collapse
lukeshiru profile image
Luke Shiru • Edited on

Here you go:

  • Array.prototype.reduce: This function is also known as "fold" in other languages. It allows you to given an array, return a new value from it by "reducing/folding" all its items to it. Here's an example:
const numbers = [1, 2, 3, 4];

const numbersTotal = numbers.reduce((total, current) => total + current);
// The callback function of `reduce` receives the total so far, and the current
// item, so this is what happens in every iteration:
//
// 0: total = 1, current = 2 ... so total + current = 3
// 1: total = 3 (from the result of the previous iteration), current = 3. 3 + 3 = 6
// 2: total = 6 (again, from the previous iteration), current = 4. 6 + 4 = 10
//
// Final result = 10
Enter fullscreen mode Exit fullscreen mode

More info here.

  • for...of: Is just a better way of looping with for over something:
const numbers = [1, 2, 3, 4];

for (const number of numbers) {
    console.log(number); // Will log 1, 2, 3, and 4 separatedly
}
Enter fullscreen mode Exit fullscreen mode

More info here.

  • Nullish coalescing: Is a new operator expressed with two question marks (??). It goes to the value of the right ONLY if the value on the left is nullish (either null or undefined):
0 ?? "right value"; // 0
false ?? "right value"; // false
null ?? "right value"; // "right value"
undefined ?? "right value"; // "right value"

// Compared to the previous "falsy" approach using `||`, which sucks:

0 || "right value"; // "right value"
false || "right value"; // "right value"
null || "right value"; // "right value"
undefined || "right value"; // "right value"
Enter fullscreen mode Exit fullscreen mode

More info here.

  • Spread: Another operator, this one is expressed with an ellipsis (3 dots: ...), and is used to "spread" values of an array, string and other iterators in place of arguments:
const numbers = [1, 2, 3, 4];

const maxNumber = Math.max(...numbers);
// This is like doing: Math.max(1, 2, 3, 4);
Enter fullscreen mode Exit fullscreen mode

More info here.

  • Object.entries: One of the best ways of looping over an object. It takes an object and returns an array with [key, value] tuples:
const object = { harder: "better", faster: "stronger" };

Object.entries(object); // [["harder", "better"], ["faster", "stronger"]]
Enter fullscreen mode Exit fullscreen mode

More info here.

Cheers!

Collapse
faisalamin001 profile image
Faisal Amin

Thank you! 😊