This question already has answers here:
Are braces necessary in one-line statements in JavaScript?
(22 answers)
Closed 7 years ago.
I've searched and I can't find a question already like this. However, why does this code work?
this.askTeller = function(pass) {
if (pass == 1234) return bankBalance;
else return "Wrong password.";
};
Shouldn't it be like
this.askTeller = function(pass) {
if (pass == 1234) {
return bankBalance;
}
else {
return "Wrong password.";
};
Shouldn't it be like
Arguably, it should be:
this.askTeller = function(pass) {
if (pass == 1234) return bankBalance;
return "Wrong password.";
};
or
this.askTeller = function(pass) {
return pass == 1234 ? bankBalance : "Wrong password.";
};
E.g., there's no point to the else at all.
But getting to your point about {}: They're optional. Control-flow structures like if (and while, and for, etc.) are connected to the one statement that follows them; if you want to have them connected to more than one statement, you use the block statement ({...}) to do that.
Many, many, many people always use the block statement even when they could get away with not using it, both for clarity and to make it easier to add a second thing into the block.
in Javascript the curly brackets are optional for if/else when you have only one statement after to execute. Note that if you will execute multiple stuff after then you will need to include the {/} or only the first statement will be applied to the condition
You can drop curly braces for nearly all block-scoped structures (if, for, while, etc). The only exception (heh) I've ran into where this isn't the case is with try and catch.
If you don't include curly braces, only the first statement after the block will be executed.
var out = document.getElementById("out");
for (var i = 0; i <= 5; i++) out.innerHTML += i;
if (out.innerHTML === "012345") out.innerHTML += " success!";
<textarea id="out"></textarea>
brackets are optional for if statement
Related
This question already has answers here:
IF Statement Always True
(3 answers)
Closed 5 years ago.
I have the following code:
console.log(usernameExists);
if (usernameExists = true) {
console.log("returning true");
return true;
} else if (looped = true) {
console.log(usernameExists+" is returned");
looped = null;
return false;
}
The first console.log(usernameExists) is returning false, but still I am getting a console message of "returning true", and the function in which this is, is returning true! I simply can't figure this out.
The condition is always true, because you assign this value to the variable and this is the value which is evaluated for the if clause.
But you could use a direct check without a compare value (and without assigning this value).
Beside that, you could change the else part to only an if part, becaue you exit the function with return, so no more else happen in this case.
if (usernameExists) {
console.log("returning true");
return true;
}
if (looped) {
console.log(usernameExists+" is returned");
looped = null;
return false;
}
= is an assignment, so you're setting the variable to true, which itself makes the if statement true. What you want is to check if the variable is set to true. In order to do that, use the == or === operators.
For checking conditions, you need to use '==' operator. '=' means assignment operator.
Whereas a '===' checks for value and type.
Hope that is the issue.
In your conditions you are using a single equal!!!
Therefore, it is a assignation operation that is done instead of comparison! So you are not checking that your variable is equal to true but you are assigning it to true and since your assignement operation was successful your condition is at the same time fulfilled.
Change it with two or tree equals == or === instead of =
Usage and differences between == and === are explained very well here:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
This question already has answers here:
Javascript conditional return statement (Shorthand if-else statement)
(2 answers)
Closed 1 year ago.
I am trying to learn how can i return in expressions, it might be impossible but any close solution can be helpfull
var something = ()=>{
(true) && (return true)
}
console.log(something())
and is a logical operator , it checks the logic and return the bool
value .you cannot use return statement within logical operator.In that
place (just to look cool) you can use ternary operator
for example:
var something = ()=>{
num=4;
return (num === 4) ? "Correct!": "Incorrect!";
}
console.log(something())
Just take an if statement along with the wanted return statement.
if (true) return true;
This question already has answers here:
How to use if-else condition in arrow function in JavaScript?
(6 answers)
Closed 4 years ago.
storyWords.filter(word => if (unnecessaryWords.includes(word)){
continue;
}
else{
betterWords.push(word);
}) ;
I keep getting an error "Unexpected token if", I was wondering if when you use an arrow function the syntax for if statements is different than in a regular function.
If you're having a statement (break, continue, if...else or switch) inside the arrow function you need to use curly braces: { }.
Arrow functions can have either a "concise body" or the usual "block body".
In a concise body, only an expression is specified, which becomes the explicit return value. In a block body, you must use an explicit return statement.
- MDN web docs
So write:
storyWords.filter(word => {
if (unnecessaryWords.includes(word)) {
continue;
} else {
betterWords.push(word);
}
});
This question already has answers here:
Function declarations should not be placed in blocks. Use a function expression or move the statement to the top of the outer function
(2 answers)
Closed 6 years ago.
Why should we avoid call functions inside if conditions in functions? For instance:
var numberChoice = function(number){
if (number == 1){
alert("You have choosen 1");
nextLevel();
}
else if(number == 2){
alert ("You have choosen 2");
nextLevel2();
}
else{
alert("Please choose a number within range 1-2");
guessAgain();
}
};
var number = prompt("What is your number?");
I could possible have missunderstood what's going on. Are you able to give an explanation of it?
function example(){
function a() {} // Okay
if (something) {
function b() {} // Danger!
}
}
Haverbeke, Marijn (2014-12-04). Eloquent JavaScript: A Modern Introduction to Programming (Kindle Locations 1168-1169). No Starch Press. Kindle Edition.
Unless your function (within if condition) is asynchronous there is no problem.
The functions that you are using is synchronous - meaning your script will finish executing it and return a value first before going to next task - in this case it will work fine.
For asynchronous function (which is executed in parallel to the other lines of instructions), then the results from that function is not returned yet and your script will continue without the right value (returned value) from it - this will cause problem.
In your two sample there is no issue.
there is no rule that don't allow you to call function in a if condition.
the only point is a warning when you have several if on the same checking :
if (number === 1) {
function1();
}
if (number === 2 ) {
function2();
}
in that case if you don't put return at the end of your function when the function will be called other condition will be evaluate.
better code is using else or switch
In your case there are no issue.
This question already has answers here:
Are braces necessary in one-line statements in JavaScript?
(22 answers)
Closed 8 years ago.
I have occasionally seen (on stack overflow) code snippets that omit the braces in the else clause of the if statement. I had thought (for years and years) that this was invalid and all my recent research has supported this view, and I have edited them back in where I wanted to use the code snippet myself.
Then a year of so ago, without concentrating much I reused a segment of code from stack overflow on how to efficiently extract query string parameters from href.location that (without my noticing it) ended .... else return ; i.e. no braces around the else clause.
This has worked fine in both Firefox chrome and safari but I do not know why.
At the same time I realised that the else if clause is actually an else followed by a single if statement with no braces. Is this the same logic that you do not actually need braces around a single else clause statement?
Blocks are only required if you give more than 1 commands.
if(condition)
command;
else
command2;
//////////////////////////
if(condition){
command;
} else
command2;
//////////////////////////
if(condition){
command1;
command2;
} else command1;
you can skip braces since there's only ONE statement
The expression
if (condition)
single_statement;
else
single_statement;
and it's combinations with {...} after both if and else parts are part of the JavaScript language.
All conditional statements in js and in most languages control whether or not the next "thing" is executed, which could be a statement (e.g. return) or a block (e.g. { //code }).
They're only required for multi-line commands. Thus it is personal preference whether to use them for single-line commands.
I myself always use the braces, even on single-line commands. It improves the readability for such small effort for me, that it's not worth leaving them out.
I don't know where you looked, but the standard is pretty clear on this subject:
Section 12.5:
IfStatement :
if ( Expression ) Statement else Statement
if ( Expression ) Statement
where a Statement is defined a level up as
Statement :
Block
VariableStatement
EmptyStatement
ExpressionStatement
IfStatement
IterationStatement
ContinueStatement
BreakStatement
ReturnStatement
WithStatement
LabelledStatement
SwitchStatement
ThrowStatement
TryStatement
DebuggerStatement