JavaScript array .map() method explained with examples
JavaScript .map() Method
There are several ways to iterate through datasets in JavaScript, including for loop
andforEach()
methods.
The.map()
method is one of the most popular methods..map()
creates an array of items in the parent array by calling a specific function on them. Unlike mutating methods,.map()
creates a new array rather than making changes to the array being called.
Syntax:
Whatever is returned by the callback function is placed in the new array at the same index.
Normally, we take the items from the original array and modify them somehow. When dealing with arrays, .map()
method has many applications.
Here are a few scenarios in which you might apply the.map()
method:
Extract data from an array
You can use .map()
method if you have an array of objects and want to extract a particular property from each object.
Example:
2) Create a new array of values
Use .map()
to create a new array of values based on a calculation or transformation of an existing array of values.
Example:
3) Transform an array of strings
Use .map()
method to transform the first character to uppercase.
Example:
.map() method in React
In React, we usually use.map()
to convert an array of raw data into an array of JSX elements that can be displayed on the page.
Using.map()
in React for creating components is better than just creating the components manually by typing them out. It can make our code more flexible and maintainable.
With .map()
, we can write concise, reusable code that can handle arrays of any size. As the data changes dynamically, the components update automatically, making our code more self-sustaining.
Example:
Output:
Conclusion
In this article, we explored JavaScript .map( )
method and its various applications. You can write more effective and concise code if you understand .map()
method.
I really hope you found this article helpful. If you have any questions or suggestions, kindly leave a comment. For more content like this, follow me, Ishrat Umar.
Happy learning!