I have a question regarding the arrow functions in Javascript: What exactly is the code inside the map() method doing? I can't understand how exactly this takes each word and then join() method takes the first character?!
const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];
const secretMessage = animals.map(animal => animal[0]);
console.log(secretMessage.join(''));
I think you understand what map does but are confused by animal[0]
for each iteration of the map loop, animal is the string held in the current element of the animals array. the [0] is a shorthand reference to the first character of the string in that element.
string[0] is identical to string.charAt(0)
So your map is merely returning a new array holding the first letter of each element of the starting array, which is then joined to make the secret word.
let string = "hello";
console.log(string[0]);
console.log(string.charAt(0));
console.log(string[0]===string.charAt(0));
animals.map(animal => animal[0]); creates an array containing first letter of each element. .map() makes a new array, iterate with the function
animal => animal[0], maps each element of new array with first letter of animal array element (respectively). Simple terms - function inside .map() is an iterator function
secretMessage.join('') - creates a string by joining each Array element with the delimiter ''
Your map function on each iteration takes the next element of the array ( animal ) and returns the first letter from the current animal
You can imagine it this way. The task of the function is to iterate over your given array With each new call, the next element of the array is passed to the arrow function. You can do any operation with it and return the result. The result that the arrow function returns will be written to the current element of the NEW array
For a simpler understanding, you can replace the arrow function with this one
(animal) => {
return animal[0]
}
As a result, you get an array, each element of which will consist of one letter (in this case, the first one)
join('') joins all the elements of an array into a string. Here ee is transmitted - this is what the gaps between the elements will be filled with, in this case it is an empty string and a continuous string will be obtained
If you pass ' ' you get something like H e l l o W o r l d