Why doesn't Mosh use an 'else if' statement after the first 'if ' statement?


My doubt is: if the ‘if’ is being used repeatedly and in the case of an average which is as low as 50, it satisfies all the conditions. This is why I used the 'else if ’ statement, and when I use the “if” statement, I get all the grades after compilation.

Mosh is returning from the function in each of those if conditions, so it short-circuits. When you always return in the if branch, there is no meaningful difference between these two:

// Using else if
if (condition) return something;
else if (anotherCondition) return somethingElse;

// Using if
if (condition) return something;
if (anotherCondition) return somethingElse;

Since they are equivalent, many programmers will choose to be less verbose and drop the else.

If you did not return, there would be a meaningful difference. For example:

// Using else if
if (someCondition) someVariable = something;
else if (anotherCondition) someVariable = somethingElse;

// Using if
if (someCondition) someVariable = something;
if (anotherCondition) someVariable = somethingElse;

In this situation, someVariable would be left as somethingElse if both conditions matched because the if branch does not short-circuit (meaning it does not prevent the rest of the conditions from being checked.

2 Likes

One more thing, if I have more than one statement after a loop, do I need to put that in a code block to be considered by the loop?
I mean, in python, the indentation does the job, but in js, I don’t see that sort of usage of indentation??

There are very few languages like Python where indentation and whitespace are used to define code blocks. Brackets are the most common I have seen across languages to define a code block. Many languages also support dropping the brackets if the code block is exactly one line. JavaScript is one such language.

In general, for loops in JavaScript should look like this:

for (initializer; condition; updater) {
  statement1;
  statement2;
  ...
}

Thank you very much. Could you please recommend some book or some resource for me to get well versed with these nuances of JavaScript? I am new to programming.

I have no personal experience with any books on JavaScript, but it looks like A Smarter Way to Learn JavaScript by Mark Myers comes highly recommended by various programming sites (and is very affordable). As you learn more about programming, you will probably find that there are many things which you carry over from one language to another.