Beginner in JS, learning from a book, passing functions example is not clear to me. This is the code:
function toCentigrade(degFahren) {
var degCent = 5 / 9 * (degFahren - 32);
document.write(degFahren + " Fahrenheit is " +
degCent + " Celsius.<br/>");
}
function toFahrenheit(degCent) {
var degFahren = 9 / 5 * degCent + 32;
document.write(degCent + " Celsius is " +
degFahren + " Fahrenheit.<br/>");
}
function convert(converter, temperature) {
converter(temperature);
}
convert(toFahrenheit, 23);
convert(toCentigrade, 75);
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 4, Example 2</title>
</head>
<body>
</body>
</html>
I don't understand the part with function convert. This is the explanation from the book:
Admittedly, you could use these functions as is without any problem, but that wouldn’t result in a very interesting example. Instead, the third function, convert(), will be used to execute toCentigrade() and toFahrenheit():
function convert(converter, temperature) { return converter(temperature); }
This function takes the first parameter, converter, and uses it as a function. The second parameter, temperature, is then passed to converter() to perform the conversion and write the results to the document. The final two lines of code use convert() and pass it the appropriate converter function and temperature value:
convert(toFahrenheit, 23); convert(toCentigrade, 75);
Although this is certainly a more complex solution to a relatively simple problem, it demonstrates the fact that functions are values in JavaScript. We can assign them to variables and pass them to other functions.
What I don't understand is probably the essence of this example - why the parameters are (converter, temperature)
, how can we assign temperature
parameter to converter
(which is now a function inside a function) when temperature
is not defined - it's just a word (for me), how after that convert
function is used for converting (toFahrenheit
, 23 and toCentigrade
, 75): for example, the function toFahrenheit
knew that it should look up to convert
function for a number needed for writing conversion result to a webpage, how? I mean, how exactly we connected all three functions in this example which resulted in printing the results to a webpage?
Basically, I'm lost with all of this part:
function convert(converter, temperature) {
converter(temperature);
}
convert(toFahrenheit, 23);
convert(toCentigrade, 75);