3 - Arrays and callbacks
Learning Objectives
By the end of this class, you should be able to answer these questions:
Describe what an array method is and use them to manipulate an array
Write code that chains array methods together
Define what a callback is
Write code that uses a callback to run code
Define what an anonymous function is
Write code that uses an anonymous function as a callback
Array properties
Arrays, like strings, have a length
property.
You can check this by starting a node console in your terminal.
Manipulating arrays
You can get a single value out of an array using bracket notation.
Did you notice how we use [0]
to get the first value? In programming we count starting at zero.
The number inside of the brackets is called an index. Index just means the position of the item within the array.
You can also set a value using bracket notation and an assignment operator (=
).
Exercise A (5 minutes)
Create an array with the names of the people on your table
console.log
out the names and how many people are at the tablePut someone from another table at the beginning of the array
Add someone else to the end of the list
Working with arrays
When working with lists it is often useful to manipulate, enhance, or search the information in that list.
Some examples of things you might want to do with a list of data:
Only use the first 10 items in a list
Get people from a list whose name starts with a
M
Find the first person in a list to be over 100 years old
Arrange people in a list alphabetically
Get the last 10 items in an array
Add all the numbers up in a list
Get all the cats in an array of animals
From a list of numbers, add a
£
sign prefixCombine a list of romance films and thrillers
Array methods
Do you remember how strings have special functions called methods? Don't worry if not! Here's an example to jog your memory:
Arrays also have several methods that you can use.
.sort()
.sort()
An array method that sorts the values in an array into ascending alphabetical or numerical order.
When you call this array method it uses the array on the left side of the dot as an input, and it sorts that array also returning it. Note how both ordered and unordered arrays are sorted now!
.concat()
.concat()
Adds (or concatenates) another value or array to the array.
Did you notice how calling the concat method did not change arr
? This is because concat
, like most array methods, returns a new array, it does not alter the one you called the method on.
If you want to use the array returned by calling .concat()
you should store it in a new variable.
.slice()
.slice()
Returns a slice of the array.
You can tell .slice()
where you want the slice to begin and end by passing it two parameters.
.includes()
.includes()
Returns true if a value is in the array.
.join()
.join()
Returns all the array values joined together in a string. By default, this method takes no parameters and then the elements are divided with a comma ,
. If you provide it with a string parameter though, then it becomes the divider of the elements, like the example below:
There is a string method .split()
. In an interactive console try using the string .split()
method and the array .join()
. How could they work together?
Exercise B (10 minutes)
Use the array of the people from your class
Combine it with another array filled with the names from another class
console.log
the names in alphabetical orderCreate a function that takes a
name
and an array of names and returns a string. If the name is not in an array, it should return<name> is not at the class with <people in the array>
. If the name is in the array, it should return<name> is at the class with <people in the array>
.
Array map
Imagine you have an array of names...
You notice that the names are not formatted consistently. To fix the array you decide you need to trim whitespace and convert to lowercase. How do you do that for every value in the array?
We can write a function that changes one name:
All you need to run every name in the array through this function and update the array values. Thankfully there is an array method that does just this!
.map()
.map()
Runs every item in the array through a function and returns a new array with the values returned by the function.
Have a look at this other example:
The map()
method runs the function we provided (double
) on each item in the array and uses the return values to create a new array. In the example numbersDoubled
is a new array containing [2, 4, 6]
.
Callback functions
A callback function is a function that is passed as an argument to another function, to be “called back” at a later time. . The term highlights that although we provide the double
function, the .map()
method calls it. (Notice how we never write double()
to call the function).
We'll see callback functions used a lot more in the coming weeks.
Often, when a function is only needed for a map operation, developers will declare the callback function inside of the method call. Let's try copying and pasting the function declaration inside of the .map()
method call.
We can make this shorter by removing the function name to declare an anonymous function. We can do this because we are not using the function anywhere else in the code, so we do not need the function name to reference it.
We can make this code even shorter still. In the latest versions of JavaScript a way of declaring functions was introduced called arrow functions.
The arrow function syntax lets you declare a function without the function
keyword. (There are some other subtle differences between arrow functions and regular functions that you will learn about at a much later stage).
There is one last thing you can do to make your code shorter. If you remove the braces ({}
) from an arrow function, the body of the function will be returned without needing to write the return
keyword.
In the example above, the expression number * 2
is automatically returned because it comes directly after the =>
arrow (instead of coming after curly braces). This is called an implicit return
.
Exercise C (10 minutes)
I have a function defined below as:
This function does not need to be modified. Can you pass in a callback function which will mutate namesArray
such that it:
Upper cases all letters in the array
Exercise D
Modify your callback function from the previous exercise so that it also:
sorts
namesArray
in alphabetical order
Array forEach
The .forEach()
method is similar to .map()
except it does not return a new array.
.forEach()
.forEach()
Say we want to log to the console a list of names.
We can use .forEach()
to go through the array, item by item, and call a function we provide.
Exercise E (10 minutes)
Create a function that takes a
birthYear
, and returns the age of someoneYou are given an array with year that 7 people were born,
[1964, 2008, 1999, 2005, 1978, 1985, 1919]
. Take this array and create another array containing their ages.console.log
the birth years array
Exercise F (5 minutes)
You can drive in the UK at the age of 17.
Write another function that takes a birth year and returns a string
Born in {year} can drive
orBorn in {year} can drive in {x} years
Use the array of birth years,
[ 1964, 2008, 1999, 2005, 1978, 1985, 1919 ]
, to get an array of strings saying if these people can driveconsole.log
the answers
Array filter
Imagine you have an array of students' test scores:
You want to show only the test scores that are higher than 80. How do you do that for every value in the array?
We can write a function that checks if one score is greater than 80:
To find out which scores were greater than 80, you'd have to run this function against every score in the array, and push the 80+ scores into a new array. Thankfully there is an array method that does just this!
.filter()
.filter()
Runs every item in the array through a condition that we set, and returns a new array with the values that match the condition.
Exercise G (10 mins)
Create a function which:
Takes an array of
birthYears
Uses
console.log
to print the messageThese are the birth years of people who can drive: <filtered birth years>
Returns an array of people who can drive (remember, you can drive if you are 17 years or older)
Array find
Imagine you have an array of names:
How would you find the first name that's longer than 6 characters?
You can write a predicate function that checks if a string is longer than 6 characters:
To find the first item that satisfies the predicate you would have to go through each array item, and pass it into isLongName
. Once it returns true, we can stop going through the array and grab the item that passed the predicate's test. Sounds complicated! Thankfully there is an array method that does just this!
.find()
.find()
Searches through the array and returns the value of the first item that satisfies a predicate function.
Exercise H (10 mins)
Create a function which:
Takes an array of names
Looks to see if your name is in the array
If it is, return
Found me!
; if not, returnHaven't found me :(
Chaining
Notice how we were able to write one method after another e.g. names.map(formatName).forEach(log)
? This is called method chaining.
You can call .forEach()
after .map()
because .map()
returns a new array.
Consider this code:
It can be written more simply (without assigning the array returned from .map()
to a variable):
Be careful though! You can not call .map()
after .forEach
.
This code does not work because forEach()
does not return a new array (it returns undefined
). The code is therefore attempting to call .map()
on undefined
, and undefined
does not have a .map()
method.
Exercise I (15 minutes)
Create a function which accepts an array of "messy" strings. Example:
This function should:
Remove all non-string entries
Change the strings to upper case, and add an exclamation mark to the end
If you're using the above example, you should expect to return an array with 2x ELAMIN!
, 1x SANYIA!
, 2x ISMAEL!
and 1x JAMES!
.
Last updated