Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 13, 2020 04:01 pm GMT

Wait... Undefined or Not defined or Null?

Some of the simplest concepts in JavaScript can be a little tricky to make sense of. One of these is the difference between undefined, not defined and null

Let's start with the easy one

Undefined:

There are certain cases when undefined value is returned in javascript such as:

1) Whenever we declare a variable without assigning any value to it, javascript implicitly assigns its value as undefined.

let name;console.log(name); //undefined

2) When a value is not assigned in an array or object.

let numArray = [1,2,,4];console.log(numArray);  //[1, 2, , 4]typeof(numArray[2])//"undefined"

3) When functions dont have a return statement but are called for assigning a value to a variable.

let add = (a,b) => {  let c = a+b;// no return statement}let sum = add(2,3);console.log(sum); //Output: undefined

In the code block above, since we commented the return statement, the value of variable sum is given as undefined in the output.

Not defined:

A not defined variable is one which has not been declared at a given point of time with a keyword like var, let or const.

console.log(a);var a = 5;//Output:- undefined

While if we dont use the var declaration, the above the output will look like this:

console.log(b);b = 5;//Output:- "ReferenceError: b is not defined

Null:

nullis a reserved keyword in javascript. We can assign a null value to a variable explicitly using this keyword. null essentially represents a non-existent or an empty value i.e. we explicitly tell the JavaScript interpreter that the variable has no value.

let life = null;console.log(life); //null

Original Link: https://dev.to/zakariaelk/undefined-vs-not-defined-vs-null-185g

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To