Louiee
Louiee

Reputation: 75

Quiz, is their answer wrong?

I had this question in a test.

What is the output of the following incorrect javascript code and what is the error?

num=0;
if (num > 10);
{
    num = num + 10;
}
alert(num);

The possible answers:

a) Output 10. There should not be a semicolon(;) at the end of the if statement if(num > 10)

b) Output 0 There should not be quotes around the num in the alert statement alert("num");

c) Output 10. There should not be a semicolon(;) at the end of the if statement if (num > 10)

d) Does not execute at all. There is an error with the calculation num = num + 10;. num == num + 10;

My answer is:

As is it would not execute, but if we removed the semicolon after if statement, and added var it would. The output would be zero.

This is because num is not greater than 10, therefore the if statement doesn't do anything. num still = 0.

There should be no semicolon after the IF statement. var should be used in front of the num variable.

Their answer was a).the output would be 10, and there should be no semicolon after if statement.

The statement doesn't work, but if we tidy it up the answer would still never be 10.

Is the question a poorly written question? Are they wrong, or am I wrong?

Upvotes: 2

Views: 95

Answers (3)

Cully
Cully

Reputation: 6965

Since there's a semicolon after the if statement, it essentially has no body and therefore nothing to run if it's true. You can think of it as ending at the semicolon.

Block statements (statements inside of brackets, {}) are valid in Javascript and, in this case, would just run like normal code. So the num = num + 10 runs. Since the if statement above ended at the semicolon, this code runs regardless of the result of the if statement. Think of it as having nothing to do with the if statement.

So the result is 10. And yes, you likely want to remove the semicolon after the if statement to get the desired result.

You can test it out if you want:

num=0;
if (num > 10);
{
num = num + 10;
}
alert(num);

Upvotes: 2

Abhishek Kulkarni
Abhishek Kulkarni

Reputation: 1767

Since there is a semicolon after the if statement, the if statement is ignored.

The statements inside the block will be executed so the below code executes :

num = num+10 

And you get 10 as your answer.

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370879

A semicolon after an if condition is not a syntax error, unfortunately - it just means that the result of the if condition is not used, because no statements run if it's true.

The { immediately following it is valid syntax, despite being disconnected from the if - it's a bare block. Bare blocks are valid too, but pretty weird - they mostly just create a new scope that const and let variables declared inside do not leak out of.

num=0;
if (num > 10);
{
num = num + 10;
}
alert(num);

See how "Run code snippet" results in 10 popping up.

The quiz is correct.

Upvotes: 4

Related Questions