JavaScript : Control Statement And Loops

 


:---- Control Statement & Loops :----

If..Else
Switch Statement
While Loop
Do-While Loop
For Loop
For in Loop
For of Loop
Conditional (ternary) operator

1. If else :-
The if statement executes a statement if a specified condition is truthy.
If the condition is falsy, another statement can be executed.

var tommorow = "sunny";
if(tommorow=="rain"){
    console.log("take an umberalla");
}else{
    console.log("No need to take an umberalla")
}


var area = "triangle";
var PI = 3.14;
var l = 5;
var b = 4;
var r = 3;

if(area =="circle"){
    console.log(PI*r**2);
}else if(area == "triangle"){
    console.log(l*b/2);
}else if(area == "rectangle"){
    console.log(l*b);
}else{
    console.log("Please enter valid Data");
}


Question :- what is truthy and falsy value in JavaScript .
We have total 5 falsy value in javaScript 
0 , "" , undefined , null , NaN , false 

if (true) {
    console.log("We Loss the game");
}else{
    console.log("We won the game");
}

2. Conditional (ternary) operator
The conditional (ternary) operator is the only JavaScript 
Operator that takes three operands. 
This is Short Hand of If else

var age = 31;
console.log((age>=18) ? "you can vote" : "You can't vote") ;

3. Switch Statement :-
Evalutates an expression , matching the expression's value to 
a case clause, and executes statements associated with the case.

var area = "triangle";
var PI = 3.14; l = 5; b = 4; r = 3;

switch(area){
    case "circle":
        console.log("The area of circle is " + PI*r**2)
        break;
    case "triangle":
        console.log("The area of triangle is " + l*b/2);
        break;
    case "rectangle":
        console.log("The area of rectangle is " + l*b);
        break;
    default:
        console.log("Please enter Valid Data");
}

 break
Terminates the current loop, switch or label
statement and transfers
Program control the statement following the terminated statement.

4. While Loop Statement :-
The while Statement creates the loop that execute a specified statement 
as long as the test condition evaluates to true.

var num=0;
while (num<=100) {
    console.log(num); // infinite Loop
    num++;
}

5. Do-While Loop Statement :-

var num = 0;
do {
    console.log(num);
    num++;
} while (num<=10);

6. For Loop Statement :-

for(var num = 0; num<=10 ; num++){
    console.log(num);
}

Challange Time :-

Q. JavaScript program to print table for given number
(8 and 9) using for Loop.

for(var x = 1; x <= 10; x++){
    var tableOf = 8;
    console.log(tableOf + " x " + x + " = " + (tableOf * x));
}

for(var num = 1; num<=10; num++){
    tableOf = 9;
    console.log(tableOf + " x " + num + " = " + tableOf*num);
}