Closed mserykh closed 3 years ago
for loop example
const theatres = [
'Mariinsky Theatre',
'New York City Ballet',
'Bolshoi Theatre',
'Royal Danish Ballet',
'English National Ballet',
'Dutch National Ballet'
];
for (let i = 0; i < theatres.length; i++) {
console.log(`${i}: {theatres[i]}`);
}
forEach()
const theatres = [
'Mariinsky Theatre',
'New York City Ballet',
'Bolshoi Theatre',
'Royal Danish Ballet',
'English National Ballet',
'Dutch National Ballet'
];
function printTheatresList(theatre, index) {
console.log(`${index}: {theatre}`);
theatres.forEach(printTheatresList);
for-of
const theatres = [
'Mariinsky Theatre',
'New York City Ballet',
'Bolshoi Theatre',
'Royal Danish Ballet',
'English National Ballet',
'Dutch National Ballet'
];
for (const [index, theatre] of theatres.entries()) {
console.log(`${index}: ${theatre}`);
}
map()
For my previous example it is better not to use map()
as I am not using the array returns.
const theatres = [
'Mariinsky Theatre',
'New York City Ballet',
'Bolshoi Theatre',
'Royal Danish Ballet',
'English National Ballet',
'Dutch National Ballet'
];
const theatresWithIndices = theatres.map((theatre, index) => console.log(`${index}: ${theatre}`));
It is interesting, that if I do not save theatres.map((theatre, index) => console.log(`${index}: ${theatre}`))
to a variable, map() will return undefined
6 times.
I just noticed that and decided to write it down here.
It is interesting, that if I do not save theatres.map((theatre, index) => console.log(
${index}: ${theatre}
)) to a variable, map() will return undefined 6 times.
@mserykh map()
doesn't return 6 times, it returns only once.
But it maps every element and its index to another value that should be returned by the function that you pass to .map()
. As you pass a single-line arrow function (one-liner), it returns the value that it has as the result of evaluating the expression console.log(`${index}: ${theatre}`)
.
console.log()
doesn't return anything. That's why each element from the original array is mapped to undefined
.
@mserykh today I learnt something :)
I didn't know about such approach:
for (const [index, theatre] of theatres) {
console.log(`${index}: ${theatre}`);
}
🚀 Challenge
There are other ways of looping over arrays other than for and while loops. There are forEach, for-of, and map. Rewrite your array loop using one of these techniques.