JS switch case not working - javascript

I have a switch case statement that doesn't work. I've checked the input, it's valid. If user is 1, it goes to default. If user is any number, it defaults. What's wrong here? I don't know javascript well at all.
switch (user) {
case 1:
// stuff
break;
case 2:
// more stuff
break;
default:
// this gets called
break;
}

Make sure you are not mixing strings and integers.
Try:
switch (user) {
case "1":
// stuff
break;
case "2":
// more stuff
break;
default:
// this gets called
}

Problem is data type mismatch. cast type of user to integer.

Cast type of user variable to integer
switch (+user) {
case 1: .. //
}

Javascript is type-aware. So '1' is not the same as 1. In your case the "user" has to be numeric, not the string. You can cast it by just:
user = Number(user)

Related

How to write case in Switch else statement in javavscript?

//This is my Problem
Complete the getLetter(s) function in the editor. It has one parameter: a string, , consisting of lowercase English alphabetic letters (i.e., a through z). It must return A, B, C, or D depending on the following criteria:
If the first character in string is in the set {aeiou}, then return A.
If the first character in string is in the set {bcdfg}, then return B.
If the first character in string is in the set {hjklm},, then return C.
If the first character in string is in the set {npqrstvwxyz}, then return D.
I am trying to implement the above scenarion and to dthis I have written the following code.
//Here is my code
function getLetter(s) {
let letter;
// Write your code here
switch (s) {
case s.match(/[aeiou]/g).includes(s[0]):
letter = 'A'
break;
case s.match(/[bcdfg]/g).includes(s[0]):
letter = 'B'
break;
case s.match(/[hjklm]/g).includes(s[0]):
letter = 'C';
break;
case s.match(/[npqrstvwxyz]/g).includes(s[0]):
letter = 'D';
break;
default:
console.log("hello")
}
return letter
}
The code is showing error. Would any help me to figure it out? How can I implement the above task using switch statement.
I don't know that much switch case, but maybe you can use parenthesis for the switch statement and if "s.match(/[aeiou]/g).includes(s[0])" return true or false
And you forgot ";" after the two first assignment
the way you wrote the switch case may be partially correct in GoLang. but in Javascript, it is not possible to achieve this using Switch-Case statement.
Better try using if-else-if statement something like below
if(s.test(/^[aeiou]/)) {
return 'A';
} else if(s.test(/^[bcdfg]/)) {
return 'B'
}
Check out this: Switch statement for string matching in JavaScript. The issue is that match returns null, which breaks the switch statement.
Use
switch(s){
case str.match(/^xyz/)?.input:
//code
break;
This stops the match from returning null.
Based on how you're using this, you actually want to switch (true) and not switch (s)
i.e. when you have a case y in a switch (x), the test being done is x === y; so you want to do true === some.test()
const s = 'a';
switch (true) {
case /a/.test(s):
console.log('first match');
break;
case /b/.test(s):
console.log('second match');
break;
default:
console.log('no match');
break;
}
Will log first match because
/a/.test('a') is true
and true /* from switch */ === true /* from case test */
Note that in most cases switch can also be written as if..else if..else.
Base your decision on which to use by which is the most readable (err on the side of if patterns)
The above example written as an if might look like this
const s = 'a';
if (/a/.test(s)) {
console.log('first match');
} else if (/b/.test(s)) {
console.log('second match');
} else {
console.log('no match');
}

JS - Evaluation with function within switch-case

I have objects with ids like alternative1, alternative2 etc. I want to style all of these the same way so I'm trying:
switch (feature.id) {
case 'marker':
...
break;
case feature.id.includes('alternative'):
case 'connectionMarker':
... //add styling
break;
This does not seem to work. How could I do this?
You can use a simple trick:
switch (feature.id) {
case 'marker':
...
break;
case (feature.id.includes('alternative') ? feature.id : !feature.id):
// your code here
break;
case 'connectionMarker':
...
break;
}
Since feature.id is always a string value, !feature.id will always return false. Hence, if feature.id includes "alternative" this line:
case (feature.id.includes('alternative') ? feature.id : !feature.id):
becomes:
case feature.id:
which will always be the case (as feature.id === feature.id). Otherwise, the line evaluates to:
case 0:
which will be skipped by the interpreter.

Javascript - switch is for strings only?

Im not sure if I can use switch only for strings or that I can use it for numbers, booleans or events.
switch() can be used to compare any types: strings, objects, numbers.
The important thing to notice that switch() uses strict type comparison: ===.
For example:
Comparing strings
var a = '1';
switch (a) {
case 1:
console.log(1); // '1' === 1 returns false, no match
break;
default:
console.log('No match'); // will print 'No match'
}
Comparing objects
var a = 1;
switch (a.constructor) {
case Number:
console.log('number'); // prints 'number'
break;
case String:
console.log('string');
break;
default:
console.log('no match');
}
Im not sure if I can use switch only for strings
Nope, it should just be a valid expression as per the spec
See this demo,
this code alerts right
var a =1;
var b = 2;
switch(a+b)
{
case 1:
alert("wrong");
break;
case 2:
alert("wrong");
break;
case 3:
alert("right");
break;
default:
alert("wrong");
break;
}

how to switch-case with inconsistent variable format

switch (req.path)
{
case "/api/posts":
console.log("posts");
break;
case "/api/posts/tags/*": // the part * is always changing depending on user input
console.log("tags");
break;
case "/api/best":
console.log("best");
break;
default:
console.log("default");
}
the req.path gives my path
for example
/api/post/tags/asd,dsfd
/api/post/tags/1
/api/post/tags/12,123
how do you manage with this as efficiently as possible?
some frameworks provide path parsers that looks like
/*
this and any input after * is ignored and treated as the same. I am curious of its inner mechanism.
What about something like this (see the jsfiddle):
function route(req) {
if(req.path === '/api/posts') {
console.log('posts');
}
if(req.path.indexOf('/api/posts/tags') > -1) {
console.log('tags');
}
// etc.
}
route({path: '/api/posts'}); // => posts
route({path: '/api/posts/tags/hi'}); // => tags
route({path: '/api/posts/tags/cool'}); // => tags
You could also use a regular expression. Keep in mind that if some input conditions might match each other, you'll want to return at the end of each if statement, or simply use else if. Totally depends on the routes your looking for.
For the default case, you can string together everything with if... else if, and in the final else put console.log('default'). I've left my above solution very minimal so you can extend it as you see fit.
Output
You can just toss a regex into your switch statement which will handle all cases branching off of that route.
switch (req.path)
{
case "/api/posts":
console.log("posts");
break;
case req.path.match(/(\/api\/posts\/tags\/)/)[1]:
console.log("tags");
break;
case "/api/best":
console.log("best");
break;
default:
console.log("default");
}

Switch with random not working

This is my current jScript code:
(modified STILL doesn't work)
function changeBG(){
document.getElementById('imgbox').src = switch(eval(rand())){
case 1: "img/img3.jpg";
break;
case 2: "img/img2.jpg";
break;
case 3: "img/img3.jpg";
break;
case 4: "img/img4.jpg";
break;
case 5: "img/img5.jpg";
break;
default: "img/background.jpg";
break;
}
}
function rand(){
return (Math.ceil((Math.random()*10)/2));
}
my HTML:
<input id="BGchange" type="button" onclick="changeBG()" value=">"/>
If I do something like this:
document.getElementById('imgbox').src = "img/img1.jpg";
It just works: I click on my button, the image changes, no problem. Fact is I want the image to change to a random one between 5 each time the button is clicked; to do this I wanted to use a switch that works with a random choice inside it.
What is wrong with my coding?! :( (I cant use jQuery or anything, just pure javascript, html and css, thats what the professor said at least)
Thank you <3
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
The switch-statement "executes" your Strings ("img/imgX.jpg") instead of returning them, so you may want put the switch in a function and then do
case 1: return "img/img3.jpg";
...
and keep in mind that each case of a switch statement must be terminated with break, otherwise the following case-Blocks will be executed as well!
Your function return an integer, while your switch case is looking for a string.
Remove quotes from the switch cases and everything should work.
function changeBG(){
document.getElementById('imgbox').src = switch(rand()){
case 1: "img/img3.jpg";
break;
case 2: "img/img2.jpg";
break;
case 3: "img/img3.jpg";
break;
case 4: "img/img4.jpg";
break;
case 5: "img/img5.jpg";
break;
default: "img/background.jpg";
}
}

Categories