Javascript what is undefined

JavaScript undefined

The undefined property indicates that a variable has not been assigned a value, or not declared at all.

Browser Support

undefined() is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

More Examples

Example

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

undefined

The undefined global property represents the primitive value undefined . It is one of JavaScript’s primitive types.

Try it

Value

Property attributes of undefined
Writable no
Enumerable no
Configurable no

Description

undefined is a property of the global object. That is, it is a variable in global scope.

In all non-legacy browsers, undefined is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it.

A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .

Note: While you can use undefined as an identifier (variable name) in any scope other than the global scope (because undefined is not a reserved word), doing so is a very bad idea that will make your code difficult to maintain and debug.

// DON'T DO THIS (() =>  const undefined = "foo"; console.log(undefined, typeof undefined); // foo string >)(); ((undefined) =>  console.log(undefined, typeof undefined); // foo string >)("foo"); 

Examples

Strict equality and undefined

You can use undefined and the strict equality and inequality operators to determine whether a variable has a value. In the following code, the variable x is not initialized, and the if statement evaluates to true.

let x; if (x === undefined)  // these statements execute > else  // these statements do not execute > 

Note: The strict equality operator (as opposed to the standard equality operator) must be used here, because x == undefined also checks whether x is null , while strict equality doesn’t. This is because null is not equivalent to undefined .

typeof operator and undefined

Alternatively, typeof can be used:

let x; if (typeof x === "undefined")  // these statements execute > 

One reason to use typeof is that it does not throw an error if the variable has not been declared.

// x has not been declared before // evaluates to true without errors if (typeof x === "undefined")  // these statements execute > // Throws a ReferenceError if (x === undefined)  > 

However, there is another alternative. JavaScript is a statically scoped language, so knowing if a variable is declared can be read by seeing whether it is declared in an enclosing context.

The global scope is bound to the global object, so checking the existence of a variable in the global context can be done by checking the existence of a property on the global object, using the in operator, for instance:

if ("x" in window)  // These statements execute only if x is defined globally > 

void operator and undefined

The void operator is a third alternative.

let x; if (x === void 0)  // these statements execute > // y has not been declared before if (y === void 0)  // throws Uncaught ReferenceError: y is not defined > 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 28, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

JavaScript undefined

Summary: in this tutorial, you’ll learn about the JavaScript undefined and how to handle it effectively.

If you have been working with other programming languages such as Java or C#, you may find that these languages have the null value.

JavaScript also has the null value. In addition, it has the undefined value. And both null and undefined values represent empty values in JavaScript.

What is undefined

The undefined is a primitive type in JavaScript. So the undefined is a type. And the undefined type has exactly one value that is undefined .

JavaScript uses the undefined value in the following situations.

1) Accessing an uninitialized variable

When you declare a variable and don’t initialize it to a value, the variable will have a value of undefined. For example:

let counter; console.log(counter); // undefinedCode language: JavaScript (javascript)

It’s a good practice to always initialize a variable whenever possible. In this example, you can initialize the counter variable to zero, like this:

let counter = 0; console.log(counter); // 0Code language: JavaScript (javascript)

2) Accessing a non-existing property of an object

If you access a non-existing property of an object, you’ll get undefined . For example:

let counter = < current: 0 >; console.log(counter.max); // undefinedCode language: JavaScript (javascript)

In this example, the counter object has one property current . Accessing the max property that doesn’t exist on the counter object returns undefined .

It’s good practice to check if the property exists before accessing it. JavaScript provides you with some ways to do so.

And the most common way to verify whether the object has a property is to use the in operator:

'propertyName' in objectNameCode language: JavaScript (javascript)

Note that you need to surround the property name of the object with single or double-quotes.

The following example uses the in operator to check if the max property exists on the counter object before accessing it:

let counter = < current: 0 >; if('max' in counter) < console.log(counter.max); >Code language: JavaScript (javascript)

If you want to assign a default value when the property of an object doesn’t exist, you can use the nullish coalescing operator ( ?? ):

const propValue = object.propName ?? defaultValue;Code language: JavaScript (javascript)

In this syntax, the nullish coalesing operator ( ?? ) returns the defaultValue if the object.propName is undefined or null .

Note that the nullish coalescing operator has been available since ECMAScript 2020.

let counter = < current: 0 >; const max = counter.max ?? 100;Code language: JavaScript (javascript)

3) Function parameters

When you call a function with a number of parameters, you often pass the same number of arguments. For example:

const formatCurrency = (amount, currency) => < return currency === '$' ? `$$ `: `$ $ `; > Code language: JavaScript (javascript)

The formatCurrency() function has two parameters. When calling it, you can pass two arguments like this:

formatCurrency(100,'$'); // $100Code language: JavaScript (javascript)

And it returned $100 as expected.

But when you call the formatCurrency() function and don’t pass all the arguments, the parameters inside the function becomes undefined . For example:

formatCurrency(100); // 100 undefinedCode language: JavaScript (javascript)

To avoid this situation, you can set a default value for the function parameters like this:

const formatCurrency = (amount, currency = '$') => < return currency === '$' ? `$$ `: `$ $ `; >Code language: JavaScript (javascript)

And when calling it without passing the second argument, you’ll get a proper value:

formatCurrency(100); // $100Code language: JavaScript (javascript)

4) Functions return a value

A function that doesn’t have a return statement implicitly returns undefined . For example:

const log = (message) => < const time = (new Date()).toLocaleTimeString(); console.log(`$ : $ `); >; const result = log('Hi'); console.log(result); // undefinedCode language: JavaScript (javascript)

Likewise, when a function has a return statement without an expression, it also returns undefined . For example:

const add = (a,b) => < const result = a + b; return; > let result = add(10,20); console.log(result); // undefinedCode language: JavaScript (javascript)

Consider the following example:

const add = (a,b) => < return a + b; >; let result = add(10,20); console.log(result); // undefinedCode language: JavaScript (javascript)

The add() function returns undefined . It should have returned 30 instead.

The problem is that when you create a new line between the return keyword and the returned expression ( a + b ), Javascript compiler automatically inserts a semicolon (;) before the new line. This feature is called automatic semicolon insertion (ASI) in JavaScript.

The add() function will look like the following to the JavaScript compiler:

const add = (a,b) => < return; a + b; >;Code language: JavaScript (javascript)

That’s why you get the undefined as the return result.

5) Accessing out-of-bounds array elements

When you access an array element that is out-of-bounds, you’ll get the undefined value. For example:

const colors = ['red', 'green', 'blue']; console.log(colors[3]); // undefinedCode language: JavaScript (javascript)

In this example, the colors array doesn’t have any element at index 3. Therefore, the colors[3] returns undefined .

Summary

  • The undefined is a primitive type that has a single value undefined .
  • Accessing an uninitialized variable returns undefined .
  • Accessing a non-existing property of an object returns undefined .
  • Accessing a out-of-bounds array element returns undefined .
  • A function without a return statement or with a return statement but without an expression returns undefined .

Источник

Читайте также:  Layout css visited links enabled
Оцените статью