What is different between undefined and null in Java Script

Noah - Jul 10 - - Dev Community

I introduce that what is different between undefined and null because it is difficult to describe it exactly.

Understanding the Difference between undefined and null

In many programming languages, there is usually one way to represent "no value," such as null.
However, in JavaScript, there are two ways to represent "no value": null and undefined. This can be surprising and confusing for people coming to JavaScript from other languages.

💡Basics

null

null doesn't occur unless programmer Intentionally uses it.

undefined

On the other hand, undefined occurs naturally, even if you don't use it explicitly.

For example, if you declare a variable and it has no initial value, JavaScript will assign undefined to it.

let test;
console.log(test);
// → undefined
Enter fullscreen mode Exit fullscreen mode

When accessing the property that doesn't exist in a object or the element that is not in array, it will automatically became undefined.

const object = {};
console.log(object.foo);
// → undefined

const array = [];
console.log(array[0]);
// → undefined
Enter fullscreen mode Exit fullscreen mode

🔍JSON

undefined

When you use undefined for the value of an object's property and then convert that object to JSON using JSON.stringify, the property is removed from the JSON output.

console.log(JSON.stringify({ name: undefined }));
// → {}
Enter fullscreen mode Exit fullscreen mode

null

On the other hand, when the value of property is null, it will retained .

console.log(JSON.stringify({ name: null }));
// → {"name": null}
Enter fullscreen mode Exit fullscreen mode

👀Conclusion

It is easier to unify with undefined because undefined occurs naturally everywhere.

Happy Coding☀️

. . . . .