JS Startup

Challenges, Tips & Tricks & Tutorials

JavaScript Quiz – switch case can change a variable value

JavaScript Quiz – switch case can change a variable value

JavaScript Switch Case

In javascript, a switch statement is used to perform different actions based on the matching expression. If no case expression is matched then it runs the default statement.

Switch statement work similar as if statement but much more faster than if statement.

It’s syntax looks like –

switch (expression) {
  case value1:
    // Statements executed
    [break;]
  case value2:
    // Statements executed 
    [break;]
  ...
  case valueN:
    // Statements executed
    [break;]
  default:
    // Statements executed
    [break;]
}

For more detail about javascript switch case click here.

JavaScript Question

In this javascript quiz, find out switch case can change variable value based on the matching expression as switch work same as if statement.

First, we declare a variable num and assign a number to it. which is 1.

let num = 1;

Now, we declare switch statement with matching case 1 with default.

switch(num){
case 1:
num = 2;
default:
num = 0;
}

Now, the switch will receive a num variable that decides conditional flow.

console.log(num);

As we assign the num variable again in the case 1 to 2 and in default 0. So, Any idea what should be the output above statement.

Answer – 0

Click To Run Code

Explanation

Now, you know the answer is 0 but why does the case 1 will match as num value is 1.

As it’s correct that switch statements match with case expression 1 because the num variable value is 1.

But in order for switch statement to stop the execution after matching expression. A break keyword need to be used.

As their no break keyword that’s why the default block is run due which first num assigned with 2 and then with 0.

At last, That’s why we get an answer “0“.

Let me know in the comment section, what you think about it.

I hope you understand the concept and logic behind it.

But wait, i have something more for you –

Check out our other javascript quiz – 

  1. JavaScript Quiz – object keys values method output can be equal
  2. JS Quiz – string match regexp can extract a number value
  3. JS Quiz – what is the math random function range
  4. JavaScript Quiz – numbers array can be sort

Conclusion

To participate in our javascript quiz or challenges, tutorial, tips & tricks make sure to join our jsstartup newsletter. So, you can able to participate in our daily challenges & learn the javascript concept.

And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page

If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top
0 Shares
Share via
Copy link