Thai Bui
Thai Bui

Reputation: 15

Issue with nested if statement (within function) in Javascript

first time here and I've run into an issue... idk if it's my syntax or my logic is completely wrong...

var hasExperience;
var amountOfExperience;

function employed(hasExperience,amountOfExperience) {

  if(hasExperience === true){
    if(amountOfExperience > 5)
      return true;
  } else {
    return false;
  }
}

It doesn't seem to want to return false if the first two if statements aren't met... anyone can help?

Thanks!

Upvotes: 0

Views: 4278

Answers (1)

Sam
Sam

Reputation: 864

If you need both of the if statements to evaluate to true, you should write it like this:

if(hasExperience === true && amountOfExperience > 5){
  return true;
} else {
  return false;
}

In your example, if(hasExperience === true) then you run the code inside the if block, else run the code inside the else block. It's important to understand that this is completely independent of what's inside the if block.

if(hasExperience === true){
    // code inside if block
} else {
    // code inside else block
}

The code inside the if block happens to be another if statement that will return true if(amountOfExperience > 5), and does nothing otherwise. Again, this is independent of the other if statement.

if(amountOfExperience > 5)
    return true;

Using &&, means that both statements have to evaluate to true in order to execute the code inside of the if block. You can read more about this here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators


Also, as some others have stated, you can just write your function like this:

function employed(hasExperience,amountOfExperience) {
    return hasExperience === true && amountOfExperience > 5;
}

Since your evaluating (hasExperience === true && amountOfExperience > 5) as a boolean and returning that boolean, you can avoid the if statement all together.

Try experimenting with this a little bit more to understand what's going on.


Update based on comment:

You could also accomplish this using the nested if, but this makes the code messy and difficult to read.

if (hasExperience === true) {
    // only hasExperience is true
    if (amountOfExperience > 5) {
        // hasExperience is true and amountOfExperience is greater than 5
        return true;
    } else {
        // hasExperience is false and amountOfExperience is less than 5
        return false;
    }
} else {
    // hasExperience is false and we have no idea what amountOfExperience is
  return false;
}

Upvotes: 2

Related Questions