Array Functions - map: Converting Celsius to Fahrenheit Made Easy!
Hey there, friend! In our previous tutorials, we explored the world of arrays and functions. Now, let's take it to the next level with Array Functions - map. Are you ready to convert a list of temperatures from Celsius to Fahrenheit with ease?
Your Task: Write a JavaScript code in the index.js file to convert an array of Celsius temperatures to Fahrenheit using the map function.
Step 1: Create an array of Celsius temperatures
Open your index.js file and create an array of Celsius temperatures:
const celsiusTemperatures = [0, 10, 20, 30, 40]
Step 2: Define a function to convert Celsius to Fahrenheit Create a function that takes a Celsius temperature as an argument and returns the equivalent Fahrenheit temperature:
const celsiusToFahrenheit = (celsius) => (celsius * 9) / 5 + 32
Step 3: Use the map function to convert the array
Now, use the map function to apply the celsiusToFahrenheit function to each element in the celsiusTemperatures array:
const fahrenheitTemperatures = celsiusTemperatures.map(celsiusToFahrenheit)
Step 4: Log the result
Log the resulting fahrenheitTemperatures array to the console:
console.log(fahrenheitTemperatures)
Run the code! Click the Run button to execute your code. You should see the converted Fahrenheit temperatures in the console.
Expected Output:
[ 32, 50, 68, 86, 104 ]
How it works:
The map function takes a callback function (in this case, celsiusToFahrenheit) and applies it to each element of the array. The resulting array is a new array with the converted values.
Real-world example:
Imagine you're a weather forecaster, and you need to convert a list of Celsius temperatures to Fahrenheit for a weather report. With the map function, you can easily convert the entire list in one line of code!
You did it! You've successfully used the map function to convert a list of Celsius temperatures to Fahrenheit. Pat yourself on the back!
Now, are you ready to learn about the filter function? Stay tuned for the next tutorial!
Tests