"Undefined" in javascript : Amazing Cases

ยท

2 min read

๐Ÿ“— ๐“๐ก๐ž ๐‚๐ฎ๐ซ๐ข๐จ๐ฎ๐ฌ ๐‚๐š๐ฌ๐ž ๐จ๐Ÿ "๐”๐ง๐๐ž๐Ÿ๐ข๐ง๐ž๐" ๐ข๐ง ๐‰๐š๐ฏ๐š๐’๐œ๐ซ๐ข๐ฉ๐ญ

๐Ÿ‘‰ In JavaScript, "undefined" is a primitive data type that represents a value that is not assigned to a variable or a property. "undefined" is a property of the global object. That is, it is a variable in global scope.

JavaScript uses the undefined value in the following situations.

โœ… 1) ๐€๐œ๐œ๐ž๐ฌ๐ฌ๐ข๐ง๐  ๐š๐ง ๐ฎ๐ง๐ข๐ง๐ข๐ญ๐ข๐š๐ฅ๐ข๐ณ๐ž๐ ๐ฏ๐š๐ซ๐ข๐š๐›๐ฅ๐ž
When we declare a variable and donโ€™t initialize it to a value, the variable will have a value of ''undefined''.
For example:

let x;
console.log(x); // Output: undefined

โœ… 2) ๐€๐œ๐œ๐ž๐ฌ๐ฌ๐ข๐ง๐  ๐š ๐ง๐จ๐ง-๐ž๐ฑ๐ข๐ฌ๐ญ๐ข๐ง๐  ๐ฉ๐ซ๐จ๐ฉ๐ž๐ซ๐ญ๐ฒ ๐จ๐Ÿ ๐š๐ง ๐จ๐›๐ฃ๐ž๐œ๐ญ
If we access a non-existing property of an object, weโ€™ll get undefined.
For example:

let person = {
name: "Sachin",
};
console.log(person.age); // undefined

In this example, the person object has one property "name". Accessing the "age" property that doesnโ€™t exist on the "person" object returns undefined.

โœ… 3) ๐…๐ฎ๐ง๐œ๐ญ๐ข๐จ๐ง ๐ฉ๐š๐ซ๐š๐ฆ๐ž๐ญ๐ž๐ซ๐ฌ
when we call the function and donโ€™t pass all the arguments, the parameters inside the function become undefined.
For example:

const calculation = (a, b ) => {
  return b === 7 ? ${ a } : ${ a} ${ b };
}
calculation(3); // 3 undefined

โœ… 4) ๐…๐ฎ๐ง๐œ๐ญ๐ข๐จ๐ง๐ฌ ๐ซ๐ž๐ญ๐ฎ๐ซ๐ง ๐š ๐ฏ๐š๐ฅ๐ฎ๐ž
A function that doesnโ€™t have a return statement implicitly returns undefined.
For example:

function myFunc() {
// Do something but don't return a value
}
console.log(myFunc()); // Output: undefined

โœ… 5) ๐€๐œ๐œ๐ž๐ฌ๐ฌ๐ข๐ง๐  ๐จ๐ฎ๐ญ-๐จ๐Ÿ-๐›๐จ๐ฎ๐ง๐๐ฌ ๐š๐ซ๐ซ๐š๐ฒ ๐ž๐ฅ๐ž๐ฆ๐ž๐ง๐ญ๐ฌ
When we access an array element that is out-of-bounds, we'll get the undefined value.
For example:

const colors = ['red', 'green', 'blue'];
console.log(colors[3]); // undefined

๐Ÿ‘‰ ๐’๐ฎ๐ฆ๐ฆ๐š๐ซ๐ฒ
โœ… 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 an out-of-bounds array element returns undefined.
โœ… A function without a return statement or with a return statement but without an expression returns undefined.

That's all for today ๐Ÿ™‚

Thanks for reading it ๐Ÿ˜Š. I hope it was insightful and that we got to learn something new today. If you liked the post, please post likes ๐Ÿ‘ and share ๐Ÿค it in your circles. Share your feedback and comment away.

ย