How to write an IF else statement without 'else' in JavaScript [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I can't use else in my script; how can I implement an if else statement without using else?
I'm trying to resize a div:
function hideTable(){
var table = document.getElementById('PDemo');
if(table.style.width == "50%") table.style.width = "150px";
if(table.style.width == "150px") table.style.width = "50%";
}
This script doesn't work because as soon as the first if statement is executed, the condition for the second if statement becomes true, so that executes too, and thus nothing changes.

The ternary operator:
condition ? execTrue() : execFalse();
This is equivalent to:
if (condition) {
execTrue();
}
else {
execFalse();
}
You can write an if/else in 1 line, just don't press enter...
if (condition) { execTrue(); } else { execFalse(); }
Further, you can write any statement of arbitrary complexity on one line:
if(condition1) { exec1(); } else if(condition2) { exec2(); } else { execFalse() }
If you're having the issue where the second if statement executes as well, you want to impose mutual exclusion, i.e., using else if instead of just if on each subsequent conditional.

Save the value into a different variable.
function hideTable(){
var table = document.getElementById('PDemo');
var width = table.style.width;
if(width == "50%") table.style.width = "150px";
if(width == "150px") table.style.width = "50%";
}

If you can't use an else (and that is crazy), use a switch.
switch (table.style.width) {
case '50%':
...
break;
case '150px':
...
break;
}

if(/*condition a*/){/*statements a*/}else if(/*condition b*/){/*statements b*/}else{/*statements c/*}
One line only.

With a while loop for the sake of uniqueness.
while (!resized){
if(width == "50%") {table.style.width = "150px";resized=true;break};
if(width == "150px") table.style.width = "50%";resized=true;break};
resized=true;
}

The && operator is called a short-circuit operator. It will return the value of the second operand based on the value of the first operand.
For example: (explanation : If 'profile' permission exists in permArray then load the user's profile)
isPermitted(permArray, 'profile') && loadProfile();
The && operator is useful also for checking for null objects before accessing their attributes. For example...
var name = person && person.getName();

Related

Getting Undefined for this Javascript Function and Not Sure why [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
Okay. So, I'm quite a newbie to JS, but not to programming in general. I've written a little bit of a recursive function (don't mind the logic here), that works perfectly in Python but returns undefined in JavaScript. This may totally be a noob thing here, but I can't really find the source of this issue, especially as it works fine in Python.
I had initially thought it was a control flow issue but I wrote other control flow functions that worked fine. Also, right before the final return statement, I console.log the array and the values are returned. Any help will be appreciated
path = []
let find_multiplier = (numb) => {
if (numb === 1) {
console.log("a result is possible for this number");
console.log(path)
return path;
} else if (numb > 1) {
if (numb % 3 === 0) {
path.push("multiply by 3");
find_multiplier(numb / 3);
} else {
path.push("add 5");
find_multiplier(numb - 5);
}
} else {
return false
}
};
console.log(find_multiplier(13)); // returns undefined. should return values.
console.log(find_multiplier(15)); // returns undefined. should return false.
The problem here is that 2 of your 4 conditions does not return anything.
You can fix this by adding the return keyword in front of your recursive call.
path = []
let find_multiplier = (numb) => {
if (numb === 1) {
console.log("a result is possible for this number");
console.log(path)
return path;
} else if (numb > 1) {
if (numb % 3 === 0) {
path.push("multiply by 3");
return find_multiplier(numb / 3); //here
} else {
path.push("add 5");
return find_multiplier(numb - 5); //here
}
} else {
return false
}
};
console.log(find_multiplier(13)); // returns undefined. should return values.
console.log(find_multiplier(15)); // returns undefined. should return false.
I believe two of your cases are missing return statements:
if (numb % 3 === 0){
path.push("multiply by 3");
return find_multiplier(numb / 3); // <-- add return here
} else {
path.push("add 5");
return find_multiplier(numb - 5); // <-- and here
}
However, you are also mutating a variable (path) outside of the scope of your function, so I would guess even they way you have it currently, path may actually contain the result you're looking for. I would choose to either mutate the out-of-scope path array and not try to also return it, or declare the variable in your function and return that, with a preference to the latter.

Two conditions in if statement in javascript does not appear to work correctly [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am unable to get a multiple if statement to work properly.
This is an extract of code from TileBoard for HomeAssistant.
Here's what I have:
title: function (item, entity) {
var start = entity.attributes.next_activity_start;
var hold_state = entity.attributes.hold_state;
var hold_until = entity.attributes.hold_until;
if ( hold_state == "on" && hold_until == "null" ); { return 'N/A - Hold'; } return timeAgo(start);
},
hold_state gets populated with "on" and hold_until gets populated with "null" which is exactly what I am expecting in this code. But, then the if clause seems to only really work properly by looking at the first condition, and not properly taking into account the second condition (hold_until == "null"). Am I using an incorrect syntax in this if statement? I'm wanting it to return "N/A - Hold" if hold_state is on AND hold_until is null.
I think its because, you are expecting a string null. Type expecting null without the string type, also remove the ; after if case
if ( hold_state == "on" && hold_until == null ) { return 'N/A - Hold'; } return timeAgo(start);
if ( hold_state == "on" && hold_until == "null" ); //this semicolon should be removed
{
return 'N/A - Hold';
}
return timeAgo(start)
Also look at your condition. I assume you want to check if your variable is not null:
if (hold_until != null && hold_state == "on")

Variable returns undefined no matter what it is set to [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
In this function, I initialize the variable allowDial() and later define it.
I was having some problems with its value so I added a console.log to the end of the offHook() function. I define it right before. No matter what I set allowDial to, it returns undefined - be it number, boolean, string, etc.
Why is console.log returning undefined? If I can't get console.log to accurately report its value, I don't see how I can make this implementation of the variable work.
Here is the relevant code:
var allowDial;
var availableNumbers = ["0", "911", "1 (847) 765-1008" , "867-5309", "1 (212) 456-1414", "555-1212", "555-5555"];
function numberSuggestion() {
var randomNumber = Math.floor(Math.random() * (availableNumbers.length));
var suggestedNumber = availableNumbers[randomNumber];
document.getElementById("suggestion").innerHTML = "How about dialing <strong id='suggestedTelephoneNumber'>" + suggestedNumber + "</strong>? Don't like this number? Click the button above again!";
}
var dialTone;
function offHook() {
document.getElementById("WE2500").style.display = "none";
document.getElementById("dialPad").style.display = "block";
dialTone = new Audio('dialTone.m4a');
dialTone.play();
allowDial === true;
console.log(allowDial);
}
You are not assigning any value to allowDial. === is used for comparison, not assignment. For assigning a value you should use allowDial = true;
You don't assign any value to allowDial.
allowDial = true;
Example:
var tmp;
testVar(tmp); // "is null"
tmp = null;
testVar(tmp); // "is null""is definitive null"
testVar()
function testVar(variable) {
if(variable == null) {
console.log("is null");
}
if(variable === null) {
console.log("is definitive null");
}
}

Is there an alternative to javascript loop? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I was working on a program, I came to a point where I wanted to loop a value and then use it to test user's input with the if statement, but the problem was that I couldn't use the value of the loop.
At least that's what I think, then I tried placing the if statement as one of the codes that the loop statement is supposed to execute, surprisingly it worked, but when I tried more that one if statement (ie. else if), it only executed one of my if statement.
Please is there an alternative method to use?
Below is the code (Input a Number between 0 and 10):
<input type="number" id="i" />
<input type="button" value="submit" onclick="result()" />
<p id="k"></p>
<script>
function result (){
//first method
var x= i.value;
var y = 0
while (y<10){
y++
}
if (x==y) {
document.getElementById("k").innerHTML = "correct"
}
/ * it didn't work probably because the if statement assumes y to be 0. /*
//second method
while (y<10){
y++
if (x==y) {
document.getElementById("k").innerHTML = "correct"
}
else if (x >y ) {
document.getElementById("k").innerHTML ="wrong"
}
}
//it only tested one of the if statement
</script>
Or is there another way instead of looping?
Some issues with your code:
The first instance the if statement is not inside the loop.
Once you're done with the loop you want to exit it with a break;
In the 2nd instance the else if block should appear after the loop. Why? For example the user enters 2. In the first iteration of the loop 2==1 will fail, 2 > 1 will be true, but it's not the wrong answer. x > y is only the wrong answer when y itself is >= 10.
Instead of looping you can check if the value itself is greater than 0 and less than 10, you can combine as many conditions as you want e.g.
function result (){
//first method
var x= Number(i.value); // Number isn't necessary.
if ( (x > 0) && (x < 10) ) { // The && means "and", so if x is greater than 0 and less than 10.
document.getElementById("k").innerHTML = "correct";
} else {
document.getElementById("k").innerHTML = "wrong";
}
}

Javascript for loop with if statement not reaching the else if statement [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
why wont this reach the else if and return (i + 0) / 2? Also, why wont the alert give me i + 0 for a 2 digit value? (ie: 10, 20, 30, 40, etc. Any help would be appreciated.
var key= "OSN0MSA9991UNAAM8ELDPBD9F57BD6PU6BVBN54CDLEGDSUSNS";
var x = 0;
if (key[20] != "P" || key[18] != "P") {
x = 0;
for (i=0;i<10;i++) {
if (key[26] == i) {
x = i + 0;
alert(x);
}
};
} else if (key[20] == "P") {
for (i=9;i>-1;i--) {
if (key[26] == i) {
x = (i + 0) / 2;
alert(x);
}
};
};
your value at key[18] is "L" so if condition is always true and you will get an alert with value 7
It's not hitting the "else if" I believe because your array starts at 0, and the key[20] is in fact a P, so it's going to always fall in to the first condition and not hit the else if. EDIT: My mistake, misread. You could alert out the key[20] and key[18] to see what it thinks those values are.
Your issue is with the key[18]. Since you have an OR and key[18] = L (hence not P)..

Categories

Resources