Java Reference
In-Depth Information
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. This is an extremely important concept to understand, and you'll see why in Chapter 10
when you learn about events.
summarY
In this chapter you concluded your look at the core of the JavaScript language and its syntax.
Everything from now on builds on these foundations, and with the less interesting syntax under
your belt, you can move on to more interesting things in the remainder of the topic.
The chapter looked at the following:
Functions are reusable bits of code. JavaScript has a lot of built‐in functions that provide pro-
grammers services, such as converting a string to a number. However, JavaScript also enables
you to define and use your own functions using the function keyword. Functions can have
zero or more parameters passed to them and can return a value if you so wish.
Variable scope and lifetime: Variables declared outside a function are available globally—
that is, anywhere in the page. Any variables defined inside a function are private to that
function and can't be accessed outside of it. Variables have a lifetime, the length of which
depends on where the variable was declared. If it's a global variable, its lifetime is that of
the page—while the page is loaded in the browser, the variable remains alive. For variables
defined in a function, the lifetime is limited to the execution of that function. When the func-
tion is finished executing, the variables die, and their values are lost. If the function is called
again later in the code, the variables will be empty.
Identifier lookup: When you use a variable or function, the JavaScript engine goes through
the identifier lookup process to find the value associated with the identifier.
Functions are first‐class citizens in JavaScript. You can assign functions to variables and pass
them to other functions.
 
Search WWH ::




Custom Search