Undefined in JavaScript

0
5

Undefined is a type of Data type in JavaScript. When a variable is declared and not initialized or not assigned with any value. By default, the variable was stored with an Undefined value. 

Undefined is a global read-only variable that represents the value Undefined. Undefined is a type of primitive type

Syntax:

let variable = undefined;
// or
let no; 

Both no and variable contain an undefined value.

1. Undefined Value in variables: When a variable is declared or not initialized but not assigned with any value then JavaScript automatically assigns it to an “undefined” value.

Example: In the below example, the variable name is declared but not assigned with any value, so it gets an Undefined value:

Javascript




let newVar;
console.log(newVar)


Output:

undefined

2. Undefined Value using Functions: A method or statement also returns undefined. If a variable was assigned with a function that does not return any value, then the JavaScript assigns an undefined value to that variable.

Example: In the below example sayhi() function actually outputs and returns nothing. In the above, we assigned the sayhi function to the x variable, so we get an Undefined value in the x variable as the sayhi() function returns nothing.

Javascript




function sayhi(name) {
    console.log(`hi ${name}`);
}
x = sayhi('hike');
console.log(`value in x= ${x}`);


Output:

hi hike
value in x=undefined
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

LEAVE A REPLY

Please enter your comment!
Please enter your name here