Javascript challenge Use Conditional Logic with If Statements

Hi, I’m new and don’t seem to be able to reply directly in the challenge topic:

I have two questions. One is that I’m wondering why I can pass arguments other than true or false and still pass the challenge. For instance, I can pass a string:

trueOrFalse("h");

and it will evaluate as true and I pass the challenge.

Or I can pass a number greater than zero; it will evaluate as true and I pass the challenge.

Or I can pass a zero; it will evaluate as false and I pass the challenge.

Why?

My other questions is about if statements in general. Is it the case that everything else inside a function will only run if the if statement evaluates as false? This isn’t explicitly stated in the challenge but seems to be the case.

In general I’m finding the challenges rather sparse on explanation. :frowning:

Here is the full code that is currently passing the challenge:


// Example
function ourTrueOrFalse(isItTrue) {
  if (isItTrue) { 
    return "Yes, it's true";
  }
  return "No, it's false";
}

// Setup
function trueOrFalse(wasThatTrue) {

  // Only change code below this line.
  
  if (wasThatTrue) {
    return "Yes, that was true";
  }
  return "No, that was false";
  // Only change code above this line.

}

// Change this value to test
trueOrFalse("h");

This helps gives a better understanding. How JavaScript is coded, it considers a ‘string’ or a positive number to be true. Similarly, an empty string or a negative number is false.

Question 1

You have stumbled on something that will be officially introduced in the challenge Falsy Bouncer. Values are either “truthy” or “falsy”. When a truthy value is treated like a boolean (for example, in a logical evaluation like an if condition) they are treated like true. Non-empty strings and non-zero numbers are truthy. Falsy values are treated like false when evaluated as a boolean.

Question 2

Not quite.

if (trueCondition) {
    console.log("I only printed because the thing was true");
} else {
    console.log("I only printed because the thing was false");
}

console.log("I am outside the if-else block and will always print.");

BUT

In the case of your code above, there is a return statement inside the if block. This is an important thing to remember for later challenges: the function is over as soon as a return statement is executed.

1 Like

@ArielLeslie @thisiswhale Awesome answers. Thank you so much. :slight_smile: