I find it strange how the switch statement works in JavaScript

It's interesting to note that while the single = is typically used as an assignment operator, it appears to function as a valid relation operator in the second example below.

First Example:

switch (true) 
  {
    case color == 'green':case color == 'red':case color == 'blue':case color == 'pink':
      alert('colorful')
      break;
    case color == 'black':case color == 'white':
      alert('classical')
      break;
    default:
      alert('dull')
      break;              
  }

Second Example:

switch (color) 
  {
    case color = 'green':case color = 'red':case color = 'blue':case color = 'pink':
      alert('colorful')
      break;
    case color = 'black':case color = 'white':
      alert('classical')
      break;
    default:
      alert('dull')
      break;              
  }

Answer №1

When you encounter the first switch statement, you are verifying a boolean value. This means that the valid outcomes will be either true or false.

In the second switch statement, we are looking for a color. The outcome of the assignment is the assigned value itself.

Setting color = 'green' will result in green and is essentially equivalent to case 'green':, with the added effect of changing the value of color. HOWEVER, it's important to note that altering the value of color while checking its value can lead to significant unintended consequences.

It is advisable to adhere to the proper formal style for case 'green': rather than using alternative forms, especially not those involving assignments.

Answer №2

My understanding of how the switch statement works inside the CPU is not completely clear, but I have a theory. I believe that when the switch statement is entered, the value of the variable color is temporarily stored for comparison. Subsequently, each assignment within the cases is evaluated against this stored switch-value, rather than directly comparing with the variable itself. To support my hypothesis, consider the following scenario:

var color = 'whit'
switch(color + 'e')
// "white" is stored for comparison...
{
  case color = 'green':
  case color = 'red':
  case color = 'blue':
  case color = 'pink':
    alert('colorful')
    break;
  case color = 'black':
  // (color = 'white') == 'white'
  // The stored value is compared with 'white'
  case color = 'white':
    alert('classical')
    break;
  default:
    alert('dull')
    break;              
}

UPDATE: In the subsequent example, the value is fetched only once, at the start of the switch statement, yet it is set multiple times within the case statements. This demonstrates that solely the value of the variable (rather than the variable itself) is utilized for comparison.

function Field(val){
    this.__defineGetter__("value", function(){
        var val = parseInt(Math.random() * 10);
        console.log('get: ' + val);
        return val;
    });
    this.__defineSetter__("value", function(val){
        console.log('set: ' + val);
    });
}

var field = new Field();
switch (field.value) {
    case field.value = 0:
        break
    case field.value = 1:
        break
    case field.value = 2:
        break
    case field.value = 3:
        break
    case field.value = 4:
        break
    case field.value = 5:
        break
    case field.value = 6:
        break
    case field.value = 7:
        break
    case field.value = 8:
        break
    case field.value = 9:
        break
    default:
        break
}

// output (e.g.)
// get: 5
// set: 1
// set: 2
// set: 3
// set: 4
// set: 5

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting text files into JSON format

I am working with a text file that has a specific structure. Title: Tombstone Release Year: 1993 Format: Blu-ray Stars: Kurt Russell, Val Kilmer, Sam Elliott, Bill Paxton Title: The Shawshank Redemption Release Year: 1994 Format: DVD Stars: Tim Robbins, M ...

Saving JSON data in SQLite using a PhoneGap application

Is there a way to save the decoded JSON data into an SQLite Database while using phonegap to develop the app? Below is the function where the json data is being decoded. function onNotification(e) { switch( e.event ) { case ...

What is the process for determining the date that is 28 days past a specified date?

I need assistance with finding the 28th day from a date formatted as YYYY-MM-DD. I've attempted various methods without success. Ideally, I would prefer a solution that does not involve Moment.js. Check out my code on Jsfiddle If there are no altern ...

What is a way to invoke the split(token) method on a string that doesn't have the token present, but still avoid encountering an

Within my HTML markup, I have two distinct types of strings serving as IDs for elements: Dates: "april-23" "march-20" and names representing seasons: "springtime" "winter" The date IDs are structured with a dash separating the month and day. Converse ...

Transform the arrow function into a standard JavaScript function

Here is the React return code snippet I'm working with: return ( <div className='App'> <form onSubmit={this.submit.bind(this)}> <input value={this.state.input} onChange={(e) ...

Move a div element to the foreground while maintaining its fixed position

I had a situation where I used the fixed position for a div on a webpage to keep it stuck at the top like a header. However, when scrolling, it ended up getting hidden behind other elements such as divs, videos, and text! Here's how the div should al ...

Limits of the window in a d3 network diagram

I'm currently working with a network diagram that consists of circle elements and lines connecting them. However, I've run into an issue where sometimes there are so many circles that they extend beyond the edge of my screen (see image attached). ...

Sending data to server with Backbone (using save() function and php script)

Wondering if you can assist me with an issue I'm facing. I am trying to utilize Backbone's save() method and send data to a php file. However, I encountered a problem right at the beginning. When I execute the following in the browser's co ...

Rotating a camera around an object in Three.JS using device movement

I’ve posted a similar question in another forum, but I wanted to provide more clarity on the issue I'm facing. What's my objective? I am currently using three.js within a WebView on my android device to create a scene that consists of a simple ...

Using jQuery to toggle the visibility of HTML elements

Hi there, I am trying to create an interactive HTML sidebar where each section shows its respective posts when clicked. However, I am facing issues as the content keeps hiding continuously. <div class="col-md-3"> <div class="list-grou ...

Blending conditional and non-conditional styles in VueJS

Is it possible to set a class in Vue based on the value of a parameter and conditionally add another class if that parameter meets a certain condition? Can these two functionalities be combined into one class assignment? <button :class="'btn btn-p ...

Which is better: using multiple makeStyles or just one in Material UI?

Uncertain about the best approach in this situation. Is it acceptable to generate styles using makeStyles for each component individually, or would it be better to create one in the base component and simply pass down class names? ...

Encountering difficulties with image processing on a web page

Recently, I've been experimenting with uploading an image and converting it to a grayscale version on my webpage. Oddly enough, the javascript code works perfectly when tested locally but fails to generate the grayscale image once integrated onto the ...

Is it possible to create a jQuery-powered color picker that changes colors in real-time

I am currently working on a form that needs to send data to the database. The form includes fields for the product name and specifications details such as spec name and color selection. While I was able to generate the spec input without any issues, I enco ...

Is it possible to manipulate the z-index programmatically?

I have been developing a Google Chrome extension that involves injecting HTML into webpages. The injected HTML should be displayed on top of the existing content, but I am encountering an issue. On some pages, the injected HTML does not show up, even after ...

Implementing a personalized pipe to enhance search functionality in a data table

I am currently working on a project that involves displaying data in a table. I want to add a search bar functionality that allows users to filter the table data. I have attempted to use a pipe to achieve this, but I am facing challenges and unsure of the ...

Error loading resource: the server returned a 405 status code and an unidentified input

I encountered an issue with this code snippet function AddComment(id) { var input = $("#" + "CommentOnPost" + id).val(); var commentHolder = $("#commentDiv" + id); commentHolder.empty(); $.ajax({ ur ...

Sort data by checking either multiple or single checkbox options in AngularJS; if none are selected, display all results

My goal is to implement a filter in my AngularJS code that will filter data based on selected checkboxes. If no checkbox is selected, all results should be displayed without any filtering. Currently, the issue I am facing is that the data is only displayed ...

Masonry is not compatible with Bootstrap 3

Can someone help me figure out how to make Masonry work with my Bootstrap grid columns? Step 1 - First, I included the Masonry script in my <head> like this : <script src="http://cdnjs.cloudflare.com/ajax/libs/masonry/3.1.5/masonry.pkgd.min.js"& ...

Updating an array element in Mongoose, the MongoDB ORM

I am currently in the process of making changes to a MongoDb collection that contains an array of documents called items. To achieve this, I am utilizing the express and mongoose frameworks. This is how my schema is structured: const mongoose = require(" ...