Skip to content

Instantly share code, notes, and snippets.

@wycats
Last active November 29, 2018 18:47
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 wycats/3cb1a8025423c598e72b6f9ed9157146 to your computer and use it in GitHub Desktop.
Save wycats/3cb1a8025423c598e72b6f9ed9157146 to your computer and use it in GitHub Desktop.
// 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