map helper in javascript

Explore our JavaScript category, where you’ll find loads of helpful articles and tutorials for everyone, whether you’re just starting out or a pro developer. Learn about different JavaScript functions that can be used in various projects according to their specific requirements.
This JavaScript code demonstrates the use of the for loop and the map function to manipulate arrays. It also provides examples with an array of numbers and an array of objects representing cars with their models and prices.
1- For Loop for Doubling Numbers:
<script>
var numbers = [1,2,3];
var doubleNumbers = [];
for (var i = 0; i < numbers.length; i++) {
doubleNumbers.push(numbers[i] * 2);
}
console.log(doubleNumbers);
</script>
This part of the code uses a for loop to iterate through each element in the numbers array, doubles each number, and pushes the result into the doubleNumbers array. The final result is then logged to the console.
2- Map Function for Doubling Numbers:
<script>
var doubled = numbers.map(function(number){
return number * 2 ;
});
console.log(doubled);
</script>
This section achieves the same result as the previous for loop but using the map function. It creates a new array (doubled) by applying the provided function (doubling each number) to each element in the numbers array.
3- Map Function for Extracting Prices from an Array of Objects:
<script>
var cars = [
{ Model: 'Audi', Price: 'Cheap' },
{ Model: 'BMW', Price: 'Expensive' }
]
var prices = cars.map(function(car){
return car.Price;
});
console.log(prices);
</script>
In this part, the map function is used to extract the ‘Price’ property from each object in the cars array, creating a new array (prices) containing only the prices. The result is then logged to the console.
Overall, this code illustrates different ways to iterate over arrays and manipulate their elements using both a for loop and the map function.