1

I'm trying to experiment with a small lightbulb switch JavaScript challenge(from w3schools). I already tried with if statement to see if I can change the bulb from off to on and vice versa with a single button, and it worked. Now I'm trying to do the same with the switch-case statement, but it doesn't work.

This is what the code looks like:

<!DOCTYPE html>
<html>
<body>



<button onclick="lightswitch(sw)">Light Switch</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">



<script>

var sw = 0;
function lightswitch(sw){

  switch(sw){
    case 1: 
    document.getElementById('myImage').src='pic_bulboff.gif'
    sw=0;
    break;

    case 0:
    document.getElementById('myImage').src='pic_bulbon.gif'
    sw=1;
    break;
   }
}
</script>

</body>
</html>

I checked with console log and the 'sw' variable does not get updated from the switch case and keeps retaining its original value outside the lightswitch function. Is there any specific reason why this happen? and can I work around it?

  • 2
    Because the `sw` parameter of the function shadows the `sw` variable outside the function. If you assign, you assign to the parameter but not the variable since JS is pass-by-value, not pass-by-reference. – VLAZ Jun 20 '22 at 19:02
  • 3
    And to make it very clear: This "problem" has nothing to do with the `switch` statement. – Felix Kling Jun 20 '22 at 19:04

0 Answers0