Skip to content

Instantly share code, notes, and snippets.

  • Save crates/4c8c3a66f18d8574ad276d75a8d58d91 to your computer and use it in GitHub Desktop.
Save crates/4c8c3a66f18d8574ad276d75a8d58d91 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