Loops and Conditions
Now that we have understood the basic datatypes and operations of JavaScript, we can start learning about other constructs. This section will cover loops and conditions.
To clear the code in the console, type and enter clear();
or hit ctrl
+ L
. This will still keep any variables you declared earlier.
To write multiple lines without executing them one at a time, hit ctrl
+ enter
(or cmd
+ return
for Mac) after every line instead of just enter
. This will be useful for the this and the next few sections.
Conditionals
Conditionals are a set of statements that execute different blocks of code based on the evaluation of one or more boolean expressions. In simpler words, if something is true then one thing happens otherwise something else happens.
The syntax for conditional statements in JavaScript is as follows:
Example:
Ternary operation
This is an operation that operates on 3 operands, specifically to allow the evaluation of a conditional statement in a single line. Like any other operation, ternary conditions can be nested. The syntax is as follows:
Example:
Loops
A loop is a block of code that gets executed repeatedly until an end condition is satisfied. There are two types of loops in JavaScript, the for
loop and the while
loop. The syntax for each is as follows:
An example of a for loop is as follows:
The loop above will print out numbers from 0 to 10 one by one. As you can see, first the counter is declared (let i = 0
), then the limit is defined (loop keeps executing as long as i < 11
), and then the step is defined (i
is incremented by 1 each time; i++
). The eventual output will look like this:
An while loop that does the same thing as the for loop above would be as below:
Note that here, the counter variable declaration needs to be done outside the loop, and the step is defined inside the loop. This is because the while loop only has a boolean expression in its keyword call. Omitting to declare the counter variable will lead to a ReferenceError: i is not defined
. On the other hand, omitting the step will cause an infinite loop, since the value of i
will never change and is always less than 11.
In a for loop, the step can be of any size and can involve valid operation:
The above code prints out numbers backwards from 1024, each time dividing k
by 2, as long as k
is greater than 1.
The counter variable can also be of any type, and you can declare multiple counter variables:
Here i
increases by 1 each time from 0 to 4 (stopping at 5) while j
decreases by 3 each time starting from 15 until the loop ends.
A loop involving strings:
This loop prints every 3rd character of str
, starting from the 1st one. The same result can be achieved with a for
loop:
Similar results can be achieved with an array.
Next steps
In the next section, we'll look at functions, their types, and how to declare and use them.
Last updated