Created
November 17, 2020 19:54
-
-
Save DoctorDerek/63c32245dd4b21fc1b3c8cf47357df2d to your computer and use it in GitHub Desktop.
Using typeof to catch undeclared variables when checking for an Array
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
// Declared array example using typeof: | |
const declaredArray = [] | |
let isThatAnArray = false | |
console.log(typeof declaredArray) // object | |
if (typeof declaredArray === "object") { | |
// Alternatively, typeof declaredArray !== "undefined" | |
// would screen out undefined & undeclared variables | |
isThatAnArray = Array.isArray(declaredArray) | |
} | |
console.log(isThatAnArray) // true | |
// Undefined variable example using typeof: | |
let undefinedVariable | |
isThatAnArray = false | |
console.log(typeof undefinedVariable) // undefined | |
if (typeof undefinedVariable === "object") { | |
isThatAnArray = Array.isArray(undefinedVariable) | |
} | |
console.log(isThatAnArray) // false | |
// Undeclared variable example using typeof: | |
isThatAnArray = false | |
console.log(typeof undeclaredVariable) // undefined | |
if (typeof undeclaredVariable === "object") { | |
isThatAnArray = Array.isArray(undeclaredVariable) | |
} | |
console.log(isThatAnArray) // false | |
// Undeclared variable example using try-catch: | |
isThatAnArray = false | |
try { | |
isThatAnArray = Array.isArray(undeclaredVariable) | |
} catch (e) { | |
console.log(e) | |
// ReferenceError: "undeclaredVariable is not defined" | |
} | |
console.log(isThatAnArray) // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment