HTML and CSS Reference
In-Depth Information
In the next section, you'll learn how to work with comparison operators to compare
one value with another.
Problem Solving: eval() or not eval() ?
The eval() method is a quick and easy way to evaluate text strings of numeric expressions
and return their numeric values. However, perhaps no JavaScript method has been more
misused than the eval() method. The general syntax of the eval() method is
eval( string )
where string is a text string that contains JavaScript code to be run by browsers. This
code can be a mathematical expression as discussed earlier, but it also can be a collection
of JavaScript statements such as the following:
eval(“x = 5; document.write(x)”);
As a result of running this statement, a browser would write the value 5 to the Web docu-
ment. You can make the text string itself a variable, as in the following statements that
use eval() to create a document.write() command that writes the value 10 to the Web
var y = 10;
eval(“document.write(“ + y + “)”);
The basic appeal of eval() is that it is a way of using JavaScript to itself write JavaScript
code. That code then can be altered in response to events initiated within a browser or by
a user. You'll often find legacy pages using eval() extensively to perform these types of
programming tricks. However, using eval() for this purpose is greatly discouraged for the
following reasons:
The code runs more slowly and uses up resources because there is no opportunity for the
browser to compile or cache the code contained in the eval() method.
• Storing code within the eval() method is a security breach, opening your program to
malicious code that can be inserted from outside agents.
• Code within the eval() method is not available to debugging tools in case of a
program error.
Almost anything that can be done using eval() also can be done with properly writ-
ten code, avoiding the security breaches and other problems associated with eval() . In
general, you should use eval() only for well-defined tasks such as evaluating an expression
that can be evaluated in no other way. Several sites on the Web provide valuable work-
arounds to avoid the misuse of the eval() method.
Working with Conditional, Comparison, and
Logical Operators
Hector wants the countdown clock to display the current time using 12-hour format
rather than 24-hour format. In 24-hour format, the hour values range from 0 hours (repre-
senting 12:00 a.m.) up to 23 hours (representing 11:00 p.m.). The time 14:35 in 24-hour
format is equivalent to 2:35 p.m. in 12-hour format. To convert 24-hour time to 12-hour
time, the code needs to apply the following rules:
• If the hour value is less than 12, add the suffix a.m. ; otherwise, add the suffix p.m.
• If the hour value is greater than 12, subtract 12 from the value.
• If the hour value is equal to 0, change it to 12.
Search WWH ::

Custom Search