惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Check Point Blog
AI
AI
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
U
Unit 42
Vercel News
Vercel News
Stack Overflow Blog
Stack Overflow Blog
P
Proofpoint News Feed
Microsoft Security Blog
Microsoft Security Blog
The GitHub Blog
The GitHub Blog
WordPress大学
WordPress大学
Martin Fowler
Martin Fowler
博客园 - 【当耐特】
B
Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
F
Full Disclosure
Google DeepMind News
Google DeepMind News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Help Net Security
Recorded Future
Recorded Future
N
News and Events Feed by Topic
雷峰网
雷峰网
V
Vulnerabilities – Threatpost
Schneier on Security
Schneier on Security
aimingoo的专栏
aimingoo的专栏
S
Schneier on Security
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
O
OpenAI News
Project Zero
Project Zero
罗磊的独立博客
G
GRAHAM CLULEY
腾讯CDC
P
Privacy International News Feed
V
V2EX
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Hugging Face - Blog
Hugging Face - Blog
爱范儿
爱范儿
H
Heimdal Security Blog
L
LINUX DO - 热门话题
Forbes - Security
Forbes - Security
美团技术团队
MongoDB | Blog
MongoDB | Blog
Security Latest
Security Latest
M
MIT News - Artificial intelligence
T
Tor Project blog
Cisco Talos Blog
Cisco Talos Blog
宝玉的分享
宝玉的分享
T
Threat Research - Cisco Blogs
TaoSecurity Blog
TaoSecurity Blog

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
3 Ways to Check if a Variable is Defined in JavaScript
Dmitri Pavlutin · 2020-11-17 · via Dmitri Pavlutin Blog

From time to time you have to check whether a variable is defined in JavaScript. For example, to determine if an external script has been successfully loaded into the web page, or to determine if the browser supports a Web API (IntersectionObserver, Intl).

How to check if a variable is defined in JavaScript? The answer is not straightforward, so let's find out!

1. The states of a variable

Before jumping into specific techniques, I'd like to have an agreement on the related terms.

In the following 2 sections, let's make clear what it means for a variable to be "defined"/"not defined" and "initialized"/"uninitialized".

1.1 Defined / not defined variable

A variable is defined when it has been declared in the current scope using a declaration statement.

The usual way to declarate variables is const, let and var statements, plus the function and class declaration statements.

Examples of defined variables:


const pi = 3.14; // pi is defined

let result; // result is defined

window.message = 'Hello';

message; // message is defined


Contrary, a variable is not defined when it hasn't been declared in the current scope using a declaration statement.

Examples of not defined variables:


pi; // pi is not defined, throws ReferenceError

result; // result is not defined, throws ReferenceError

if (true) {

// result is defined, but in this block scope

let result;

}


The scope sets the limits where the variable is defined and accessible. A scope in JavaScript is defined by a code block (for const and let variables) and by a function body (for const, let, var).

Accessing a variable that's not defined throws a ReferenceError:


// pi is not defined

pi; // throws ReferenceError


1.2 Initialized / uninitialized variable

A variable is initialized when the declared variable has been assigned with an initial value.

Examples of initialized variables:


const pi = 3.14; // pi is initialized

let result;

result = 'Value'; // result is initialized


On the other side, a variable is uninitialized when the declared variable has not been assigned with an initial value.

Examples of uninitialized variables:


let result; // result is uninitialized

var sum; // sum is uninitialized


The value of an uninitialized variable is always undefined:


let result; // result is uninitialized

result; // => undefined


2. Using typeof

Knowing the possible states of variables, let's consider the techniques to find whether a variable is defined or not.

The typeof operator determines the variable's type. typeof myVar can evaluate to one of the values: 'boolean', 'number', 'string', 'symbol', 'object', 'function' and 'undefined'.

The expression typeof missingVar doesn't throw a ReferenceError if the missingVar is not defined, contrary to simple access of the not defined variable:


// missingVar is not defined

typeof missingVar; // Doesn't throw ReferenceError

missingVar; // Throws ReferenceError


That's great because you can use the expression typeof myVar === 'undefined' to determine if the variable is not defined:


if (typeof myVar === 'undefined') {

// myVar is (not defined) OR (defined AND unitialized)

} else {

// myVar is defined AND initialized

}


Be aware that typeof myVar === 'undefined' evaluates to true when myVar is not defined, but also when defined and uninitialized. All because accessing a defined but uninitialized variable evaluates to undefined.


// missingVar is not defined

typeof missingVar === 'undefined'; // => true

// myVar is defined and unininitialized

let myVar;

typeof myVar === 'undefined'; // => true


Usually, that's not a problem. When you check if the variable is defined, you want it initialized with a payload too.

Of course, if the variable is defined and has a value, typeof myVar === 'undefined' evaluates to false:


const myVar = 42;

typeof myVar === 'undefined'; // => false


3. Using try/catch

When accessing a not defined variable, JavaScript throws a reference error:


// missingVar is not defined

missingVar; // throws "ReferenceError: missingVar is not defined"


So... what about wrapping the checked variable in a try block, and try to catch the reference error? If the error is caught, that would mean that the variable is not defined:


// missingVar is not defined

try {

missingVar;

console.log('missingVar is defined')

} catch(e) {

e; // => ReferenceError

console.log('missingVar is not defined');

}

// logs 'missingVar is not defined'


missingVar in the above example is not defined. When trying to access the variable in a try block, a ReferenceError error is thrown and catch block catches this reference error. That's another way to check the variable's existence.

Of course, if the variable is defined, no reference error is thrown:


// missingVar is defined

let existingVar;

try {

existingVar;

console.log('existingVar is defined')

} catch(e) {

console.log('existingVar is not defined');

}

// logs 'existingVar is defined'


Compared to typeof approach, the try/catch is more precise because it determines solely if the variable is not defined, despite being initialized or uninitialized.

4. Using window.hasOwnProperty()

Finally, to check for the existence of global variables, you can go with a simpler approach.

Each global variable is stored as a property on the global object (window in a browser environment, global in NodeJS). You can use this idea to determine if the global variable myGlobalVar is defined: simply check the global object for corresponding property existence: window.hasOwnProperty('myGlobalVar').

For example, here's how to check if the browser defines an IntersectionObserver variable:


if (window.hasOwnProperty('IntersectionObserver')) {

// The browser provides IntersectionObserver

} else {

// The browser doesn't support IntersectionObserver

}


var variables and function declarations, when used in the outermost scope (aka global scope), do create properties on the global object:


// Outermost scope

var num = 19;

function greet() {

return 'Hello!';

}

window.hasOwnProperty('num'); // => true

window.hasOwnProperty('greet'); // => true


However, be aware that const and let variables, as well as class declarations, do not create properties on the global object:


// Outermost scope

const pi = 3.14;

let message = 'Hi!';

class MyClass {}

window.hasOwnProperty('pi'); // => false

window.hasOwnProperty('message'); // => false

window.hasOwnProperty('MyClass'); // => false


5. Summary

In JavaScript, a variable can be either defined or not defined, as well as initialized or uninitialized.

typeof myVar === 'undefined' evaluates to true if myVar is not defined, but also defined and uninitialized. That's a quick way to determine if a variable is defined.

Another approach is to wrap the variable in a try { myVar } block, then catch the possible reference error in a catch(e) { } block. If you've caught a ReferenceError, then the variable is not defined.

Finally, to check the existence of a global variable myGlobalVar invoke window.hasOwnProperty('myGlobalVar'). This approach is useful to check if the browser supports a Web API.

What is your preferred way to check if a variable is defined?