home

JavaScript If Statement

If statement executes a statement if a specified condition is true. If the condition is false, another statement can be executed, that’s is called else statement that we covered in below if else condition section.

Javascript If/else Statements
var num = 18;
            if( num > 16 ){
               document.write("18 is less than 20");
            }
         //-->
 // if you want to test, just change variable to different value and play with conditions

If else statement

Else statement is the block of code to be executed when if condition is false.

if (condition){
   statement1 – executes if the statement is true
   }else{
   statement2 – executes when the statement gets false
}

Condition - this is an expression, will work based condition true or false. Statement1 – this will executes when the conditions is true. To write multiple condition use block statement ({….}). Statement2 - will executes when the statement is false.

Example Code

var car = "Land Rover";
            if( book == "BMW" ){
               document.write("BMW Car");
            }
         
            else if( book == "Land Rover" ){
               document.write("Land Rover Car");
            }
              else if( book == "mercedes benz" ){
               document.write mercedes benz  Car");
            }
               else{
               document.write("Local Brand");
            }
// output will be Land Rover Car, because statement matching with variable ("Land Rover").

Set variable to different value and then try...

Javascript loops and array, condition and function example code

Learn loops concepts with simple examples like how to create new array and how store objects(multiple data) as a single array and calling to use in the function.

Javascript code

i=0;
// while loop//
while(i<5){
document.write(i+"is less then to 5"+"<br>");
i++;
}
// Array //
var array = new Array('anji','arun');
document.write("my name is"+array+"<br>");

//for loop//
for(i=0; i<5; i++){
document.write(i);
}
// if condition//
if(i<=5){
alert('i less then 5')
}else{
alert('i gretter then to 5');
}

// Basic function example code//
function myclick(){
alert("clicked on button");
}