0
If else statements in js
For if and else statements without brackets, how do I know they are working correctly? For example: if (condition) if (condition2) code else code Is the else statement connected to the first if statement or the second?
3 Respuestas
+ 6
Unclear code like this is one of the reasons people highly advise against omitting curly brackets in JavaScript. While it's sometimes convenient to leave them out, it will more often than not create some confusion.
Take the following code:
if (condition)
doSomething()
doSomethingElse()
JavaScript actually interprets this as
if (condition) {
doSomething();
}
doSomethingElse();
The only situation where this is often seen as appropriate is something like the following:
if (x === null) return;
As for your question, see the code below.
https://code.sololearn.com/cKiXHr8tnNMW/?ref=app
+ 4
Another example here.
https://code.sololearn.com/Wxw9eLnS9qh1/?ref=app
If you don't have braces, the else branch sticks to the inner if. The indentation doesn't matter in JavaScript.
Using braces improves readability of your code, and helps avoiding such mistakes and bugs.
0
Of course with the second one.
//The JavaScript compiler doesn't care about indentation, it will remove it. It's like writing code in one line, just don't forget about punctuation marks. I always recommend that students keep the code to a minimum in order to better learn the lesson. In your case, the logic should be such that if you add an "else" statement to the "if" block, then you assume that the condition may be false, let's imitate this case right away and we will get something like this:
if(true)if(false)pass;else console.log(2);
//So we get two conditions following each other, which means that we can write them into one condition:
if(true&&false)pass;else console.log(1);
//Now the question itself disappears, doesn't it.
//Also, this method makes it easier to learn the ES6 ternary syntax:
(true&&false)?pass:console.log(1);
//Agree everything is very simple.
//I hope you already guessed that instead of the "pass" statement, you can write any desired operations in one line.