Java Reference
In-Depth Information
Variable scope and lifetime.
Variables declared outside a function are available globally — that
is, anywhere in the page. Any variables defi ned 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 defi ned in a function,
the lifetime is limited to the execution of that function. When the function has fi nished being
executed, the variables die, and their values are lost. If the function is called again later in the
code, the variables will be empty.
Exercise Questions
Suggested solutions to these questions can be found in Appendix A.
1.
A junior programmer comes to you with some code that appears not to work. Can you spot
where he went wrong? Give him a hand and correct the mistakes.
var userAge = prompt(“Please enter your age”);
if (userAge = 0);
{
alert(“So you're a baby!”);
}
else if ( userAge < 0 | userAge > 200)
alert(“I think you may be lying about your age”);
else
{
alert(“That's a good age”);
}
2.
Using document.write() , write code that displays the results of the 12 times table. Its output
should be the results of the calculations.
12 * 1 = 12
12 * 2 = 24
12 * 3 = 36
...
12 * 11 = 132
12 * 12 = 144
3.
Change the code of Question 2 so that it's a function that takes as parameters the times table
required and the values at which it should start and end. For example, you might try the four
times table displayed starting with 4 * 4 and ending at 4 * 9.
4.
Modify the code of Question 3 to request the times table to be displayed from the user; the code
should continue to request and display times tables until the user enters -1 . Additionally, do a
check to make sure that the user is entering a valid number; if the number is not valid, ask the
user to re-enter it.
Search WWH ::




Custom Search