Last active
April 4, 2020 18:00
-
-
Save DavidWells/31b2e2e85d1bd10cc8c924f4c64317d3 to your computer and use it in GitHub Desktop.
Try to avoid returning null when you can. Here is why https://github.com/sindresorhus/meta/issues/7. From https://twitter.com/DavidWells/status/1246251867761344512
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function test() { | |
// simple return or return void 0 to return undefined | |
return void 0 | |
} | |
var x = test() | |
if (!x) { | |
console.log('no x! great check') // good | |
} | |
if (x === undefined) { | |
console.log('x === undefined') // good | |
} | |
if (typeof x === 'undefined') { | |
console.log("typeof x === 'undefined'") // good | |
} | |
if (typeof x === 'object') { | |
console.log("typeof x === 'object'") // Yay not seen as an object like 'null' | |
} | |
function defaultValueFunc(data = {}) { | |
return data.id | |
} | |
defaultValueFunc(undefined) // fine | |
defaultValueFunc(x) // fine | |
try { | |
defaultValueFunc(null) // NOT fine | |
} catch (err) { | |
console.log('Dang it null!') | |
console.log(err) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment