i have a question on the if…else statement …why we didn’t put a semi-colon after the code block of else statement for example:
if (sale) {
console.log(‘Time to buy!’);
} else {
console.log(‘Time to wait for a sale.’)
}
*I meant after the last parentheses of else …
why didn’t we write it as
else {
console.log(‘Time to wait for a sale’);
}
Semi-colon tells the interpreter to stop parsing and begin compiling. An if statement does not end untl after the else block. Even then we don’t give it a semi-colon since it is well delimited and the interpreter knows to parse from if to the final }.
The statements inside the blocks may well need a semi-colon, though we might be able to relax that requirement when there is but one statement in the block. Newer iterations of JS in most browsers will auto-insert them but we should not depend upon this a reliable feature.
From my understanding of doing a bit of research into the topic is that it is both a personal choice and assists with readability.
You could write that code as:
if (false) {
console.log(‘The code in this block will not run.’);
}
else {
console.log(‘But the code in this block will!’);
}
The above would work exactly the same way, but when you start nesting if statements in other if statements, it makes it more readable if you indent the else statement after the if, as when you are reading it, you will immediately know that that else statement belongs to that if statement, where if you do it the way I showed above, it might take a little more investigation to find out which one it belongs to.
If it is just a matter of readability, personally I find doing it the following way a lot better for knowing what belongs where at a glance, even if it uses more lines:
if(sale)
{
console.log('Time to buy!');
}
else
{
console.log('Time to wait for a sale.');
}
Especially in text editors where you can fold curly bracket contents, I find it really helps, especially for nested conditionals. Apparently I must be in the minority from what I read everywhere. My question is: would this different preference somehow hamper my eligibility or ability to work in a team?
Partially related question… Are you suppose to put a semicolon at the end of that entire statement?
else {
console.log(‘Time to wait for a sale’);
};
^^right here. Not sure if this is incorrect. I was under the impression that the entire statement had to end with it as well. I ran it this way during this challenge just to see what would happen and it still ran correctly. Does this just fall under clean code orrrrr
No, only the statements inside the code block. Being superfluous, it will have no effect. It looks rather out of place to an experienced coder so form the habit of not including it anywhere but in the blocks.
Well done! I think we’re (some of us) used to the CSS way of moving down to the next line, but this makes total sense. Thank you for putting this answer up!
Sorry but as I move ahead in the Javascript module, I started payinf attention to the syntax of the { if…else} pair, and noticed these " lines of code which look contradictory to me : https://www.codecademy.com/courses/introduction-to-javascript/lessons/control-flow/exercises/true-false-values.
In the first example there is no semicolon at the end of the block , whereas in the second there is one.
What is it that I am not getting ? thks in advance
Semi-colons have a place when they actually end a statement AND there is another statement following. Inside a block (or a function) the last statement in the block does not need a semi-colon. You’ll find this same pseudo-rule applies in a CSS declaration block, as well.
let condition;
if (condition) {
console.log(true)
} else {
console.log(false);
console.log("The condition has not been met.")
}
Note the slight variance in the examples. The first line has a statement following so we give it a semi-colon. The true branch code block has but one statement, so the semi-colon is optional. The else branch has two statements, so the first one gets a semi-colon, and the last one is optional.
The if statement itself is delimited with curly braces so is never given a semi-colon.
JS is a very loose language when we don’t specify 'use strict' so there is no actual syntax enforcement of the ‘end of statement tokens’, leaving it mostly up to us to judge when they ought to be used, and when they don’t need to be used (as in superfluous).
Add to this that modern browsers may have the built in ability to auto-insert the tokens when the interpreter deems them necessary. If we assume this to be always the case we risk forming a habit that may come back to bite us, especially if we run a minifier over our code to compress the production file.
Bottom line, the semi-colon is not as crucial in JS as it is in other more strict compiled languages such as C, C++, C# and Java, among others that require a token at the end of every statement, no exceptions. Forming a habit of using them can never hurt since it can be carried forward into the lower level languages.
Thanks ! Beig a language teacher myself , I’m always looking for “rules”
They help me “edit” my code after writing sth or looking for misitakes one I have one, and that’s pretty common!
Your explanation is really clear.
thks!
in most practical applications, your conditionals will lead to things that take up more lines than that, but having it that way is fine if it fits
nesting, you can’t see the structure of nested conditionals.
e.g.
let condition1, condition2, condition3;
if (condition1) {if (condition2) {if (condition3) {console.log("All three")}
else {console.log("1 and 2 but not 3")}
else if(condition3){console.log("1 and 3")} else {console.log("just 1")}
else if (condition 2) {if(condition3){console.log("2 and 3")}
else {console.log("only 2")}}
else if(condition3) {console.log("just 3")}
else {console.log("none")}}
it’s just a mess, whereas that same thing will be 100x more readable and make so much more sense if you structure it as you’re writing it
let condition1, condition2, condition3;
if (condition1) {
if (condition2) {
if (condition3) {
console.log("All three")
}
else {
console.log("1 and 2 but not 3")
}
else if(condition3) {
console.log("1 and 3")
}
else {
console.log("just 1")
}
else if (condition 2) {
if(condition3) {
console.log("2 and 3")
}
else {
console.log("only 2")
}
}
else if(condition3) {
console.log("just 3")
}
else {
console.log("none")
}
}
for this specific problem you’d actually just use like a switch statement or something instead of repeated conditionals, but a lot of times you’ll be mixing a bunch of different things like function calls which return boolean values where you will actually need to structure the conditionals yourself in order for it to be readable.
imo it’s fine to do that for things that only take up one line, like if(condition) {console.log"yes")}, but anything where there’s something more meaningful or dynamic inside of the conditional, like another conditional, a function call, a loop, or a switch, you’re gonna wanna get into the habit of indenting each level so it’s neatly nested and legible.