0
0
Javascriptprogramming~15 mins

Switch vs if comparison in Javascript - Hands-On Comparison

Choose your learning style9 modes available
Switch vs if comparison
📖 Scenario: Imagine you are building a simple program that tells the day of the week based on a number from 1 to 7. You want to see how to use both switch and if statements to do this.
🎯 Goal: You will create a program that takes a number called dayNumber and prints the name of the day using both switch and if statements. This will help you understand how these two ways of making decisions work.
📋 What You'll Learn
Create a variable dayNumber with the value 3
Create a variable dayNameIf to hold the day name using if statements
Create a variable dayNameSwitch to hold the day name using a switch statement
Print both dayNameIf and dayNameSwitch to compare results
💡 Why This Matters
🌍 Real World
Programs often need to make choices based on values, like showing the day name from a number. Knowing both <code>if</code> and <code>switch</code> helps you write clear code.
💼 Career
Understanding decision-making in code is essential for all programming jobs. Using <code>switch</code> or <code>if</code> statements correctly helps you write readable and efficient code.
Progress0 / 4 steps
1
Create the dayNumber variable
Create a variable called dayNumber and set it to the number 3.
Javascript
Need a hint?

Use const dayNumber = 3; to create the variable.

2
Create dayNameIf using if statements
Create a variable called dayNameIf. Use if, else if, and else statements to set dayNameIf to the correct day name for dayNumber. Use these mappings: 1 = 'Monday', 2 = 'Tuesday', 3 = 'Wednesday', 4 = 'Thursday', 5 = 'Friday', 6 = 'Saturday', 7 = 'Sunday'. If the number is not 1 to 7, set dayNameIf to 'Invalid day'.
Javascript
Need a hint?

Use if and else if to check dayNumber and assign the correct day name to dayNameIf.

3
Create dayNameSwitch using a switch statement
Create a variable called dayNameSwitch. Use a switch statement on dayNumber to set dayNameSwitch to the correct day name using the same mappings as before. Use a default case to set dayNameSwitch to 'Invalid day' if the number is not 1 to 7.
Javascript
Need a hint?

Use switch (dayNumber) with case for each day number and a default for invalid numbers.

4
Print both dayNameIf and dayNameSwitch
Write two console.log statements to print the values of dayNameIf and dayNameSwitch.
Javascript
Need a hint?

Use console.log(dayNameIf); and console.log(dayNameSwitch); to print the results.