DEV Community

Cover image for Some awesome js tricks you should know about
Ellie
Ellie

Posted on

Some awesome js tricks you should know about

When it comes to adding all the numbers in an array, most people would think of the 'for loop' to traverse all the numbers, but other than that, do you know you can also use array.forEach() and array.reduce()to do so? Let's take an example here!

(1) array.forEach()
Alt Text

(2) array.reduce()
Alt Text

There're also lots of array tricks you may not know about, take a look at the examples below:

(3) use array.reverse() to reverse a string:

Alt Text

(4) repeat certain string for multiple times

Alt Text

We all know that spread operator can be used to split an array into a pseudo array,but it can also used to copy an object in react project! Look at the example below:

(5)use spread operator to copy an object in class component.

...To be continued

Top comments (2)

Collapse
 
tqbit profile image
tq-bit • Edited

don't forget the invaluable array.map() method. Basically an abbreviation of array.forEach(), but executes a callback on each array element and returns an array with the mutated values.

const nums = [1, 15, 30];
const numsPlusTen = nums.map((num) => num + 10);
console.log(numsPlusTen); // Returns [11, 25, 40]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
is_ellie profile image
Ellie

Haha right, .map() could basically do all forEach() could do, thanks for commenting btw!