Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

480 LESSON 17: Introducing JavaScript


This example uses the Math object, another object built in to JavaScript. It provides a
number of methods that perform a variety of mathematical operations so that you don’t
have to write the code to perform them yourself. Math.sqrt() is a method that returns
the square root of a number. In this case, I subtracted the square root of 16 from the
square root of 25. You can enter any of these expressions in the Console and see the
results.

Variables


Thus far, I’ve been manipulating values and printing them directly to the page. The next
fundamental building block of writing scripts is temporary storage of those values so that
they can be reused. Like all programming languages, JavaScript supports the use of vari-
ables. A variable is a user-defined container that can hold a number, text, or an object.
Creating variables and retrieving their values is simple in the Console, as shown in Figure
17.5.

Input ▼
var message = "Message"
message

Output ▼


In that example, I created a variable called message and then printed its value by entering
it as an expression in the Console. You can also assign the results of an expression to a
variable:
var sum = 5 + 5;
And you can use variables in your exp ressions:
var firstName = "George";
var lastName = "Washington";
var name = firstName + " " + lastName;

FIGURE 17.5
A variable declara-
tion in the console.
Free download pdf