function convertToFahrenheit(celsius) {
return (celsius * 9 / 5) + 32;
}
function convertToCelsius(fahrenheit) {
return (fahrenheit - 32) * 5 / 9;
}
function convertTemperature(degrees, unit) {
if (unit === 'C') {
const result = convertToFahrenheit(degrees); /* How can we use "degrees" here? */
return `${result}F`;
} else if (unit === 'F') {
const result = convertToCelsius(degrees); /* How can we use "degrees" here? */
return `${result}C`;
}
}
console.log(convertTemperature(25, 'C'));
console.log(convertTemperature(86, 'F'));
As you can see in the above code, there were two functions defined – convertToFahrenheit(celsius) and convertToCelsius(fahrenheit). But later on, when these functions were called, there parameter names were changed to degrees. How is it possible?
At first, I thought that , when the functions were called inside the new function convertTemperature(degrees, unit), the argument passed for the convertToFahrenheit(celsius) and convertToCelsius(fahrenheit) was "degrees" itself. Am i correct?
2
Answers
The arguments are called
degrees
. The parameters are calledcelcius
andfahrenheit
. The name of the argument does not need to match the name of the parameter. This should be especially obvious when you consider that an argument doesn’t need to be associated with a name at all:The object that
degrees
holds/points to is passed into, for example,convertToFahrenheit
. That passed object is then stored inside thefahrenheit
parameter variable. At that point,degrees
andfahrenheit
are two names that both refer to the same object.You’re correct, you’re passing ‘degrees’ into the function. Function calls do not require the actual name of the parameter, you just put the value, in this case a number.
When you create a function, you use the parameter names as a stand in for the value you’re going to get when you call the function.
See how on the bottom lines you use 25 and 86 in a function call. Then within that function it uses those numbers under the name degrees. Then it calls the top 2 functions which use those numbers under the names celsius and fahrenheit, but the whole time they are 25 and 86.