Photo by Frank Zimmermann on Unsplash
Array .map() - Single line versus multi-line
By the power of Ra ...
A year or more* into learning JavaScript, I am at the point where I understand and manipulate can most vanilla JS. This is mostly due to completing exercises on sites like Codewars. It is also because of Codecademy and other resources.
* The last 6 months have been hit or miss, becasue of a baby 🤷
So while I am perhaps best described as an "advanced-novice", I found a great "Intro to Programming" type course online that uses JavaScript to teach basic programming concepts. Despite my current knowledge level, I am going through the course both to reinforce my understanding of basic concepts, and to fill any knowledge gaps that might exist.
One of the basic concepts taught is arrays--i.e. what they are, how they can be manipulated, etc. Currently I am at the .map()
method part of the array lessons. The way the course teaches .map()
(and other methods like .forEach()
) is to write out the code in long form.
At this point in my journey outside of this course, I have learned how to turn .map()
in a single line of code, depending on its application. So, it was interesting to see how to use the method in a much more verbose way as--oddly--I do not recall actually seeing it in this format before.
All that said, I thought it would be beneficial for others (and myself) to see the difference between two pieces of code that do the same thing.
Longform .map()
function tripleGrades(grades) {
let tripled = grades.map(function(grade) {
return grade * 3;
})
return tripled;
}
A breakdown of the parts
A
function
declaration,tripleGrades
Parameter
grades
, representing an array of numbersUse of the
.map()
method applied to the passed in array represented bygrades
Anonymous callback function (again a function declaration) with parameter
grade
Parameter
grade
represents each item in the arrayThe anonymous callback function returns each
grade
multiplied by 3Saves all of that to a variable aptly named
tripled
tripleGrades
returnstripled
return
is visible and required
Single line .map()
const tripleGrades = grades => grades.map(grade => grade * 3);
Breakdown
An anonymous function expression
ES6 arrow function
Parameter
grades
, representing an array of numbersUse of the
.map()
method applied to the passed in array represented bygrades
Anonymous callback function (again a function expression) with parameter
grade
Parameter
grade
represents each item in the arrayCallback function returns each
grade
multiplied by 3There is no
tripled
variable acting as an intermediate stepreturn
is omitted