If else statements in js | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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?

20th Sep 2022, 11:25 PM
ITDW
3 Answers
+ 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
21st Sep 2022, 3:25 AM
Daniel C
Daniel C - avatar
+ 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.
21st Sep 2022, 3:54 AM
Tibor Santa
Tibor Santa - avatar
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.
21st Sep 2022, 12:09 AM
Solo
Solo - avatar