JavaScript switch statement and case expression

Struggling to use boolean expressions within a switch statement to search for undefined values and manually change them. When using an if statement, the process is easier.

For example: if statement

if(Item1 == undefined)
{
  item1 = "No";
}
else if (Item2 == undefined)
{
  item2 = "No";
}

But when attempting this with a switch statement:

 switch (array) {
 case (item1 == undefined):
 item1 = "No";
 console.log('item1 result', item1 );
 break;
 case item2 == undefined:
 item2 = "No";
 console.log('item2 result', item2 );
 break;
 default:

 }

The switch statement does not execute properly, except when removing == undefined and just using item1. Then it seems to work?

Answer №1

The switch statement is unable to evaluate array values in that manner, which is why it does not proceed through the switch statement. To use a switch statement with an array, you must define the specific value from the array that you want to switch.

Additionally, within a case statement, expressions cannot be used; you must provide a direct value instead.

If you still wish to utilize a switch statement for your task, you can implement something like this:

item1 = array[1];
switch(item1) {
    case "undefined":
        // code goes here
    break;
}

However, judging by your example, it seems like you are attempting to verify if certain values are set or not. In such cases, using if statements would be a more suitable choice rather than switch statements.

$arr = []; // Your array
if(typeof $arr[0] == "undefined") {
    $arr[0] = "No";
}

Answer №2

Only one variable can be used in a switch statement, like so:

switch (element) {
 case 'undefined':
 outcome1 = "Not present";
 console.log('outcome1:', outcome1);
 break;
 case element.length:
 outcome2 = "Not found";
 console.log('outcome2:', outcome2);
 break;

 }

Answer №3

Helpful for understanding function arguments.

An efficient and straightforward method would be:

value1 = (value1 === null || value1 === undefined) ? 'no' : value1;
value2 = (value2 === null || value2 === undefined) ? 'no' : value2;

If the variable is either null or undefined, it will assign a default value; otherwise, it will keep the original value.

p.s. This approach checks for null or undefined values and is more concise than using a switch statement.

Answer №4

let index = 0;
while(index < myArray.length){
    switch(myArray[index]){
        case "null":
        //continue with other cases
            break;
    }
    index++;
}

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

What causes the body onload = javascript function to run repeatedly?

Greetings for the absolute beginners out there, just dipping your toes in AJAX. I'm curious to know what exactly triggers the continuous change in divMessage content when the text "myName" is altered. 1) It appears that the Javascript function proce ...

Is there a way to decrease the speed of a range slider?

Recently, I created a range slider using HTML, CSS, and JS to complement my Lua Nui. It's been working smoothly for the most part, but I've noticed an issue when sliding too quickly on the slider. As I slide it to the left, certain values fluctua ...

The behavior of the 'typeof null' function in JavaScript is not functioning

I have a collection of objects where each object contains a key and an array as a value. You can see what I mean in this image. Some of the arrays had less than 20 elements, so I wrote some code to pad them with zeros. The result of running my code can be ...

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? ...

Encountering an unexpected syntax error while refreshing a page in Html5Mode

I've enabled Html5Mode(true) in my AngularJS application. Everything works smoothly when I initially visit my website at: http://www.example.com The URL then transforms to: http://www.example.com/home/index and my page displays correctly. However, ...

JavaScript Fullcalendar script - converting the names of months and days

I recently integrated the Fullcalendar script into my website (https://fullcalendar.io/). Most of the features are functioning correctly, however, I am seeking to translate the English names of months and days of the week. Within the downloaded package, ...

When manipulating an array in JavaScript, the final count is wrong and there is an unexpected object

When I click this button, the addToCart function is invoked which dispatches an action to the reducer to add an item to the cart. The goal is to store only one instance of a specific item and increment the amount if the same item is added again. case &apo ...

In Rails 3, you can utilize JavaScript to submit a form_tag remotely, however ensure that it submits as

I am trying to implement a form_tag in rails 3 that can be submitted using ajax instead of html through javascript. Despite setting the form to submit as javascript, it still submits as html when clicking the submit button. - form_tag({:controller => " ...

Encountering an issue with usememo in React js?

I'm currently experimenting with the useMemo hook in React JS. The goal is to sort an array of strings within a function. However, when I return the array from the function, only the first element is being returned. Can someone please assist me in ide ...

"The controller seems to always return an 'undefined' value for the Angular

Within my project, I have implemented ui-view with the following structure: <main class="content"> <div class="inner" ng-controller="OrderPageController"> <div ui-view="main-info"></div> <div ui-view="comment ...

Looking for an alternative to document.querySelectorAll?

My issue involves using querySelectorAll('a') to select all buttons, but I only want to target two specific buttons labeled 'Know More'. How can I achieve this? Below is the code snippet in question: const buttons = document.query ...

employing a variable within a function that is nested within another function

I'm encountering an issue where I am using a variable within a nested function. After assigning a value to it, I pass it to the parent function. However, when I call the function, nothing is displayed. function checkUserExists(identifier) { let user ...

Inverting the order of vertices in a THREE.js face

I am seeking a way to reverse the order of vertices in faces within my geometry. For instance: // create geometry var geometry = new THREE.Geometry(); // create vertices geometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) ); geometry.vertices.push( ...

The Magic of Javascript Routing with Regex Implementation

I'm currently developing a Javascript Router similar to Backbone, Sammy, and Spin. However, my specific requirements are rather straightforward. I need the ability to define a series of routes along with their corresponding callbacks, and I want to be ...

Outputting HTML using JavaScript following an AJAX request

Let's consider a scenario where I have 3 PHP pages: Page1 is the main page that the user is currently viewing. Page2 is embedded within Page1. It contains a list of items with a delete button next to each item. Page3 is a parsing file where I send i ...

Is there a bug hiding in the Angular code for the Codecademy Calendar App waiting to be found?

Currently, I am working on the Codecademy task - CalendarApp utilizing AngularJS which involves services and routing. Unfortunately, it seems to have some issues as the data is not displaying correctly and the expression: {{ day.date | date }} appears as i ...

What is the best way to transition a connected component from a class-based to a functional component in TypeScript?

I'm in the process of switching from a class-based component to a functional component. This is a connected component that uses mapState. Here is my initial setup: import { connect } from 'react-redux' import { fetchArticles } from '. ...

What causes the string to be treated as an object in React Native?

I am fetching a string value through an API and I need to display it in the View. However, the string value is coming as a Promise. How can I handle this? "Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65 ...

Move the cursor to the start of a textarea with the power of jQuery

MyEvent.prototype.sendMessage_ = function(input) { //input is this.find('#mytextarea'); if (input.val().trim() != '') { input.val(''); $('#mytextarea').focus(); } }; //...within the html....// <text ...

Tips for executing JavaScript code within a component

Looking to incorporate a parallax effect into an HTML element in my template. Have the code written, but uncertain of where to place it so that it runs each time the page is scrolled. let pos = document.body.scrollTop; document.getElementById('parall ...