The most useful control statement is the decision. This statement can create a fork in the program logic.This fork has one condition and two branches. The condition is a Boolean expressions. When the expression is evaluated to "true", first branch is executed. When condition becomes "false" the second branch is executed.Please study the diagram below and the example to understand better this statement:
decision diagram
/* demo for "if" statement */
function greater(x, y) {
let message
/* use conditional expression */
if (x > y) {
message = "yes! "+ `${x} is greater than ${y}` // True branch
} else {
message = "no! " + `${x} is not greater than ${y}` // False branch
}
return message
}
/* call function with arguments */
console.log(greater(10,20)) // expected: no
console.log(greater(20,10)) // expected: yes
Single branch: We can improve the code to show how a decision statement can work with just one branch.By using initial value "wrong" we assume that first parameter x is not greater than second parameter y.Then we test the condition and change the default value to "good" when the condition is true.This will simplify the function without loosing its logic. It will produce the same results as previous version.
/* demo for "if" statement */
function greater(x, y) {
let message = "no"
/* use conditional expression */
if (x > y) {
message = "yes" // one branch
}
return message
};
/* call function with arguments */
console.log(greater(10,20)) // expected: yes
console.log(greater(20,10)) // expected: no
Concept for this statement comes from "switch radio button" that you can rotate to select a channel. We use a "switch" statement to split a logical path into multi-path workflow.The criteria for switching is a numeric variable that may take different values.For each value we create one "case". When value match with case selector then we execute the block.
Switch Diagram
Example:
In this example for each day number from 0 to 6 we get the day name in English.
/* determine current day*/
function get_day(day) {
let result = "";
switch (day) {
case 1:
result = "Monday";
break;
case 2:
result = "Tuesday";
break;
case 3:
result = "Wednesday";
break;
case 4:
result = "Thursday";
break;
case 5:
result = "Friday";
break;
case 6:
result = "Saturday";
break;
default:
result = "maybe is Sunday";
}
return result;
}
var today = new Date();
console.log(get_day(today.getDay()));
In this example we detect a workday from a weekend day. The cases are executed top down if a break do not exist. In all cases 1,2,3,4,5 we have workday in cases 0 or 7 we have WeekDay. This technique is called fall through.
/* determine if is weekend */
function get_day(day) {
var result = "";
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
result = "WorkDay";
break;
case 0:
case 6:
result = "Weekend";
break;
default:
result = "Error";
}
return result;
}
var today = new Date();
console.log(get_day(today.getDay()));
For/Loop Repetition
Note: In JavaScript we have five repetitive statements:
Execute a block of code for a specific number of times. This loop is controlled by an integer variable that is local to the block. In next example "i" play the role of control variable.Initial value is 0 and maximum limit is 5. When i == 5 the repetition will end.After the loop, control variable is out of scope.
//initial statement
var text = ""
for (var i = 0; i < 10; i++) {
//first block
text = "i = " + i;
if (i == 5) {
console.log("break")
break
}
//second block
if (i > 3) {
console.log("continue")
continue
}
//third block
console.log(text)
}
//next statement
console.log("final i=" + i);
For statement has 3 parts:
Control Variable:
for (let i = 0; i < 5; i++) {
text = "i = " + i;
console.log(text)
}
console.log(i); // error: i is not defined
This statement uses a visitor: x that enumerate members of an object. In next example we scan properties of a person object using "for in" loop and display each value.
var person = {first_name:"John", last_name:"Doe", age:25};
let text = "";
for (let x in person) {
console.log(x);
text += person[x]+" ";
}
console.log(text);
Note: In this example we use in operator to iterate over an object person. The "text" variable starts empty and accumulate data from person attributes. Notice x is not a number but instead a string that have values: first_name, last_name or age. To get the value we use person[x].
To iterate over values of an array you can use "for…of" loop. This is a bit different than "for…in" and you have to understand both before use them with array object. Notice an array in JavaScript is also an object so you can use both these statements with different results:
/* array traversal */
var array = [4,5,6];
// read keys: '0', '1', '2'
for (element in array) {
console.log(element);
}
console.log(typeof(element)) // 'string'
// read values: 4, 5, 6
for (element of array) {
console.log(element);
}
console.log(typeof(element)) // 'number'
Notice: The difference is:
It is a repetitive statement that execute as long as one condition is true. When the condition becomes false the statement will stop and control is given to next statement. If the condition is false in the first place, the loop will never execute.
Repetition Diagram
let i = 2;
while (i < 10) {
console.log("i = " + i);
i++;
}
console.log(i); // 10
This is a repetitive statement that execute at least once. It is controlled by a condition that evaluate only after first execution. When the condition becomes false, the repetition stop and control is given to the next statement.This statement is harder to understand so I have made a diagram for you.
do-while diagram
let i = 2;
do {
console.log("i = " + i);
i++;
} while (i < 10);
Try/Catch is a control statement that is branching the code in case of error. We use this statement to create error handlers. Error handling is the process of responding to and recovering from runtime errors in a program. This allows the program to continue running despite encountering some errors. Developer can chose what particular exceptions can be handled and what other exceptions will actually stop the program.
try-catch diagram
try {
// Some code that may cause an error
}
catch(error) {
// Handle the error
}
finally {
// Optional - always execute this code
}
try {
let a = 5;
if (a === 5) {
throw 'Variable a is 5';
}
}
catch(err) {
console.log(err);
}
finally {
console.log("finally block is executed");
}
Read next: Objects