You are previewing Eloquent JavaScript.

Eloquent JavaScript

Cover of Eloquent JavaScript by Marijn Haverbeke Published by No Starch Press
O'Reilly logo

Program Structure

One-line programs are not very interesting. When you put more than one statement into a program, the statements are executed, predictably enough, one at a time, from top to bottom. This program has two statements; the first one asks the user for a number, and the second one shows the square of that number:

var theNumber = Number(prompt("Pick a number", ""));
alert("Your number is the square root of " + (theNumber * theNumber));

The function Number converts a value to a number, which is needed in this case because the result of prompt is a string value. There are similar functions called String and Boolean that convert values to those types.

Conditional Execution

Sometimes, you do not want all the statements in your program to always ...

The best content for your career. Discover unlimited learning on demand for around $1/day.