Use Conditional Logic with If Statements101

Function below says that check myCondition if it is true return the value “it was true”. My question is when i call the test(true), how if statement checks that myCondition is true even though there is no condition set to inside the if statement such as myCondition == True.

could you please help?


function test (myCondition) {
  if (myCondition) {
     return "It was true";
  }
  return "It was false";
}
test(true);  // returns "It was true"
test(false); // returns "It was false"

It’s a feature of the language … or “because JavaScript was designed that way”. The conditions are reduced to either true or false, but if you pass it one of these values directly, it acts upon that … if-statements also interpret so called “truthy” values as true:

if (true)
if ({})
if ([])
if (42)
if ("0")
if ("false")
if (new Date())
if (-42)
if (12n)
if (3.14)
if (-3.14)
if (Infinity)
if (-Infinity)

and the “falsy” ones as false:

if (false)
if (null)
if (undefined)
if (0)
if (-0)
if (0n)
if (NaN)
if ("")

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if…else

2 Likes

ok got it ! thank you so much!

2 Likes