If Else, Loop and Switch 💻

If Else

Use if else whenever you want to perform task conditionally.

Syntax

Condition can be anything like

Q. If number is even print EVEN else print ODD


Loop

Loop is the most important thing that I use most frequently in my projects to iterate over arrays.

Various types of loops that I use in development are :

  • for
  • for-in
    Gives current index on each iteration.
  • for-of
    Gives current value on each iteration.
  • forEach
    built in function of array.
    forEach function returns void.
  • map
    1. built in function of array.
    2. returns an array of values, which can be stored in variable.
    3. returns undefined if no value is returned.
  • filter built in function of array.
    returns array of values.
    If condition is matched, value is added to returned array.
    If condition does not match for any given values of array empty array is returned

Switch case

Use switch case when you have more values to compare.

Syntax

  1. expression is the value that should match the cases defined.
  2. If none of the cases matches the expression than default case runs. (Should always have a default case)
  3. If you notice the syntax you can see break keyword, that is used to simply to get out of the switch statement.
  4. If we dont use break keyword switch will move to the next case and if that case matches again it will run and execute the task to perform.

Let's understand this with the example:

Based on the name provided case is executed and it breaks out of it.

If we remove break from case 'bippan', lets see what happens.

After the case bippan is executed case sourav gets executed too because case bippan does not has a break keywork.

if name is not initialized default case runs.


That's all.

BYEE.👋