Site icon Kaizen.Personal computer work.

undefined(JavaScript Variable data type)

Japanese version.

undefined is a special value in JavaScript that indicates that a variable has not been initialized or a value has not been explicitly set. In some JavaScript environments, accessing an undefined variable or function will also return undefined.

For example, consider the following code:

let myVar;
console.log(myVar); // undefined

function myFunc() {
  // Do nothing
}

console.log(myFunc()); // undefined

In this code, a variable named myVar is declared but not assigned an initial value, so its value is undefined. The myFunc function returns nothing, so calling it also returns undefined.

undefined is also a data type in JavaScript. The undefined data type is returned when you reference a variable or object property that has a value of undefined. Accessing a variable or object property that has not been defined will result in an error.

Here are some examples of undefined:

let myVar;
console.log(typeof myVar); // "undefined"

let myObj = { prop: undefined };
console.log(myObj.prop); // undefined

console.log(myNonExistentVar); // ReferenceError: myNonExistentVar is not defined

These examples show that myVar is of the undefined data type, that myObj.prop has a value of undefined, and that accessing an undefined variable myNonExistentVar results in an error.

Difference between undefined and null

undefined and null are special values in JavaScript that indicate the absence of a value, but they have slightly different uses.

undefined is used when a variable is declared but not initialized or a value has not been explicitly set. It is also returned when you reference an undefined variable.

On the other hand, null is used to indicate the absence of an object. It can be assigned to variables and properties to explicitly indicate that they have no value.

In JavaScript, undefined and null are considered equal when using the equality operator ==, but not when using the strict equality operator ===.

Here is an example that illustrates the difference between undefined and null:

let myVar1;
let myVar2 = null;

console.log(myVar1); // undefined
console.log(myVar2); // null

console.log(myVar1 == myVar2); // true
console.log(myVar1 === myVar2); // false

In this example, myVar1 is uninitialized and therefore has a value of undefined. myVar2 has been explicitly assigned a value of null. Comparing myVar1 and myVar2 with the equality operator == returns true, but using the strict equality operator === returns false.

Links

JavaScript Articles

JavaScript
Exit mobile version