Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save djD-REK/93bead868bf5b443bf277787a6bd3596 to your computer and use it in GitHub Desktop.
Save djD-REK/93bead868bf5b443bf277787a6bd3596 to your computer and use it in GitHub Desktop.
// This will safely check a value to make sure it has been declared and assigned a value other than null or undefined:
console.log(typeof undeclaredVariable !== "undefined" &&
(typeof undeclaredVariable !== "object" || !undeclaredVariable)) // false
// Compare to checking for null using ==, which will only work for declared variables:
try { undeclaredVariable == null } catch(e) { console.log(e) } // ReferenceError: undeclaredVariable is not defined
try { undeclaredVariable === null } catch(e) { console.log(e) } // ReferenceError: undeclaredVariable is not defined
try { undeclaredVariable === undefined } catch(e) { console.log(e) } // ReferenceError: undeclaredVariable is not defined
let declaredButUndefinedVariable
// Values that have been declared but not assigned a value will have the value undefined, which has a typeof undefined:
console.log(typeof declaredButUndefinedVariable !== "undefined" &&
(typeof declaredButUndefinedVariable !== "object" || !declaredButUndefinedVariable)) // false
let stringVariable = "Here's Johnny!"
// If the variable has been both declared and assigned a value that is neither null or undefined, we will get true:
console.log(typeof stringVariable !== "undefined" &&
(typeof stringVariable !== "object" || !stringVariable)) // true
// This can be used to create a function that will return false for undefined, undeclared, and null values:
const isNotNullNorUndefined = (value) => typeof value !== "undefined" && (typeof value !== "object" || !value)
console.log(isNotNullNorUndefined(stringVariable)) // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment