DEV Community

Cover image for Some awesome js tricks you should know about

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)

tqbit profile image
tq-bit • Edited

don't forget the invaluable 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 = => num + 10);
console.log(numsPlusTen); // Returns [11, 25, 40]
Enter fullscreen mode Exit fullscreen mode
is_ellie profile image

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