Variable not defined javascript

ReferenceError: «x» is not defined

The JavaScript exception «variable is not defined» occurs when there is a non-existent variable referenced somewhere.

Message

ReferenceError: "x" is not defined (V8-based & Firefox) ReferenceError: Can't find variable: x (Safari) 

Error type

What went wrong?

There is a non-existent variable referenced somewhere. This variable needs to be declared, or you need to make sure it is available in your current script or scope.

Note: When loading a library (such as jQuery), make sure it is loaded before you access library variables, such as «$». Put the element that loads the library before your code that uses it.

Examples

Variable not declared

foo.substring(1); // ReferenceError: foo is not defined 

The «foo» variable isn’t defined anywhere. It needs to be some string, so that the String.prototype.substring() method will work.

const foo = 'bar'; foo.substring(1); // "ar" 

Wrong scope

A variable needs to be available in the current context of execution. Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function

function numbers( ) < const num1 = 2; const num2 = 3; return num1 + num2; > console.log(num1); // ReferenceError num1 is not defined. 

However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access all variables defined in the global scope.

const num1 = 2; const num2 = 3; function numbers( ) < return num1 + num2; > console.log(numbers()); // 5 

See also

Found a problem with this page?

Last modified: Aug 5, 2022 , by MDN contributors

Читайте также:  Global styles inline css
JavaScript

The JavaScript exception «is not constructor» occurs when there was an attempt use object variable but that There was an attempt to use object or variable

The JavaScript exception «is not function» occurs when there was an attempt to call value from but actually It attempted to call value from function, but

The JavaScript exception «precision out of range» occurs when number that’s outside 0 and 20 (or 21) was passed into toFixed toPrecision.

The JavaScript exception «Permission denied to access property» occurs when there was an attempt object for which you have no DOMException.

Источник

ReferenceError: «x» is not defined

The JavaScript exception «variable is not defined» occurs when there is a non-existent variable referenced somewhere.

Message

ReferenceError: "x" is not defined (V8-based & Firefox) ReferenceError: Can't find variable: x (Safari)

Error type

What went wrong?

There is a non-existent variable referenced somewhere. This variable needs to be declared, or you need to make sure it is available in your current script or scope.

Note: When loading a library (such as jQuery), make sure it is loaded before you access library variables, such as «$». Put the element that loads the library before your code that uses it.

Examples

Variable not declared

.substring(1); // ReferenceError: foo is not defined 

The «foo» variable isn’t defined anywhere. It needs to be some string, so that the String.prototype.substring() method will work.

const foo = "bar"; foo.substring(1); // "ar" 

Wrong scope

A variable needs to be available in the current context of execution. Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function

function numbers()  const num1 = 2; const num2 = 3; return num1 + num2; > console.log(num1); // ReferenceError num1 is not defined. 

However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access all variables defined in the global scope.

const num1 = 2; const num2 = 3; function numbers()  return num1 + num2; > console.log(numbers()); // 5 

See also

Found a content problem with this page?

This page was last modified on Jul 7, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

3 Ways to Check if a Variable is Defined in JavaScript

Post cover

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!

Before I go on, let me recommend something to you.

The path to becoming good at JavaScript isn’t easy. but fortunately with a good teacher you can shortcut.

Take «Modern JavaScript From The Beginning 2.0» course by Brad Traversy to become proficient in JavaScript in just a few weeks. Use the coupon code DMITRI and get your 20% discount!

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:

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:

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 :

1.2 Initialized / uninitialized variable

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

Examples of initialized variables:

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

Examples of uninitialized variables:

The value of an uninitialized variable is always undefined :

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:

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

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 .

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 :

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

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 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:

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:

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

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

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?

Like the post? Please share!

Dmitri Pavlutin

About Dmitri Pavlutin

Software developer and sometimes writer. My daily routine consists of (but not limited to) drinking coffee, coding, writing, overcoming boredom 😉. Living in the sunny Barcelona. 🇪🇸

Dmitri Pavlutin

About Dmitri Pavlutin

Software developer and sometimes writer. My daily routine consists of (but not limited to) drinking coffee, coding, writing, overcoming boredom 😉. Living in the sunny Barcelona. 🇪🇸

Источник

Explain the difference between undefined and not defined in JavaScript

In JavaScript, they both are related to memory space and there is a very simple difference between them. If the variable name which is being accessed doesn’t exist in memory space then it would be not defined, and if exists in memory space but hasn’t been assigned any value till now, then it would be undefined.

undefined: It is a JavaScript keyword that has a special meaning. Everything which gets a space in memory will contain undefined until we assign a value to that memory space.

Let’s understand how the JavaScript code is being executed to see a more clear picture. Everything in JavaScript happens inside the execution context. Execution context is the little separate section where code is being executed and variables get their memory space.
The JavaScript code is being executed in two-phase,

  1. The first one is the memory allocation phase during this all the variables and function definitions get stored inside the memory heap. The JavaScript assigns undefined to each variable in this phase.
  2. The second one is a thread of the execution phase, during this the code written inside the JavaScript file is being executed.
    Each variable holds the value undefined till the program reaches the line where we have assigned that variable. After that line, the variable’s undefined value gets replaced by the original value.

Example 1: The global execution context will be created and in the memory allocation phase, the var a will get space in memory, and JavaScript will assign undefined to it. During the thread of execution, the JavaScript will encounter the first line console.log(a) and as we haven’t assigned the value for a, undefined will be printed on the console. In the next line, we have assigned 5 to a, hence the variable a is no more undefined. Now it contains the value 5. So next time whenever we access the variable a, it won’t be evaluated as undefined. So it will print the actual value of a.

Источник

Оцените статью