📗 𝐓𝐡𝐞 𝐂𝐮𝐫𝐢𝐨𝐮𝐬 𝐂𝐚𝐬𝐞 𝐨𝐟 “𝐔𝐧𝐝𝐞𝐟𝐢𝐧𝐞𝐝” 𝐢𝐧 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭
👉 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 🙂