An Interest In:
Web News this Week
- April 28, 2024
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
"Undefined" in javascript: Amazing Cases.
""
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 theglobal object. That is, it is a variable in global scope.
JavaScript uses theundefinedvalue in the following situations.
1)
When we declare avariableand dont 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-existingproperty of an object, well getundefined.
For example:
let person = {name: "Sachin",};console.log(person.age); // undefined
In this example, theperson object has one property"name". Accessing the"age" property that doesnt exist on the"person" object returnsundefined.
3)
when we call thefunction and dont pass all the arguments, the parameters inside the function becomeundefined.
For example:
const calculation = (a, b ) => {return b === 7 ? ${ a } : ${ a} ${ b };}calculation(3); // 3 undefined
4)
A function that doesnt have areturnstatement implicitly returnsundefined.
For example:
function myFunc() {// Do something but don't return a value}console.log(myFunc()); // Output: undefined
5) --
When we access anarrayelement that is out-of-bounds, we'll get theundefinedvalue.
For example:
const colors = ['red', 'green', 'blue'];console.log(colors[3]); // undefined`
Theundefinedis a primitive type that has a single valueundefined.
Accessing an uninitialized variable returnsundefined.
Accessing a non-existing property of an object returnsundefined.
Accessing an out-of-bounds array element returnsundefined.
A function without areturnstatement or with areturnstatement but without an expression returnsundefined.
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 :)
Original Link: https://dev.to/sachink07/undefined-in-javascript-amazing-cases-4gk9
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To