Skip to content

Instantly share code, notes, and snippets.

@flawyte
Last active May 24, 2020 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flawyte/e7e39d1d48aa1d5e7512b21bb8429b1f to your computer and use it in GitHub Desktop.
Save flawyte/e7e39d1d48aa1d5e7512b21bb8429b1f to your computer and use it in GitHub Desktop.
How JavaScript handles inner `if` and outer `else` when there's no brackets

Given this function :

function testFn(a1, a2) {
    if (a1)
        if (a2)
            return 'a1 && a2';
    else
        return 'else';
}

you would think that the following is true :

testFn(true, true); // expected to return `'a1 && a2'`
testFn(true, false); // expected to return `undefined`
testFn(false, false); // expected to return `'else'`

but no! JavaScript handles the else as a sibling of the inner if, not the outer one. If you run the code above here's what you'll get instead :

testFn(true, true); // returns `'a1 && a2'` (as expected)
testFn(true, false); // returns `'else'` (!!)
testFn(false, false); // returns `undefined` (!!)

Beware of this as this can create subtle bugs in your code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment