Array Methods And Callbacks In Javascript
Tags: javascript, codenewbie, webdev
Published: 2021-03-03 11:13:05

# Introduction

One of the most important things in JavaScript is arrays. 99% of the time there is going to be an array in someone's JS script. And if you take a look into someone else's code, you will likely see them use an array method or callbacks.

Callbacks are functions that get passed on to another function as an argument.

These methods are built-in functions in JavaScript that you can use for your array. 

In this post, we are going to talk about some of these callbacks and array methods and how to use them.

# `forEach()`

`forEach()` used to be a lot more used before the `for...of` loop came out. This method allows us to run a function that runs our code once per item in some array.

Let's first create our array. We are going to call it `numbers`.

```
let numbers = [1, 2, 3, 4, 5];
```

And now let's use the `forEach()` method and print out all of the numbers in our array.

This is what you will most commonly see. Defining a function inline.

```
numbers.forEach(function (num){
    console.log(num);
})
```

This is very famous and is mainly used this way. We could pass in a name function that we have already created, but most of the time we will pass in a function that exists only for this.

If you want to pass a function that already exists, it should look something like this:

```
function print(el){
    console.log(el);
}

numbers.forEach(print);
```

This is pretty uncommon. You will hardly see this in someone else's code.

# `map()`

The `map()` function creates a new array with the results of calling a callback on every element of the array. Let's create our first array.

```
const heroes = ['batman', 'spider-man', 'superman'];
```

Now let's use the `map()` method to create our new array called `superHeroes` and use the `toUpperCase` method.

> The `toUpperCase`method returns the value to uppercase.

```
const superHeroes = heroes.map(function (t){
     return t.toUpperCase();
})
```

Now let's call our new array and see the results.

```
superHeroes

<- (3) ["BATMAN", "SPIDER-MAN", "SUPERMAN"]
```

We just made a new array, in which all the values are in uppercase. You can do so much more with this method. Give it a try and see how much fun stuff you can do with it.

# Arrow `=>`

This method is probably one of the most useful ones. This is a newer syntax for defining functions. It allows us to write functions without actually having to write the keyword `function`. How cool is that!

They are super useful for when you have a short function to write for a one-time thing. 

Arrow functions are used to create function expressions. But they can only be created from a variable. This is how it looks like:

```
const sum = (x, y) =>{
    return x + y;
}
```
So now to execute the function, it will be the same as executing any other function. That's because it is just like any other function, but with a nicer and cleaner syntax.

```
sum(5, 5);

<- 10
```

If you want to write a function with no arguments, then you just have to add the empty parenthesis.

```
const  greet = () =>{
    return 'Hello World!';
}
```

And we can call this function back like any other function.

```
greet();

<- "Hello World!"
```

If you have a function with only one argument, then you can write it without parenthesis.

```
const square = x =>{
    return x * x;
}
```

And then you have to call it back the same way as you usually do.

```
square(5);

<- 25
```

So remember, if you have two or more arguments - use parenthesis. If you have zero arguments - use parenthesis again. But if you have only one argument - you don't need to use parenthesis.

We can also make our arrow function even shorter with **implicit returns**. What this means is that we can get rid of the `return` keyword. We just have to turn our curly braces into parenthesis. So let's make our last function (`square`) a little bit shorter.

```
const square = x =>(
    x * x
);
```

As you can see we got rid of the `return` keyword and it got a little bit shorter. **It's very important to know that we can only do this if there is only one line of code with a single value.**

If our function is a super short one, we can have it all on one line. We just have to remove the parenthesis. This is how it should look.

```
const square = x => x * x
```

As you can see the arrow function makes it so much shorter and cleaner. This is very helpful for those short functions that you need in your code.

# `filter()`

The `filter()` function creates a new array with all of the elements that the test implemented by the provided function. Let's create an array with some numbers in it.

```
const numbers = [1, 2, 3, 4, 5];
```

Let's use the `arrow` method and return the numbers that are greater than 2 while using the `filter()` method.

```
const newNumbers = numbers.filter(x =>{
    return x > 2;
})
```

Now if we call the `newNumbers` array that we just created, it's going to give us back all of the numbers that are greater than 2.

```
newNumbers

<- (3) [3, 4, 5]
```

# every/some

These two methods are put together because they are very similar. The `every` method tests whether **all** elements in the array pass the provided function. **It returns a Boolean value**. As for the `some` method, it does the same as `every`, but it returns `true` if **any** of the array elements pass the test function. 

These two methods always return `true` or `false`. Unlike the previous methods- `map()` and `filter()`, which return a new array.

Let's create a new array. It is going to contain the result of an exam.

```
const results = [92, 85, 78, 96, 77, 71, 89];
```

Now let's check if every student passes the exam. In order to pass it, they must have a score over 70.

```
results.every(score => score > 70);

<- true
```

We get `true` because all of the elements in the array are over 70. But now if we change the score of which you have to have to pass the exam to 75, we will get `false`.

The `some` method will say true if any of the elements in the array pass the function. So this means if we change the minimum score to be 75, we are still going to get true.

```
result.some(score => score < 75);

<- true
```

And if none of the array elements pass, then we will get `false`.

# Conclusion

These methods may seem intimidating and scary at first, or probably a bit useless, but the more you use them and get comfortable with them, the more awesome stuff you can create. And you can create them much easier. You just have to keep on practicing and applying these methods to your day-to-day coding sessions.

I hope that this post has helped. I am currently learning all this stuff at the moment and I wanted to share them with the world. Any feedback will be greatly appreciated!