DEV Community

pranavinu
pranavinu

Posted on

if-else,switch,and Ternary opreator in JS

if statement:

  • It is a conditional statement,that excute when the condition is true

if-else statement:

  • It is to check the multiple condition

else statement:

  • It excute when the condition is false

let mark =76;

if(mark>=90)
{
console.log("O")

}
else if(mark>=80)
{
console.log("A")

}
else if(mark>=70)
{
console.log("B")

}
else if(mark>=60)
{
console.log("C")

}
else if(mark>=50)
{
console.log("D")

}
else
{
console.log("No Grade")

}

switch:

  • It check the a variable value against multiple case value and excute the matching case

let op ='+';
let a=5;
let b=10;
switch(op)
{
case '+':
console.log(a+b);
break;
case '-':
console.log(a-b);
break;
case '*':
console.log(a*b);
break;
default :
console.log();
break;
}

Ternary operator:

  • It is an alternative of if-else statement
  • It is to check the simple if-else situation Syntax: variable = condition ? true value : false value;

let num=23;
let result = num%2==0 ? "even":"odd";
console.log(result);

Truthy

  • if a condition has a true value,it is treated as true

Truthy values:

  • non-zero numbers
  • non-empty strings
  • boolean(true)
  • arrays []
  • objects{}

Falsy

  • if a condition has a false value,it is treated as falsy

Falsy values:

  • boolean(false)
  • 0
  • -0
  • empty
  • null
  • undefined +nan

Top comments (0)