The if
statement
Conditional statements occur in almost all programming languages that we use today. These are simply statements that evaluate a certain condition and then execute code only if that condition is met.
JavaScript is no way behind. It supports conditonal statements out-of-the-box.
In this section, we shall see one of the most used and common conditional statement used in JavaScript — the if
statement.
if
statement executes code if a given condition is true.It denotes a conditional statement.
Here's the syntax to creating an if
statement:
if (expression) statement
We start with the if
keyword, followed by a pair of parentheses (()
). Inside these parentheses, we put an expression that is the condition to check.
If this condition evaluates to the Boolean value true
, the following statement
is executed.
statement
here is called the body of if
. while the preceding piece of code in the if
statement is called the header of if
.
In the last chapter on JavaScript Data Types, we came across Boolean values i.e true
and false
. Conditional statements are the biggest application of Booleans.
The if
statement evaluates the given expression and checks to see if it reduces down to true
. If it does, it means that the condition of the statement is met and therefore the following body is executed.
However, if the opposite happens i.e. the given expression evaluates down to false
, this means that the condition isn't met and hence the statement at the end of the if
statement isn't executed — it's simply ignored.
Let's consider a simple example.
We'll create a Boolean variable specifying whether today is a rainy day or not.
var isRaining = true;
For now, we put a dummy value inside this variable — true
.
However in a real world application, such as an app notifying the user of the weather and climatic conditions of a given location, this Boolean variable would be given a value very meaningfully, like by retrieving and parsing actual data from a satellite.
Anyways, with the Boolean in place, we'll now set up a simple conditional statement to alert the user that he/she should go out with an umbrella if it is about to rain today:
var isRaining = true;
if (isRaining) alert("Don't forget an umbrella!");
Notice how natural this code sounds. It says that 'if it is raining, alert the user to not forget an umbrella'.
As soon as we execute this code, we get an alert made. This is because the given expression isRaining
is true
.
So this was easy. What do you think?
One thing worthwhile mentioning here is that as per the syntactic rules of JavaScript, it's not required to put the body of if
on the same line as the header.
For instance, we could write the code above like this without having any effect on its semantics (i.e. meaning):
var isRaining = true;
if (isRaining)
alert("Don't forget an umbrella!");
The indentation is really handy — it helps us distinguish the if
statement's header from its body. In fact, more than just handy, it's a convention, used even in other programming languages with a similar C-like syntax as JavaScript.
But an even more mainstream convention for JavaScript (and other C-like-syntax languages) is to encapsulate the body inside a pair of curly braces as follows:
var isRaining = true;
if (isRaining) {
alert("Don't forget an umbrella!");
}
As we'll learn later on in this unit, besides a couple of other things, a pair of curly braces ({}
) represents a block statement in JavaScript.
It can be thought of a group for a sequence of statements.
So in the code above, the body of if
happens to be a block statement which contains just one statement, that is the call to alert()
.
By virtue of its readability and flexibility to be able to execute more than one statement, we'll stick to using a block statement as the body of if
, and almost all similar statements throughout the rest of this chapter and the rest of this course.
Coming back to if
, let's consider another example.
This time instead of using a Boolean value directly inside the if
's header, we'll use a relational expression that returns one itself.
The idea is that we ask the user to enter a number greater than 10
. If the input value is not greater than 10
, i.e. the requirement is not met, then we simply make an alert stating that the given input is invalid:
var num = Number(prompt('Enter a number greater than 10'));
if (num <= 10) {
alert('Invalid input');
}
while
loop, we'll extend this code to keep repeating the input prompt as long as the entered value is not valid.And this is if
.
As we shall see later on in the JavaScript Conditionals chapter, and even in general throughout this course, tons and tons of important ideas in the word of computing rely on the if
statement. It's totally impossible to imagine modern-day computing without if
!
But if
doesn't stand alone to claim this position. There is a similar statement that works together with if
in laying out complex conditions in a given piece of code.
That statement is called else
.
Let's explore it...
The else
statement
The else
statement is another conditional statement in JavaScript.
Unlike if
, it couldn't be specified alone — there has to be an if
statement preceding an else
.
So what's else
used for?
else
statement executes a piece of code if the condition in the preceding if
statement evaluates down to false
.In other words, if the condition mentioned in an if
statement fails, the corresponding else
block takes over. Can't get easier, can it?
Together, the if
and else
statements are generally referred to as if...else
statements.
The syntax of else
is pretty much similar to if
— just remove the condition, sinch it's not required in else
:
if (expression) statement;
else statement;
Alright, let's consider an example using else
.
We'll bring our rainy day example back and extend it to show two alerts — one when it is raining and one when it is NOT raining. In addition, we'll also change the dummy value to false
(previously it was true
) so that we could test the else
clause.
Here's the code:
var isRaining = false;
if (isRaining) {
alert("Don't forget an umbrella!");
}
else {
alert("No need for an umbrella.");
}
The moment we run the code, we get the second alert, just as we expected.
Also notice the body of else
. Just like that of if
, it's a block statement (denoted using {}
) as well and happens to be comprised of just one statement.
Over to the second example, again the same one we considered in the section above on if
.
Previously, if the user entered a number not greater than 10
, we made an alert specifying that the entered value is invalid. This time, we handle the other case as well by alerting the number if it is indeed greater than 10
:
var num = Number(prompt('Enter a number greater than 10'));
if (num <= 10) {
alert('Invalid input');
}
else {
alert(num);
}
Perfect!
Note that it's invalid to put an else
statement without a preceding if
statement.
Even logically, this sounds weird. We're used to sentences like 'if this, then that, or else that', not to sentences like 'else that' where the 'else' seems to appear out of nowhere.
Shown below is an invalid piece of code:
var num = Number(prompt('Enter a number greater than 10'));
else {
document.write(num);
}
The error here is the else
statement, which has no preceding if
statement.
The switch
statement
Apart from if..else
statements, there is another conditional statement in JavaScript called switch
.
switch
is useful when we have multiple equality cases to check a given value against.
switch
statement evaluates an expression and executes a matching case
block.case
is a new keyword that we've encountered. It's native to switch
statements — we can't use it outside the statement. It defines a case for the corresponding switch
.
Altogether, the syntax of a switch
statement is as follows:
switch (expression) {
case case1:
// code here
break;
case case2:
// code here
break;
...
case caseN:
// code here
}
We start with the switch
keyword followed by a pair of parentheses (()
) following a block of code. This is called the body of switch
. Here, we mention cases for the conditional statement.
A case begins with the case
keyword followed by a value to match the expression
mentioned at the start of the switch
statement with. If this value matches expression
, the corresponding block of code following the colon (:
) is executed.
The break
keyword serves to break execution out of the switch
statement once a case block is executed. It's redundant to give it in the last case block, since anyways, after executing the last case block execution moves out of the switch
statement.
We'll see the details to break
in the section below.
Anyways, let's consider a very basic example to clarify all this syntax theory.
We'll create a program where the user enters a three-digit number, that is an HTTP response code, and then gets back the corresponding response text returned.
var code = Number(prompt('Enter an HTTP response code:'));
var msg;
switch (code) {
case 200:
msg = 'OK';
break;
case 404:
msg = 'Not Found';
break;
}
document.write(msg);
For now only two response codes are supported: 200
which stands for the text 'OK', and 404
which stands for the text 'Not Found'.
If the user enters an HTTP response code that isn't covered by our code or that just doesn't exist at all in the HTTP standard, then nothing is displayed on the document.
How could we deal with such case as well?
Well, we need a default
case.
default
keyword, native to switch
, denotes a case block that gets executed when no other case gets matched.Let's the syntax for using default
:
switch (expression) {
case case1:
// code here
break;
case case2:
// code here
break;
...
case caseN:
// code here
break;
default:
// code here
}
The default case begins with the default
keyword (not with the case
keyword), followed by a colon (:
), followed by the case's block of code.
default
at the end of a switch
statement is just a convention — not a syntactic requirement.Alright, with default
understood, it's time to use it in the code above.
Recalling the problem, we needed to output a message saying 'This response code is not covered.', when the input number doesn't have a matching case block in the switch
statement.
var code = Number(prompt('Enter an HTTP response code:'));
var msg;
switch (code) {
case 200:
msg = 'OK';
break;
case 404:
msg = 'Not Found';
break;
default:
msg = 'This response code is not covered.'
}
document.write(msg);
One thing to remember while working with switch
is that using break
inside a case block totally depends on your need.
As some might think, it's not a syntactic requirement, although generally most of the switch
statements you'll encounter would have it included.
If you want multiple cases to execute the same piece of code, you mention the cases one after another and skip the break
statement in all but the last case block.
JavaScript is configured to search for a matching case block and then move on to the next case block without even checking whether it is a match or not. This flow of execution isn't an error or bug in the language — it's given purposefully to allow multiple case blocks to use the same block of code.
We'll see the details to all these concepts in the JavaScript switch
Statement chapter.
The for
loop
Conditional statements, as we saw above, are handy for many many practical-level use cases. Modern-day computing can't even be thought without them.
But they are not the only paramount idea in the world of programming. There exists another such idea which we call iteration or looping.
Let's see what it is.
It sits right at the heart of computer automation.
Nearly all modern languages provide utilities for iteration. JavaScript defines two keywords to cater to iteration needs: for
and while
.
In this section, we'll go over the former.
The for
keyword, generally referred to as the for
loop, defines a statement that is executed repeatedly as long as a condition holds.
It consists of three steps: variable declaration and initialization, followed by a condition to continue executing the loop, followed by an expression modifying the variables declared in the first step.
What are these three steps for?
Well, they just simplify writing code when we need to iterate a given number of times.
Here's the syntax:
for (initialization; condition; modification) statement
initialization
is a variable declaration and assignment, condition
is an expression that must evaluate to true
in order to execute statement
, and modification
is an expression evaluated at the end of each iteration.
As stated before, for
is generally used to iterate a given number of times.
In this way, it's syntax could be simplified as follows:
for (var counter = 0; counter < n; counter++) statement;
In the loop's header, first we declare and initalise a variable counter
to 0
(you'll need to name this variable something else in your code), then write an expression counter < n
to be checked before each iteration.
This expression would return true
exactly n
times as the reader could verify and hence, get statement
to be executed exactly n
times.
Finally, for the last statement in the header as well, we specify counter++
. This increments counter
by 1
at the end of each iteration so that at some point it becomes larger than n
and consequently results in the execution jumping out of the for
loop.
Without an incrementing expression, the condition counter < n
would always evaluate to true
and lead to what's known as an infinite loop.
Let's try to print the text 'Hello World!' out on the document 5 times using the for
loop:
for (var i = 0; i < 5; i++) document.write('Hello World!<br>');
Time to understand this code, starting with the very first thing — the header of the loop.
- In the header, we begin by declaring a variable
i
and setting it to0
. - Next up, we write
i < 5
since we need to iterate 5 times. This expression evaluates totrue
exactly 5 times (wheni
is0
,1
,2
,3
and4
). - Finally, we write
i++
to incrementi
with each new iteration.
As a whole, the statement document.write()
is executed 5 times.
Easy!
Just as we did with if
and else
above, we'll now use a block statement as the body of for
instead of using an actionable statement directly. That looks way more readable.
Here's the same for
loop shown above:
for (var i = 0; i < 5; i++) {
document.write('Hello World!<br>');
}
What do you say? Doesn't it look more readable?
Let's see one more example.
This time instead of outputting static messages, we'll generate them on-the-go in the loop's body using the counter variable i
.
The general form of each message will be 'This is iteration <i>' where <i> will be replaced by the number of the iteration (1
for the first iteration and so on).
Here's the code:
for (var i = 0; i < 5; i++) {
document.write('This is iteration ' + (i + 1) + '<br>');
}
Apart from iterating a given number of times, the for
loop is also used to iterate over iven sequences such as strings, arrays, etc.
The length
property of the sequence helps in defining the number of times to iterate.
The counter variable, which begins at 0
is used as the index to access each subsequent item in the sequence.
In the code below, we define an array nums
and log each of its items one-by-one using the for
loop:
var nums = [1, 3, 5];
for (var i = 0; i < nums.length; i++) {
console.log(nums[i]);
}
3
5
Let's try another example.
This time, we'll make two console logs for each item in an array lang
containing the names of some programming languages:
var langs = ['C', 'C++', 'Python', 'Java', 'JavaScript'];
for (var i = 0; i < langs.length; i++) {
console.log('Language #' + (i + 1) + ':');
console.log(langs[i]);
console.log('\n') // blank line
}
C
C++
Python
Java
JavaScript
for
in detail in the JavaScript for
Loop chapter.The while
loop
The second looping control structure provided by JavaScript is while
.
The while
keyword, also known as the while
loop, denotes a statement that is repeatedly executed until some condition becomes false
.
Syntactically, it's quite different from for
:
while (condition) statement;
We start with the while
keyword, followed by a pair of parentheses. In here, we specify a condition that must evaluate to true
in order for statement
to be executed.
Akin to for
, condition
is checked before each new iteration.
At the core level, both for
and while
continue iterating only if the given condition is met i.e. it evaluates down to true
. However, both are used for different purposes.
Difference between for
and while
for
, as we know, is more commonly seen when iteration is to be done on a given number of times, or over a sequence such as a string, or an array.
In contrary to this, while
is usually used when iteration is to be done an unknown number of times where a counter variable isn't required to keep track of the iteration.
An example of using while
would be to continue asking the user to enter a value in a prompt dialog until the entered value meets the desired criteria.
Below we set up a program that asks the user to input a programming language he/she knows in an input prompt. If the prompt dialog is canceled or given no value, we make an alert stating that the entered value is invalid and then display a prompt again. This goes on until the entered value is appropriate.
var lang = prompt('Enter a programming language:');
while (!lang) {
alert('Invalid input.');
lang = prompt('Enter a programming language:');
}
document.write('You know ' + lang + '.');
The expression !lang
returns true
if lang
is falsey i.e has a value that coerces into the Boolean false
. This happens if it is an empty string (''
) or the value null
.
In both these cases, the body of while
gets executed and consequently displays an input prompt again.
When the correct input is given, !lang
returns false
, execution jumps out of the loop (if it was inside the loop), and finally the input value is written out to the document.