2

I'm trying to stop the js execution if the validate function returns false. However, if it's false, the script doesn't stop and I can se the message "This will run??" - Would someone give me a hint as to why calling the validate() function inside submit() doesn't work? What's wrong here? Thanks in advance.

// validate name
function validate(name){
    if(name.length < 1){
        console.log('false - length: ' + name.length);
        return false;
    }
}

// submit function
function submit(){
    var name = '';

    // if name is empty, the script should stop.
    validate(name);

    console.log("This will run??");
    return true;
}

submit();
2
  • It does work. It just doesn't do what is incorrectly expect: return only applies to the function body it appears in. Commented Jun 29, 2016 at 1:57
  • 1
    you want if (!validate(name)) return false; And you also need to return true at the end of validate when the check passes. Commented Jun 29, 2016 at 2:00

1 Answer 1

3
function validate(name){
  if(name.length < 1){
      console.log('false - length: ' + name.length);
      return false;
    }
  return true;
}

your validate function should return true (otherwise it returns undefined, which is falsy)

function submit(){
    var name = '';

  // if name is empty, the script should stop.
  if(validate(name)) {
    console.log("This will run??");
    return true;
  } else {
    return false;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.