A comparison between the if statement and switch statement in JavaScript

Let's dive into a challenging scenario for those who consider themselves experts in JavaScript, particularly with switch and if statements. Here is how it typically works:

var a = 1;
if (a == 1) alert("true");

This is just a basic example. Now, let's see how it is supposed to work with the switch statement:

var a = 1;
switch (a)
{
  case 1: alert("true");
}

However, when attempting to use the switch statement to replace multiple if statements, things don't seem to go as planned. This issue has been discussed before, but each code snippet varies, leaving me unable to find a consistent solution online.

The following code should indicate that the hero's values are NOT confirmed:

<script type="text/javascript">
// Your script here...
</script>

Your hero:
<select id="heroes">
{/* Options */}
</select>
<br />
Your skill level: <input type="text" id="SkillQ"><br />
Required skill level: <input type="text" id="SkillA"><br />
<label for="writeNew">Write New?</label><input type="checkbox" id="writeNew" /><br />
<button onclick="skillcalc()">Calculate</button>

<p id="Answer"></p>

Feel free to ask any questions about this intriguing challenge. There may be something I'm missing, but I'm eager to figure it out.

Sincerely, Patrick

Answer №1

The reason for the issue is that the input value utilized in the switch-statement is considered as text format.

To test this, you can execute the following code in the console:

var b = '42'; 
switch(b) {
    case 42: alert('Number'); 
    case '42': alert('Text');
}

A solution to this problem would be to use switch(parseInt(b)).

Answer №2

Have you ever noticed that JavaScript sometimes interprets what you meant instead of what you actually said?

This interesting occurrence is referred to as type coercion, and it occurs when the == (double equal) operator is used instead of the strict comparison operator === (triple equal).

With ==, such as in '1' == 1, one of the values gets converted to match the type of the other value, resulting in a comparison like '1' == '1', which evaluates to true.

In contrast, when using ===, the values must not only be equal but also of the same type. For instance, '1' === 1 will yield false.

Interestingly, the switch statement does not perform this automatic conversion, behaving similarly to

===</code where both value and type need to match.</p>

<p>To ensure the <code>switch
statement functions correctly, the value provided to switch(value) needs to have the same type as the cases within the case statements.

In your code, a value is taken from the DOM (a form), using:

waarde = document.getElementById("heroes").value

This value will always be of string type. Therefore, you should either use strings in your case statements (e.g., case '1':) or convert the DOM-obtained value into a number (e.g., waarde = parseInt(..., 10) - remember that the radix argument is crucial!)

For further information on coercion, you can explore more resources here.

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

The order of CSS precedence shifts even when the class sequence is the same

In my development setup, I have a react component that is embedded within two distinct applications each with their own webpack configurations. Within the component, I am utilizing a FontAwesome icon using the react-fontawesome library: <FontAwesom ...

Error: npx is unable to locate the module named 'webpack'

I'm currently experimenting with a customized Webpack setup. I recently came across the suggestion to use npx webpack instead of node ./node_modules/webpack/bin/webpack.js. However, I am encountering some difficulties getting it to function as expecte ...

Customize the font color in Material UI to make it uniquely yours

How can I customize the default Text Color in my Material UI Theme? Using primary, secondary, and error settings are effective const styles = { a: 'red', b: 'green', ... }; createMuiTheme({ palette: { primary: { ...

Tips for utilizing setState to display specific information fetched from an API call through the mapping method

Is there a way to utilize setState in order to render individual data retrieved from an API call? Despite my efforts, all I seem to get is another array of data. Here's the code snippet: const [likes, setLikes] = useState(0); useEffect( async () = ...

Employing jQuery to add an element as a sibling rather than a child node

I'm having trouble finding the specific functionality I need. My goal is to add sibling DOM elements to a disconnected node. From what I gather, it should be possible with either .after() or .add(), but for some reason both methods are not working as ...

Do not continue submitting if the innerHTML matches the specified value

I am currently working on a web page that verifies if an email entered by the user is available in the database. If it is, I need to prevent the form from being submitted. To achieve this, I have implemented Ajax for real-time checking of the email and di ...

Encountering a NaN outcome when summing values from various select options

I'm working on a project that involves adding up the prices based on the surface chosen by the user. I'm struggling with calculating the partial cost when the user's choice changes. totalSum.ts num: Calculation totalAmount: number cate ...

Assigning ng-view to "NAME" using RouteProvider

I'm completely new to Angular and I have a question regarding injecting a template or URL into multiple ng-views. However, my current approach involves having ng-view in my base template. My base template structure is as follows: <body> < ...

Guide on making a prev/next | first/last button functional in list.js pagination

Is there a way to enhance my paginated index by adding prev/next, first/last buttons? I am curious if anyone has implemented these features using List.js. <script src='//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js&ap ...

An AJAX script for dynamically adding, modifying, and removing records from a database

How can I implement a functionality where by pressing "-" the vote is removed from the database, and when any other number is selected, the vote will be updated in the database with that value? The default value of the dropdown list is votacion.votCalific ...

Retrieving the $index value for the chosen option in Angular

Consider this scenario: <input ng-model="selectedColor" type="text"></input> This approach will not produce the desired outcome: <p ng-click="changeColor($index)">change color</p> Is there another way to access $index without u ...

Discover the position of a dynamically added element

Is there a way to identify the specific dynamically added checkbox that was clicked, whether by index or name? I came across a similar question with a solution in this JSFiddle: JSFiddle Instead of just displaying "clicked", I would like it to show someth ...

How can one check in JavaScript if a specific URL was targeted with a XMLHttpRequest?

While I am familiar with monitoring network traffic in the browser's development tools and having XMLHttpRequests shown in the console, I am curious if there is a specific window property that showcases all network activity at once? ...

Having trouble closing my toggle and experiencing issues with the transition not functioning properly

Within my Next.js project, I have successfully implemented a custom hook and component. The functionality works smoothly as each section opens independently without interfering with others, which is great. However, there are two issues that I am facing. Fi ...

What causes the 'find' query to return a Query object instead of the expected data in MongoDB?

After researching extensively on SO, I have yet to find a solution to my ongoing issue. Currently, I am in the process of developing a project using node, express, and mongodb. To start off, I created a seeder file to populate some data into mongodb: var ...

What is the importance of always catching errors in a Promise?

In my project, I have implemented the @typescript-eslint/no-floating-promises rule. This rule highlights code like this - functionReturningPromise() .then(retVal => doSomething(retVal)); The rule suggests adding a catch block for the Promise. While ...

How can the Singleton pattern be properly implemented in Typescript/ES6?

class Foo{ } var instance: Foo; export function getFooInstance(){ /* logic */ } or export class Foo{ private static _instance; private constructor(){}; public getInstance(){/* logic */} } // Use it like this Foo.getInstance() I would ...

AngularJS date formatting fails to properly format dates

{{ map.thedate }} The result is 2014-06-29 16:43:48 Even after using the following code, it still displays the same date as above. {{ map.thedate | date:'medium' }} ...

The functionality in the React Native code that uploads images to an S3 bucket is currently failing to initiate the network request

I have been using a redux-observable epic to upload images to my AWS S3 bucket through react-native-aws3. It has been functioning smoothly for quite some time. However, recently it seems to have stopped entering the .map and .catch blocks of code. I suspec ...

What is the best way to ensure that the operations are not completed until they finish their work using RX

Is there a way to make RXJS wait until it finishes its work? Here is the function I am using: getLastOrderBeta() { return this.db.list(`Ring/${localStorage.getItem('localstorage')}`, { query: { equalTo: fa ...