Techoceanhub logo

Control Flow in Javascript

If-Else Statement

The if-else statement evaluates a condition and executes a block of code if the condition is true. If the condition is false, it optionally executes an alternate block of code specified by else.

let hour = new Date().getHours();
let greeting;

if (hour < 12) {
    greeting = "Good morning!";
} else if (hour < 18) {
    greeting = "Good afternoon!";
} else {
    greeting = "Good evening!";
}

console.log(greeting);

In this example:

  • The current hour of the day is fetched using new Date().getHours().
  • Depending on the value of hour, a different greeting message is assigned.
  • The if condition checks if hour is less than 12, else if checks if hour is less than 18, and else covers all other cases.

Switch Statement

The switch statement evaluates an expression against multiple possible case values and executes the corresponding block of code for the first matching case. It also has an optional default case that executes if no cases match.

let day = new Date().getDay();
let dayName;

switch (day) {
    case 0:
        dayName = "Sunday";
        break;
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    case 4:
        dayName = "Thursday";
        break;
    case 5:
        dayName = "Friday";
        break;
    case 6:
        dayName = "Saturday";
        break;
    default:
        dayName = "Unknown";
}

console.log("Today is " + dayName);

In this example:

  • new Date().getDay() retrieves the current day as a number (0 for Sunday, 1 for Monday, and so on).
  • The switch statement checks the value of day and assigns dayName accordingly.
  • Each case represents a different day of the week, and default handles any unexpected values.

Both if-else and switch statements are essential for controlling the flow of execution in JavaScript based on different conditions or values. They provide flexibility in how your program responds to varying situations, enhancing its functionality and logic.

Share:

Categories

Archives

Related Posts

Array Destructuring

Array Destructuring Array destructuring is a powerful syntax introduced in ES6 that allows you to unpack elements from an array

Read More »

Explore our Affiliated partner links

hostgator website plan

Hostgator

Best Website hosting plans & Best for 24/7 support.

hostinger webhosting plan

Hostinger

Reasonable website hosting packages for small business & 24/7 Email support

Elementor pro

Design Worpdress website quickly using Elementor Builder and AI

buy elementor website templates

Buy Elementor Website Template

Buy ready made Elementor Website Template from us & Get Free Elementor pro licence for 1 year .