Condensing several if statements into a for and an if - javascript

Is there a way to condense these four if statements into a for loop and with a single if condition? I was told that there is a way but I can only think of multiple else if statements.
function New() {
if (foodInOven == true) {
timeOfCooking += 1;
}
if (timeOfCooking == 10) {
console.log("cooked pasta");
} else if (timeOfCooking == 15) {
console.log("burning pasta!");
} else if (timeOfCooking == 20) {
console.log("pasta burnt!!");
}
}

One option could be to have a lookup for your times and, if there's a value, log it to the console.
const cookingLookup = {
10: "cooked pasta",
15: "burning pasta!",
20: "pasta burnt!!"
}
function New() {
if (foodInOven == true) {
timeOfCooking += 1;
}
if (cookingLookup[timeOfCooking]) {
console.log(cookingLookup[timeOfCooking]);
}
}

Related

Trouble with if statements

function lessThanNinety(num) {
//return true if num is less than ninety
//otherwise return false
//code here
}
Here is the problem, here is my solution.
function lessThanNinety(num) {
if (number < 90) {
return true;
}
else {
return false;
}
}
var number = 50;
Where am I going wrong? Thanks
Seems like you are using wrong variable name, change variable number to num:
function lessThanNinety(num) {
if (num < 90) {
return true;
}
else {
return false;
}
}
and you will need to call the function:
var number = 50;
lessThanNinety(number);

Javascript not working as I want to

Alright, I have made some JavaScript for an assessment. Everything worked fine until I put in a new function with a switch statement called:
function differentComments(answer) {
The program doesn't seem to load the follow function anymore when the function differentComments is in there:
function genQuestion() {
All of my JavaScript code is below (HTML is available on Pastebin):
var x, y; //the global variables
function aNumber() {
return Math.floor(1 + Math.random() * 12);
}
function genQuestion() {
x = aNumber();
y = aNumber();
dout = document.getElementById('Question');
dout.value = x + " times " + y;
}
function buttonPressed() {
var input = document.getElementById('Typed').value;
var answer = x * y;
if (input == answer) {
differentComments("Right");
genQuestion();
} else {
differentComments("Wrong");
}
document.getElementById('Typed').value="";
}
function differentComments(answer) {
var random_number = Math.floor(1 + Math.random() * 4);
if (answer == "Right") {
switch (random_number) {
case 1:
window.alert("Very Good!");
break;
case 2:
window.alert("Excellent!");
break;
case 3:
window.alert("Correct - Nice work!");
break;
case 4:
window.alert("Correct - keep up the good work!");
break;
default:
break;
}
} else (answer == "Wrong") {
switch (random_number) {
case 1:
window.alert("No. Please try again.");
break;
case 2:
window.alert("Wrong. Try once more.");
break;
case 3:
window.alert("Incorrect – Don’t give up.");
break;
case 4:
window.alert("No – keep trying.");
break;
default:
break;
}
}
}
Your else clause is incorrect.
if (answer == "Right") {
switch(random_number) {
...
}
else (answer == "Wrong") {
}
won't parse because the second test is missing an if.
if (answer == "Right") {
switch(random_number) {
...
}
else **if** (answer == "Wrong") {
}
Essentially you're treating an if() as if it's a switch(), and that's not syntactically correct.
The first thing you should do when you run into situations like this is use either jshint or jslint to check the syntactical correctness of your code.
In your code block :
if (answer == "Right") {
switch(random_number) {
...
}
else (answer == "Wrong") {
switch(random_number) {
...
}
}
mean you put if and else statement and a else condition only execute when all if conditions are return false. So there is no need to put conditional-statement(like in your case -else (answer == "Wrong") {) ).
You can simply write this :
if (answer == "Right") {
switch(random_number) {
...
}
else {
switch(random_number) {
...
}
}
It's means if your answer is not equal to Right, it always go to else statement.
OR
If you want to check for more conditions, use else if(){} statements.
if (answer == "Right") {
switch(random_number) {
...
}
else if (answer == "Wrong") {
switch(random_number) {
...
}
}
Read this

nested if/else statements talked about assigning variables...I've already done that and it still doesn't work

Why won't my nested if/else statements work: it takes me to bing.com as a search engine no matter what adult age I enter; everything else works correctly.
function adult_jump(SelectSE, SelectWD, age) {
if (SelectSE==true) {
if (age <= 45) {
window.location = "http://www.google.com"
} else {
window.location = "http://www.bing.com"
}
} else {
if (SelectWD==true) {
window.location = "http://www.yahoo.com"
} else {
window.alert("You must select a search tool!")
}
}
}
while comparing with true or false.. it is better to use the === operator.. i modified the window.location to alert.. so you can see all results at once here
function adult_jump(SelectSE, SelectWD, age) {
if (SelectSE === true) {
if (age <= 45) {
alert("http://www.google.com") ; }
else { alert("http://www.bing.com") ; }
}
else {
if (SelectWD === true) {
alert("http://www.yahoo.com") ; }
else { alert("You must select a search tool!") ;}
}
}
adult_jump(true,false,30); // alerts google
adult_jump(true,false,48); // alerts bing
adult_jump(false,true,0) ; //alerts yahoo
adult_jump("","",0) ; // alerts select a search tool

uncaught Reference error: invalid left hand assignment

if ((value.length == 12) || (value.length == 9)) {
if ((value.length == 12)) {
if (value.substring(0, 2) = "048") { //this doesn't work in the execution
return true;
} else {
return false;
}
}
if ((value.length == 9)) {
return true;
} else {
return false;
}
} else {
return false;
}
You need == like this. you cant have a single = in an if statement
if (value.substring(0,2)=="048"){
It is because you are using the JS assignment operator. Typically var a = 123;
You want to be using === since it doesn't do type coercion. As opposed to == which does.
if (value.substring(0,2) === "048") {
// etc
}

Javascript Testing Corners of an Array (Grid)

I'm doing this project trying to reproduce Schelling's Segregation model. I have a function(below) that is testing to see if the four immediate adjacent cells of the array are either the same or different or empty compared to the current cell being tested.
There are four possible spots to be tested for every cell in the array. But on corners and side spots, obviously you cant test spaces that are out of bounds. So in the function, if it finds one of the out of bounds spaces it decrements the number total around the cell. However, it keeps crashing telling me that I have an Uncaught Reference Error: Cannot read property '0' of undefined. I can't tell why its crashing.
The final lines of this code take the number of goods(similar cells) and the total number of cells around it (empty cells do not count) and gets a percentage similar.
Any help would be appreciated into telling me why it might be crashing and giving me an error? Thanks!
model.Test = function( i, j )
{
var numberToTest= 4;
var goods= 0;
if ((i - 1) >= 0)
{
if (model.BoardArray[i-1][j] != "E")
{
if (model.BoardArray[i][j] == model.BoardArray[i-1][j])
{
goods++;
}
}
else
{
numberToTest--;
}
}
else
{
numberToTest--;
}
if((i + 1) < $("#BoardSizeValue").val())
{
if (model.BoardArray[i+1][j] != "E")
{
if (model.BoardArray[i][j] == model.BoardArray[i+1][j])
{
goods++;
}
}
else
{
numberToTest--;
}
}
else
{
numberToTest--;
}
if ((j - 1) >= 0)
{
if (model.BoardArray[i][j-1] != "E")
{
if (model.BoardArray[i][j] == model.BoardArray[i][j-1])
{
goods++;
}
}
else
{
numberToTest--;
}
}
else
{
numberToTest--;
}
if ((j + 1) < $("#BoardSizeValue").val())
{
if (model.BoardArray[i][j+1] != "E")
{
if (model.BoardArray[i][j] == model.BoardArray[i][j+1])
{
goods++;
}
}
else
{
numberToTest--;
}
}
else
{
numberToTest--;
}
var similar = $("#SimilarSlider").val()/100;
if (numberToTest == 0)
{
return false;
}
else
{
var needed = goods/numberToTest;
if (needed >= similar)
{
return false;
}
else
{
return true;
}
}
}
From looking at your code, you would only get a Reference Error: Cannot read property '0' of undefined. if i was out of the bounds of the array.
I think the problem might be in this part of the code:
if ((i - 1) >= 0) {
if (model.BoardArray[i-1][j] != "E") {
if (model.BoardArray[i][j] == model.BoardArray[i-1][j]) {
if i = $("#BoardSizeValue").val() and $("#BoardSizeValue").val() is a one-based index of the array size, then [i-1] would be okay, but not [i]. So try adjusting your code to this:
if ((i - 1) >= 0 && i < $("#BoardSizeValue").val()) {
if (model.BoardArray[i-1][j] != "E") {
if (model.BoardArray[i][j] == model.BoardArray[i-1][j]) {
This would also apply to the j comparisons as well.

Categories