I have a function that needs to pick out the color of a fruit and I have opted for a switch case statement. The problem is I'm not sure how to get the result out of the statement. Maybe I should get an if/else-statement instead?
Here is the code:
function fruitColor(fruit) {
switch(color) {
case "apple" : green;
break;
case "banana" : yellow;
break;
case "kiwi" : green;
break;
case "plum" : red;
break;
}
}
var result = fruitColor(plum);
I can't get the result and I'm not sure if I need a 'return' value or something like that.
The return statement ends function execution and specifies a value to be returned to the function caller. return MDN
There are a few missteps here aside from not returning a value. return is the facility to send a value back from a function, but in order for that to happen, no errors can occur. As it stands, the variable color is used in the switch statement, but it does not exist, perhaps because it was supposed to be fruit or vice versa. Further, the values in the resulting code for the case statements are basically just references to variables, and if there is no variable named green then it is just undefined. Perhaps you meant "green".
function fruitColor(fruit) {
//note that there was no value color here, there was only the accepted
//parameter fruit, which should either be used or changed to color
switch(color) {
case "apple" :
//needs quotes, green with no quotes is a variable reference
"green";
//note that simply using the string "green" doesn't accomplish anything though
//what we really need to do is send a value back, and in JavaScript you
//use the return keyword for that followed by the returning value
return "green";//like this
break;
case "banana" : "yellow";//^
break;
case "kiwi" : "green";//^
break;
case "plum" : "red";//^
break;
}
}
var result = fruitColor("plum");//needs quotes, plum would be a variable refernce
Personally, I prefer dictionaries for this type of work.
var fruitColors = {
apple : "green",
banana : "yellow",
kiwi : "green",
plum : "red"
};
var plumColor = fruitColors["plum"];//red
When coding, you always want to keep your code as high performance as possible. Now that I said that, let me give you some options to solve problems of this kind:
First, let’s go with your current solution and making it work.
function fruitColor(fruit) {
switch(color) {
case "apple" :
return 'green';
break;
case "banana" :
return 'yellow';
break;
case "kiwi" :
return 'green'
break;
case "plum" :
return 'red';
break;
}
}
var result = fruitColor(plum);
This one uses your switch construct and also returns prematurely, works.
However, it is not the best way to attack these kind of problems, because it generates code bifurcations that imply more memory is used to store and evaluate your code. Another way to do this is using an object with the fruits and colours.
function fruitColor(fruit) {
var fruits = {
apple : 'green',
banana : 'yellow',
kiwi : 'green',
plum : 'red'
};
return fruits[fruit] || 'not found';
}
var result = fruitColor('plum');
This code relies in a in-memory data base, works fast and has less bifurcations, but it also depends on a search.
This is my function implementation of the switch construct:
const fruitColor = fruit =>
({ apple: "green", banana: "yellow", kiwi: "green", plum: "red" }[fruit] ||
"Nothing");
I would like to add a following up to Travis J's answer.
From here I want to emphasise how you can put your arguments into the switch statement. The parameter variables fruit and color takes an argument. If you want an argument taken from the function fruitColor into the switch statement, use the same parameter variable name. I.e., either use fruit for both, or color for both.
function fruitColor(fruit) {
// Note that there was no value color here. There was only the accepted
// parameter fruit, which should either be used or changed to color
switch(color) {
case "apple":
"green";
return "green"; // Like this
break;
case "banana": "yellow"; // ^
break;
case "kiwi": "green"; // ^
break;
case "plum": "red"; // ^
break;
}
}
var result = fruitColor("plum");
First of all, in the switch statement, you have got to use the fruit argument, not the color and then you need a variable to store your choice:
function fruitColor(fruit) {
switch(fruit) {
case "apple" : result = green;
break;
case "banana" : result = yellow;
break;
case "kiwi" : result = green;
break;
case "plum" : result = red;
break;
}
return result;
}
var result = fruitColor(plum);
Related
let type = document.querySelector('#productType');
type.addEventListener('change', function() {
switch (type.value) {
case 'DVD':
document.querySelector('.DVD').classList.add('visible');
document.querySelector('.Furniture').classList.remove('visible');
document.querySelector('.Book').classList.remove('visible');
break;
case 'Furniture':
document.querySelector('.Furniture').classList.add('visible');
document.querySelector('.DVD').classList.remove('visible');
document.querySelector('.Book').classList.remove('visible');
break;
case 'Book':
document.querySelector('.Book').classList.add('visible');
document.querySelector('.Furniture').classList.remove('visible');
document.querySelector('.DVD').classList.remove('visible');
break;
}
})
You could take an array of ids and update the wanted value with a single loop
ids = ['DVD', 'Furniture', 'Book'];
// update
ids.forEach(id => document.querySelector(id).classList[id === value
? 'add'
: 'remove'
]('visible'));
I have an object with key value pairs made of questions and answers. There are several different ways to ask the question, so I'm trying to group questions that mean the same using a switch statement and the js match function.
{ 'Name?' : 'bob', q2: a2, .......}
I want to loop through the objects and find partial matches between the array elements and the object keys. So far I have:
switch (/terms/.test(key)) {
case ( terms ="Name|What's Your Name?"):
text = "matched";
break;
default:
text = "default";
Logger.log(key);
}
Logger.log(text)
});
The output in part shows:
18-10-09 15:37:41:415 EDT] *What's Your Name?*
[18-10-09 15:37:41:416 EDT] default
Obviously a match is not occurring. How can I get this working?
EDIT:
I changed my code to:
Object.keys(obj).forEach(function(key) {
switch (true) {
case (/^Name|term2$/.test(key)):
text = "MATCHED!!!!";
break;
case 0:
case 6:
// text = "It is Weekend";
break;
default:
text = "default";
Logger.log(key);
}
Logger.log(text)
});
Still no match.
You can combine switch cases like this:
switch (key) {
case 'Name':
case 'What\'s Your Name?':
// Do something
break;
default:
// Do something
}
This code is equivalent to:
if (key === 'Name' || key === 'What\'s Your Name?') {
// Do something
} else {
// Do something
}
In Javascript, is there a way to achieve something similar to this ?
const databaseObjectID = "someId"; // like "product/217637"
switch(databaseObjectID) {
case includes('product'): actionOnProduct(databaseObjectID); break;
case includes('user'): actionOnUser(databaseObjectID); break;
// .. a long list of different object types
}
This is more a curiosity question to understand the possibilities of switch / case, as in this particular case I have solved my problem using const type = databaseObjectID.split('/')[0]; and apply the switch case on type
This will work, but it shouldn't be used in practice.
const databaseObjectID = "someId"; // like "product/217637"
switch(true) {
case databaseObjectID.includes('product'): actionOnProduct(databaseObjectID); break;
case databaseObjectID.includes('user'): actionOnUser(databaseObjectID); break;
// .. a long list of different object types
}
You usage would be considered an abuse of case.
Instead just use ifs
if (databaseObjectId.includes('product')) actionOnProduct(databaseObjectID);
else if (databaseObjectId.includes('user')) actionOnUser(databaseObjectID);
// .. a long list of different object types
If the ObjectId contains static content around the product or user, you can remove it and use the user or product as a key:
var actions = {
"product":actionOnProduct,
"user" :actionOnUser
}
actions[databaseObjectId.replace(/..../,"")](databaseObjectId);
Sorry, I'm a noob so someone will probably have to clean this up, but here is the idea. Pass to a function to check and return a category then use the switch.
function classify(string){
var category = categorize(string);
switch (category) {
case 'product':
console.log('this is a product');
break;
case 'user':
console.log('this is a user');
break;
default:
console.log('category undefined');
}
}
function categorize(string){
if (string.includes('product')){
return 'product';
}
if (string.includes('user')){
return 'user';
}
}
classify("product789");
classify("user123");
classify("test567");
Sorry, as well, for not matching your example.
Question:
use string “includes()” in switch Javascript case
While the includes() method will work, it is case sensitive, and just matches any characters. I have found a Regex solution that I like much better, and provides a lot of flexibility. For example, you could easily change this to match only WORDS.
var sourceStr = 'Some Text and literaltextforcase2 and more text'
switch (true) { // sourceStr
case (/LiteralTextForCase1/i.test(sourceStr)):
console.log('Case 1');
break;
case (/LiteralTextForCase2/i.test(sourceStr)):
console.log('Case 2');
break;
default:
console.log('ERROR No Case provided for: ' + sourceStr);
};
//-->Case 2
So I have some code:
var Animal = 'Giraffe';
switch (Animal) {
case 'Cow':
case 'Giraffe':
case 'Dog':
case 'Pig':
console.log('This animal will go on Noah\'s Ark.');
break;
case 'Dinosaur':
default:
console.log('This animal will not.');
}
Ideally, I'd like the first console.log to print "This Giraffe will go on Noah's Ark", or whatever the variable Animal happened to be. I want to refer to the case. However, I'm not sure how to write that code. Can someone help?
Just use additional arguments to log and Animal.
console.log('This', Animal, 'will go on Noah\'s Ark.');
You could use a token %s (string in this case) and than after a comma use your variable:
var Animal = 'Giraffe';
switch (Animal) {
case 'Cow':
case 'Giraffe':
case 'Dog':
case 'Pig':
console.log('This %s will go on Noah\'s Ark.', Animal);
break;
case 'Dinosaur':
default:
console.log('%s will not.', Animal);
}
Just use your variable:
var Animal = 'Giraffe';
switch (Animal) {
case 'Cow':
case 'Giraffe':
case 'Dog':
case 'Pig':
console.log('This ' + Animal + ' will go on Noah\'s Ark.');
break;
case 'Dinosaur':
default:
console.log('This animal will not.');
}
(note: I'm using string concatenation here under the assumption that you may actually want to do something other than use the console.log function to do something like this - if you really just want to use console.log, it may be more reasonable to use one of the other answers provided)
I do not want to use Switch in my code, so I'm looking for some alternative
Example with Switch:
function write(what) {
switch(what) {
case 'Blue':
alert ('Blue');
break;
...
case 'Red':
alert ('Red');
break;
}
}
Example without Switch:
colors = [];
colors['Blue'] = function() { alert('Blue'); };
colors['Red'] = function() { alert('Red'); };
function write(what) {
colors[what]();
}
My questions are:
Do you know any other alternatives?
Is this best solution?
I have only a note about your second approach, you shouldn't use an Array to store non-numeric indexes (that you would call in other languages an associative array).
You should use a simple Object.
Also, you might want to check if the what argument passed to your write function exists as a property of your colors object and see if it's a function, so you can invoke it without having run-time errors:
var colors = {};
colors['Blue'] = function() { alert('Blue'); };
colors['Red'] = function() { alert('Red'); };
function write(what) {
if (typeof colors[what] == 'function') {
colors[what]();
return;
}
// not a function, default case
// ...
}
I used a structure like this today:
var chosenColor = 'red';
var colorString = {
'red': 'The color is red.',
'green': 'The color is green.',
'blue': 'The color is blue.',
}[chosenColor] || 'The color is unknown.';
I like that it's a really small amount of code to choose a string based on choice.
You could also pass it to a function:
alert({
'red': 'The color is red.',
'green': 'The color is green.',
'blue': 'The color is blue.',
}[chosenColor] || 'The color is unknown.');
You could use object literals, and try catch to trap the default:
function write(what) {
var colors = {
'Blue': function(){ alert('Light-Blue'); },
'Red': function(){ alert('Deep-Red'); },
'Green': function(){ alert('Deep-Green'); }
}
try {colors[what]();}
catch(err) {colors['Green']();}//default behaviour
}
write('Pink');
Question 2:
Generally, if you can replace custom control structures with a dictionary lookup, you're perfectly fine. It's easy to read and highly elegant -- stick with it.
I had to do do a compare for a group sort of object props for a list and did not want to do a switch/case for all the possibilities so I did an array of objects assignment to a numeric rank first so the case became a simple compare. This is only 4 possibilities but you get the drift of how to extend this to situation where a switch/case becomes unmanageable:
function mySort2(item1,item2){
var matrix = {
'repair': 4,
'r/r': 3,
'part': 2,
'misc': 1
};
(matrix[item1.category] < matrix[item2.category]) ? return +1 : return -1;
// if possible bad data need to check for this first ???
i1=matrix[item1.category] || null;
i2=matrix[item2.category] || null;
if (i1==null){
// handle bad data in item 1
return +1; // put it after 2
}
if (i2==null){
// ditto
return -1; //put 1 first
}
if (i1<i2)
return +1;
else
return -1;
}
You are pretty much there already. If possible you might want to add a helper function to make the setup easier. For Example:
function setup(what)
{
colors[what] = function() { alert(what); };
}
EDIT:
If what you want to do for each option is more complicated clearly this will not work. As mentioned in the comments by #roe this uses the global colors which is often frowned upon.
Alternatively, you can also use Dictionaries, so you could see the type of the function return, I think it's clean and scalable, although it's just pure JS.
const ColorDictionary = {
red: 'applies red color',
blue: ' applies blue color',
green: 'applies green color',
}
const useShowColors = (color) => {
// color will be selected or fallout to default value.
const getColor = () => (
ColorDicionary[color] ?? 'applies default color'
)
return { getColor }
}
const { getColor } = useShowColors() //pass the color you wish.
An alternative is to define a class with a write method, and override that in subclasses Red and Blue to do the right thing.
Whether or not that is better than your proposed solution, depends on your particular situation.
As I said, it's great. The only thing I can add to your solution is that it's perhaps better to localize your colors.
function write(what) {
var colors = [];
colors['Blue'] = function() { alert('Blue'); };
colors['Red'] = function() { alert('Red'); };
colors[what]();
}