๐ ๐๐ก๐ ๐๐ฎ๐ซ๐ข๐จ๐ฎ๐ฌ ๐๐๐ฌ๐ ๐จ๐ "๐๐ง๐๐๐๐ข๐ง๐๐" ๐ข๐ง ๐๐๐ฏ๐๐๐๐ซ๐ข๐ฉ๐ญ
๐ 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.
Let's connect on LinkedIn. I'd love to connect :)
Top comments (0)