Solve - Alert is not Defined Error in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Sereja Ris

Solve - Alert is not Defined Error in JavaScript #

The "ReferenceError: alert is not defined" occurs when the alert() method is used outside of the browser environment, most commonly in Node.js. The alert method is a method on the window object, which is only available in the browser.

referenceerror alert is not defined

To solve the "alert is not defined" error, use the console.log or console.error methods instead of alert when outside the browser. The console.log and console.error methods allow us to output a message to the web console or standard output and error if you're on the server side.

index.js
console.log('hello'); console.error('an error occurred');

If you're getting the error in a browser, you might be using server side rendering (e.g. with Next.js), or you might have misspelled alert (all lowercase).

index.js
alert('hello');

If you're getting the error when using server side rendering, you can conditionally check if you're on the browser (can use alert) or you are on the server (can't use alert).

index.js
if (typeof window !== 'undefined') { console.log('You are on the browser') // ๐Ÿ‘‰๏ธ can use alert() } else { console.log('You are on the server') // ๐Ÿ‘‰๏ธ can't use alert() }

In our if statement, we check if the window global variable is not undefined. If it is defined, we can use the alert method.

The alert method is defined on the window object in the browser.
index.js
console.log(alert === window.alert); // ๐Ÿ‘‰๏ธ true

If you check whether alert is equal to window.alert in a browser environment, we get a true value back.

The window global variable represents the window that contains the DOM document (browser side only).

An easy way to think about it is - in a browser, each tab is represented by its own Window object.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee