Beginner JavaScript: change if, else if, else to switch - javascript

Im in an intro JavaScript class and I have a homework assignment where I need to switch a picture every 5 seconds. I had it written out as a if, else if, else statement and it worked fine but then I saw on the directions that it's supposed to be a switch statement. Now I am having a tough time getting it to work. If anyone can help me out and let me know what Im doing wrong, that'd help a lot.
This is what I had:
var currAd = "pic1";
function changeAd() {
if (currAd == "pic2") {
document.images[0].src = "cvb1.gif";
currAd = "pic1";
}
else if (currAd == "pic3") {
document.images[0].src = "cvb2.gif";
currAd = "pic2";
}
else {
document.images[0].src = "cvb3.gif";
currAd = "pic3";
}
}
This is the switch statement. I assume its not working because of the currAd variable being the same on all of the cases, but I dont know what to switch it to
var currAd;
function changeAd() {
switch (currAd) {
case currAd:
return document.images[0].src = "cvb2.gif";
case currAd:
return document.images[0].src = "cvb3.gif";
default:
return document.images[0].src = "cvb1.gif";
}
}

Each case is the value you're comparing currAd with. You're currently comparing it to itself, when you should be comparing it to pic2, pic3, etc.
switch(curaAd) {
case "pic1":
// ...

Change your switch statement to:
switch (currAd) {
case "pic1":
return document.images[0].src = "cvb2.gif";
case "pic2":
return document.images[0].src = "cvb3.gif";
default:
return document.images[0].src = "cvb1.gif";
}

Related

How to get out of an infinite prompt loop when the prompt is assigned to a variable

Here's my code
function cc() {
prompt("Choose Character")
}
function cs() {
var chars = setTimeout(function(){ cc() }, 3000);
switch (chars) {
case "spy":
selectedspy()
break;
case "bulovian soldier":
selectedbulovian()
break;
case "stonian soldier":
selectedstonian()
break;
default:
cs()
}
}
it keeps getting stuck in an infinite loop of asking the prompt again. I feel like I'm making a simple mistake, but I couldn't figure what I needed to type into google to get the answer
I believe this is what you are trying to do.
function cc() {
return prompt("Choose Character");
}
function cs() {
//This will only run the code once, if you wish to have a loop use setInterval()
setTimeout(function(){
var chars = cc();
switch (chars) {
case "spy":
selectedspy()
break;
case "bulovian soldier":
selectedbulovian()
break;
case "stonian soldier":
selectedstonian()
break;
default:
cs()
}
}, 3000);
}

Trying to solve If/else problem with specific string and boolean

Problem
I've tried multiple avenues and watched videos. I'm stuck...
function exerciseThree(typeOfPizza){
let lovesPizza;
// In this exercise, you will be given a variable, it will be called: typeOfPizza
// You are also given another variable called: lovesPizza;
// Using an if/else statement assign lovesPizza to true if typeOfPizza is 'pepperoni', assign it to false if it is 'olives'
What I've tried:
if (lovesPizza==='pepperoni') {
// The value is empty.
return true;
}
else {
(lovesPizza==='olives')
return false;
}
Another attempt
// if(lovesPizza===pepperoni){
// return true
//}
//else (lovesPizza===olives){
// return false
// }
Another one
//if (lovesPizza.equals(pepperoni))
// return "true";
//else (lovesPizza.equals(olives))
// return "false"
As the comments say, you're looking for if / else. You should also double check your reading of the question, you had your checking / assigning variables the wrong way around
function exerciseThree(typeOfPizza){
let lovesPizza;
if (typeOfPizza === 'pepperoni') {
lovesPizza = true;
} else if (typeOfPizza === 'olives') {
lovesPizza = false;
}
console.log('lovesPizza:', lovesPizza);
};
exerciseThree('pepperoni');
exerciseThree('olives');
I would highly recommend using a switch statement in this case here. Switch statements run faster and are easier to work with in my opinion.
But to point out what you're doing wrong:
Here you are checking if lovesPizza has the value of pepperoni. But you should be checking typeOfPizza. This is why you're most likely getting undefined:
if (lovesPizza==='pepperoni') {
// The value is empty.
return true;
}
else {
(lovesPizza==='olives')
return false;
}
Check out how this looks with a switch statement.
function exerciseThree(typeOfPizza) {
switch (typeOfPizza) {
case 'pepperoni':
return true;
case 'olives':
return false;
default:
return false;
}
}
exerciseThree('pepperoni');
exerciseThree('olives');
Your else statement needs an if
if(somethingisTrue)
{
return "it is true";
}
else if(somethingelseistrue)
{
return "no the other thing was true";
}
else
{
return "nothing is true"
}
Also === checks the strings equal and are both strings. It is often better to make sure the if is case insensative
if(!typeOfPizza)
{
//raise an error as null was passed in
return "false"
}
else if(typeOfPizza.toLowerCase().trim()==="pepperoni"){
{
return true..... you can build the rest
I often write a function (prototype) called cleanString or compareString to perform all the normal cleaning up of strings.
A simple solution is but doesn't use ifs as asked.
function exerciseThree(typeOfPizza){
let lovesPizza= typeOfPizza==="pepperoni";
return lovesPizza;
}
I certainly hope you teacher is playing a trick on you.
There is no sane suggestions what to do if you send for instance 'ham' into it, and not handle all possibilities are just sloppy.
let lovesPizza;
function exerciseThree(typeOfPizza){
if(typeOfPizza === 'pepperoni') {
return true;
} else if (typeOfPizza === 'olives') {
return false;
} else {
return undefined;
}
}
lovesPizza = exerciseThree('pepperoni');
console.log(lovesPizza); // true
lovesPizza = exerciseThree('olives');
console.log(lovesPizza); // false
lovesPizza = exerciseThree('ham');
console.log(lovesPizza); // undefined

Switch Statement and jQuery hasClass function

I am trying to use a switch statement to check if the current page has a specific body class. This is kind of what I am looking for:
var bodyClass = $('body').hasClass('className')
switch(bodyClass) {
case 'homepage':
// console.log("This is the homepage");
break;
case 'residential-page':
// console.log("This is the residential page");
break;
default:
// console.log("default code block ran");
}
I do understand that the jQuery hasClass function returns true of false and is used like $('body').hasClass('someClassName') and this will return true or false. Also, my body typically has about 7-10 different class names for a given page.
This is not the use case for a switch in my opinion, but a simple set of branches
var body = $('body');
if(body.hasClass('abc')) {
}
else if(body.hasClass('def')) {
}
else {
/* default case */
}
/* etc */
I agree with the other answer that you're better suited to just use if, else if statements here, but an alternative would be to rip the classes off the body tag and check them against your strings:
var bodyClasses = ($('body').attr('class') || '').split(' ');
for (var i = 0, len = bodyClasses.length; i < len; i++) {
switch(bodyClasses[i]) {
case 'homepage':
// console.log("This is the homepage");
break;
case 'residential-page':
// console.log("This is the residential page");
break;
default:
// console.log("default code block ran");
}
}
I know this is an old thread, but it may help someone else.
If you are able to ensure the classes for the element are declared in a specific order, you could ensure the class you are checking for is first / last in the list, and use something similar to this:
var bodyClass = $('body').attr('class');
var firstClass = bodyClass.slice(0, bodyClass.indexOf(' '));
switch(firstClass) {
case 'homepage':
// Some code here
break;
case 'residential-page':
// Other code here
break;
default:
// More code here
}

From IF/ELSE to Switch in Javascript

So, I'm trying to substitute the code within the IF statements to run the same way in a Switch statement. However, I can't seem to understand how to get the functions to run the same way in the switch as they do in the if statement. Here's the code I've written with the if statement. Could anyone help me figure out how to format it correctly to run with the switch statement instead?
function processInput() {
listitem = "item" + i;
document.getElementById(listitem).innerHTML = document.getElementById('toolBox').value;
document.getElementById('toolBox').value = '';
if (i == 5) {
document.getElementById('resultsExpl').innerHTML = "Thanks for your suggestions";
}
i++;
}
I am not sure why you want the switch but for sample purposes here is how a switch would work for the code you posted above:
function processInput() {
listitem = "item" + i;
document.getElementById(listitem).innerHTML = document.getElementById('toolBox').value;
document.getElementById('toolBox').value = '';
switch(i) {
case 5:
document.getElementById('resultsExpl').innerHTML = "Thanks for your suggestions";
break;
default:
// any code you want to run in the else statement
}
i++;
}
This switch statement would replace the current if statement that you have.
switch (i) {
case 5:
document.getElementById('resultsExpl').innerHTML = "Thanks for your suggestions";
}

javascript switch(true)

Hi i am trying to handle an ajax json response
here is my code
success: function (j) {
switch(true)
{
case (j.choice1):
alert("choice2");
break;
case (j.choice2):
alert("choice2");
break;
default:
alert("default");
break;
}
}
based on what j is return i do my action BUT i keep getting the default.
I have alert the j values and come correct.Some how case (j.choice1) case (j.choice2) is not working.
I tried case (j.choice1!="") (j.choice2!="") But in this scenario i keep getting the first choice.
What am i missing
It works for me:
var a = 0, b = true;
switch(true) {
case a:
console.log('a');
break;
case b:
console.log('b');
break;
}
However, the case labels must be equal to true, not just implicitly true.
Also, only the first case that evaluates to true will execute.
SOLVED
Based on SLaks answer i modify the code as below
if(j.choice1){ var choice1=true;} else { var choice1=false;}
if(j.choice2){ var choice2=true;} else { var choice2=false;}
switch(true)
{
case choice1:
alert("choice1");
break;
case choice2:
alert("choice2");
break;
default:
alert("default");
break;
}
For all asking why switch and not if.
Switch will execute only 1 statement, but if can execute more than 1 if any mistake come form response (for example if set choice1 and choice 2 the if will alert both but switch will alert only choice1).
The response expecting as choice has to do with credit card charge to bank so i want to ensure that only 1 action will exetute
Thank to all
You need to read up on the switch statement. You should not be switching on a constant value.
It appears that you need to use if statements, as you don't really want to be switching on your j value:
success: function (j) {
if (j.choice1)
{
alert("choice1");
break;
}
if (j.choice2)
{
alert("choice2");
break;
}
alert("default");
}
}
In a case like this, a better way to do this is probably something like:
success: function (j) {
if(j.choice1 || j.choice2) {
alert("choice2");
} else {
alert("default");
}
}
Why not use an object literal instead of a switch(true) ?
const j= {
choice1: false,
choice2: true
};
const map = {
true: 'default',
...(j.choice1 ? {[`${j.choice1}`]: 'choice1'} :{}),
...(j.choice2 ? {[`${j.choice2}`]: 'choice2'} :{})
}['true']
console.log(map) // 'choice2'

Categories

Resources