JavaScript’s
predefined functions represent a collection of useful, general-purpose abstractions
nthe programmer can add additional abstractions via
user-defined functions
nonce defined, a user-defined function can be used the
same way as a predefined function
n
ne.g., consider converting a temperature from Fahrenheit
to Celsius
p tempInCelsius = (5/9) * (tempInFahr - 32);
function
FahrToCelsius(tempInFahr)
// Assumes: tempInFahr is a
temperature in Fahrenheit
// Returns: the equivalent
temperature in Celsius
{
return (5/9) * (tempInFahr - 32);
}
this expression & assignment
could be used whenever we want to convert but it requires remembering the formula every time.
instead, we could define a function to encapsulate the
calculation
We could then call that function whenever a conversion
was needed
freezing = FahrToCelsius(32);
current = FahrToCelsius(78);