Rod
Rod

Reputation: 11

Curly brackets at the end of the if statement changes how the program behaves (contrary to not adding the brackets at all). Why?

The difference is noticeable only when choosing an option above 100, this happens even when there is nothing inside the brackets.

I'm new to JS and learning on my own for almost a week now. Would like to know why this little change gives a "different" result.

function To10(numTo10) {
  let rest = 100 - numTo10;
  if (numTo10 < 100) {}
  document.write("How much to 100? ");
  return rest;
}
document.write(To10(1))

With the brackets any number above 99 (for example 100) prints: How much to 100? -1

Without the brackets any number above 99 (again, 100) prints: -1

Upvotes: 1

Views: 42

Answers (2)

Code Maniac
Code Maniac

Reputation: 37755

{} is considered as block statement, which is used to combine multiple statement into one,

so when you don't use {} after if statement it executes the very next statement if the condition evaluates to true

if(true)
console.log('true hello')

if(false)
console.log('false hello')

Where as if you use {} than in case the if evaluate to true it tries to run code inside {}, in this cases it's empty block so it does nothing

if (true){}
  console.log('true hello')

if (false){}
  console.log('false hello')

For sake of avoiding such confusions it always better to add the code you want to run inside {} if conditional statement is true

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44087

Because without the braces, it's interpreted as:

if (numTo10 < 100) document.write("How much to 100? ");

Which is equivalent to:

if (numTo10 < 100) {
  document.write("How much to 100? ");
}

It's easier and less confusing in this case to invert the condition:

if (numTo10 >= 100) {
  document.write("How much to 100 ?");
}

Upvotes: 1

Related Questions