JavaScript 101: Conditionals and Loops

javascript-logo

This article is part of the JavaScript 101 series, you can find the previous part on the following link: JavaScript 101: Variables and Data Types.

Conditionals

In the programming conditional statement, conditional expression or simply a conditional is a feature, which performs different computations whether a boolean condition is true or false. A conditional is sometimes referred to as an "if-else".

Let's see a simple example

if(boolean){
  //if boolean is true do this
  return 'It is true'
}else{
  //else do this
  return 'It is not true'
}

if-else

Conditionals exist in other forms besides the if-else. For example, the switch statement can be used as a shortcut for a couple series of if-else statements.

Loops

A loop is a sequence of statements which is specified once but which may be carried out several times in succession. The code inside the loop is computed a specified number of times (for each of a collection of items, until some condition is met or indefinitely). There are a couple of types of loops most used are: "for loop", "while loop" and "for each".

A for loop repeats until a specified condition evaluates to false. A for statement looks as follows:

for (var i = 0; i < 5; i++){
  console.log(i)
}

And we got:

0
1
2
3
4

A while loop executes its statements as long as a specified condition evaluates to true. A while statement looks as follows:

var i = 0
while (i < 5){
  console.log(i)
  i = i + 1
}

And again we got:

0
1
2
3
4

And the last one foreach calls a function(we will see how functions work in later chapters) once for each element in an array, in order. A foreach statement looks as follows:

var numbers = [1, 2, 3, 4]
numbers.forEach(myFunction);

function myFunction(item, index){
  console.log(item)
}

And again we got:

0
1
2
3
4

Conditional and loops are building blocks for Computer Science.

Next part: JavaScript 101: Functions.




#javascript #javascript101

Author: Aleksandar Vasilevski |

Loading...