Last active
November 29, 2018 18:47
-
-
Save wycats/3cb1a8025423c598e72b6f9ed9157146 to your computer and use it in GitHub Desktop.
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
// default tagName is 'div' | |
// The problem | |
function createElement(tagName: string): Element { | |
// very broken | |
return document.createElement(tagName || 'div'); | |
} | |
// you might want to use defaults | |
function createElement(tagName: string = "div"): Element { | |
return document.createElement(tagName); | |
} | |
createElement(); // <div> | |
createElement(null); // <null> | |
// but maybe you are just going to keep doing it inline | |
// let's look at the semantics of ?? where it only coalesces undefined | |
function createElement(tagName: string): Element { | |
return document.createElement(tagName ?? "div"); | |
} | |
// in this case, it has the same behavior as the previous example | |
// however, maybe you are TRYING to coalesce away nulls | |
function createElement(tagName: string): Element { | |
return document.createElement(tagName == undefined ? 'div' : tagName); | |
} | |
// what happens if we make ?? coalesce null AND undefined | |
function createElement(tagName: string): Element { | |
return document.createElement(tagName ?? "div"); | |
} | |
// however, what if you are trying to match the behavior of the built-in default syntax | |
function createElement(tagName: string): Element { | |
return document.createElement(tagName === undefined ? 'div' : tagName); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment