Program Structure Eloquent JavaScript

Eloquent JavaScript Ch.2: Control Flow

In the second chapter of Eloquent JavaScript, we will learn about variables, functions and flow control in JavaScript. They are all essential, make sure you understand all of them and type all example code to your JavaScript console to try them out.

Make sure you’ve read chapter 1:

Ch.1 Value Types & Operators

Expression and Statement

A fragment of code that produces a value is called an expression.


A statement is a whole sentence formed by one or more expressions.


The semicolon at the end indicates the end of a sentence(statement). But in JavaScript, you can omit the semicolon.


A program uses variables to remember things(to hold value).

var sum = 5 + 5;

The keyword var defines a variable, sum. And the = operator gives a value(5 + 5, which is 10) to this variable. By the way, this is also a statement.

A variable can be used as an expression.

var sum = 10;

The value of a variable can be changed:

var today = "Monday";
today = "Tuesday";

var total = 10;
total = total - 5;

If you don’t give a value to a variable, it will be undefined.

“A single var statement may define multiple variables. The definitions must be separated by commas.”

var first = 1, second = 2;

The rules for naming a variable

  1. It can’t be a keyword, such as var.
  2. It can’t have any space.
  3. It can’t start with a digit, but it can contain digits.
  4. It can’t include punctuation, except for $ and _.

When naming variables, it’s better to follow the convention in JavaScript: to capitalise every word except the first.

var myFirstVariable;

Keyword list

These keywords are reserved by JavaScript, you can’t use any of them aa the name of a variable.

break case catch continue debugger default delete do else false finally for function if implements in instanceof interface let new null package private protected public return static switch throw true try typeof var void while with yield this

The Environment

The collection of variables and their values that exist at a given time is called the environment.

When a program starts, JavaScript creates an environment for the program. The environment contains not only data(values, variables, etc) for the program, but also data of the surrounding system, such as variables and functions of the browser.


A function is a piece of program wrapped in a value. The alert in the following example is a function:

alert("Hello world!");

The value between the parentheses(“Hello world!”) is called an argument. It will be used inside the function. In this example, the alert will use “Hello world!” as output strings.

We have already seen the console.log function. It can takes more than one arguments.

var x = 30;
console.log("the value of x is", x);

We will learn more about functions in the later chapters.

“When a function produces a value, it is said to return that value.”

The function Math.max takes several numbers and returns the greatest.

console.log(Math.max(5, 9)); 

// > 9

The returned value can be used in larger expression:

console.log(Math.max(2, 4) + 10);
// > 14

Let’s see two more functions: prompt and confirm.

confirm: ask an OK/Cancel question with a popup window. Returns true if the user click OK and false if the user click Cancel.

confirm("Shall we, then?");

prompt: ask an open question. The first argument is the question, the second is the default text, the user can input text as return string.

prompt("Tell me everything you know.", "...");

Control Flow

There are two ways to control the flow of your program:

  1. Conditional execution
  2. Looping

Conditional Execution

There are two types of conditional executions:

  1. if…else…
  2. switch
var moveOn = confirm("Move on?");

if (moveOn)
  alert("You want to move on!");
  alert("You don't want to move on!");

If the user clicks on the OK button, the first alert will be executed, otherwise the second.

The else part can be omitted, if you don’t need it.

You can chain multiple if/else:

var num = Number(prompt("Pick a number", "0"));
if (num < 10)
else if (num < 100)

If you want to chain many if/else together, you can use switch instead.

switch (prompt("What is the weather like?")) {
  case "rainy":
    console.log("Remember to bring an umbrella.");
  case "sunny":
    console.log("Dress lightly.");
  case "cloudy":
    console.log("Go outside.");
    console.log("Unknown weather type!");

Every case should has a break. The default session will be executed, if none of the above matches.


Looping is used to repeat a piece of program.

There are three loops in JavaScript:

  1. While
  2. do
  3. for


var number = 1;
while (number <= 10) {
  number = number + 1

This will output 1 to 10. Every time the number increase by 1, until it reaches 11 and the while will not be executed any more.


var number = 1;

do {
  number = number + 1;
} while (number < 10);

This piece of code does the same thing. Pay attention to two things. First, the do statement will be executed at least once. Second, the condition is number < 10, rather than number <= 10 as in the while statement, why is that?


for (var number = 0; number <= 10; number = number + 1)

The for statement put all the controlling elements in the parentheses.


If you want to break out of a loop, you can use the break.

for (var current = 20; ; current++) {
  if (current % 7 == 0)

current++ means current = current + 1;

You can also use class=”lang:js decode:true crayon-inline” >current– , as well as:

current += 1;
current *= 1;
current -= 1;


Comments will not be executed, it’s for human to make some notes. There are two types of comments in JavaScript:

// This is a single line comment.

/* This is
a multiple line


In this chapter, we’ve learned about variables, the basic of functions, flow control. Make sure you try all of them in your JavaScript Console.

Next: Functions

In the next chapter, we will learn more about functions. It’s one of the most important element in JavaScript.

Tagged with: , , , ,

No comment yet, add your voice below!

Leave a Reply