-1

In the following get function: If parent && parent.parentNode is true and the return value is parent.parentNode.selectedIndex -- will the function return null at the end, too?

get: function( elem ) {
    var parent = elem.parentNode;
    if ( parent && parent.parentNode ) {
        parent.parentNode.selectedIndex;
    }
    return null;
}
4
  • 1
    Yes...It will...All the time.... Commented Apr 1, 2016 at 6:09
  • 2
    It will always return null, you're not telling it do anything else Commented Apr 1, 2016 at 6:09
  • 3
    You are not returning anything except null. You need return parent.parentNode.selectedIndex; inside the function. And then it will return null only if your condition fails. Commented Apr 1, 2016 at 6:09
  • Okay, thanks for clarifying! Commented Apr 1, 2016 at 6:11

2 Answers 2

1

You need to use a return statement within the if statement. Return statements in JavaScript return control back to the parent function immediately. So if function 1 calls function 2, as soon as function 2 comes to a return statement, it stops what it's doing and passes control, and data if specified, back to function 1.

get: function( elem ) {
    var parent = elem.parentNode;
    if ( parent && parent.parentNode ) {
        return parent.parentNode.selectedIndex;
    }
    return null;
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to return only a value

If parent && parent.parentNode is true

or return null

If parent && parent.parentNode is false

then write the below code

get: function( elem ) {
    var parent = elem.parentNode;
    if ( parent && parent.parentNode ) {
        return parent.parentNode.selectedIndex;
    }
    else{
        return null;
    }
}

Comments

Your Answer

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