Photo by Kaitlyn Baker on Unsplash
"๐ก๐๐น๐น ๐ฎ๐ป๐ฑ ๐จ๐ป๐ฑ๐ฒ๐ณ๐ถ๐ป๐ฒ๐ฑ ๐ถ๐ป ๐๐ฎ๐๐ฎ๐ฆ๐ฐ๐ฟ๐ถ๐ฝ๐: ๐ง๐ต๐ฒ ๐๐ถ๐ป๐ฒ ๐๐ถ๐ป๐ฒ ๐๐ฒ๐๐๐ฒ๐ฒ๐ป ๐ง๐ต๐ฒ๐บ"
๐ก๐๐น๐น ๐ฎ๐ป๐ฑ ๐จ๐ป๐ฑ๐ฒ๐ณ๐ถ๐ป๐ฒ๐ฑ ๐ถ๐ป ๐๐ฎ๐๐ฎ๐ฆ๐ฐ๐ฟ๐ถ๐ฝ๐
๐ ๐ช๐ต๐ฎ๐ ๐ถ๐ ๐ก๐๐น๐น?
We have heard the word "null" many times in English. Its literal meaning is having no value. The same meaning is analogous to the meaning of null in programming.
Null in JavaScript is a specific value that represents the intentional absence of any object value. When we assign null as a value to a variable, it means that the variable is intentionally empty or blank. This is different from undefined, which represents the absence of any value, including both object and primitive values.
Although typeof null returns "object", null is actually a primitive value type in JavaScript, like undefined, boolean, number, string, and symbol.
var x = null;
Here we have assigned the value null to variable x.
โ
๐ช๐ต๐ฎ๐ ๐ถ๐ ๐จ๐ป๐ฑ๐ฒ๐ณ๐ถ๐ป๐ฒ๐ฑ?
As the name suggests, undefined means "not defined". So if we declare a variable but do not assign a value to it, the variable becomes undefined.
Unlike null, the value of an undefined variable is set by JavaScript as undefined. The variable gets created at run-time. When we do not pass an argument for a function parameter, the default value is taken as undefined. Additionally, when a function doesn't return a value, it returns undefined.
var x;
console.log(typeof(x)); // undefined
Here we have declared variable x and then checked its type. During run-time, undefined gets assigned to the variable x.
In JavaScript, null and undefined are both used to represent the absence of a value. However, they have slightly different behaviors when used in arithmetic operations.
When null is used in arithmetic operations, it gets converted to the number 0. This is because the ๐๐ผ๐ก๐๐บ๐ฏ๐ฒ๐ฟ() function is called on null, which converts it to 0. Therefore, any arithmetic operation performed on null will result in 0.
On the other hand, when undefined is used in arithmetic operations, it gets converted to NaN (Not a Number). This is because ๐๐ผ๐ก๐๐บ๐ฏ๐ฒ๐ฟ() function called on undefined converts it to NaN.
var length = 19;
var breadth;
var area = length*breadth;
console.log(area); // NaN
var length2 = 19;
var breadth2 = null;
var area2 = length2 * breadth2;
console.log(area2); // 0
The variable 'breadth' is undefined, so when we try to calculate the area of the rectangle, the result is NaN. On the other hand, the variable 'breadth2' is null, so when we try to calculate the area of the rectangle, the result is 0.
Understanding the difference between null and undefined is important in writing bug-free and efficient code.
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.