Null and undefined are both are primitive data types in JavaScript. Both provides the similar feelings when observed at theoretical level. Sometime times the consequence are more debugging and clarification for the usage of these two values.
Null
The primitive type null is use as value indicating absence of value intentionally. You can assign null to a variable, ensuring it is declared and initialised, but does does not point to any object or value currently. It is a way of reseting value for a variable, once it becomes unnecessary.
const something = null;
console.log("Value for initSomething is ", something);
/* Output: Initial value of something is null */
Undefined
undefined is primitive value that is mimic the absence of object value without any explicit intention. In JavaScript it is implicitly assigned when variable declared but represents the uninitialised state. The usage for undefined can be seen mostly with hoisted declaration, like trying to access variables way before declaration.
Some case when JavaScript use undefined to assign as a value
- Declaration of uninitialised variable
//declartaion of a variable without a value
var something;
console.log("Something is ",something);
/* Output: Something is undefined */
- Accessing property of object that does not exist
const someObj={};
console.log("Value of property 'pattern' in someObj is ", someObj.name);
/* Output:Value of property 'pattern' in someObj is undefined*/
- Fetching array element based on undefined index
const arr = ['a', 'b','c','d'];
console.log("5th element of array is ",arr[5]);
/* Output: 5th element of array is undefined*/
- Absence of parameters supply for function
const someMethod = function(param){
console.log("value for param is ",param);
};
//call someMethod without supply of defined parameters
someMethod();
/* Output: value for param is is undefined */
- For a function with a return value that is not explicitly defined
//returning value without any explicit definition.
const someMethod = ()=>{
return;
};
console.log("return value for someMethod is ",someMethod());
/* Output: return value for someMethod is undefined */
Differences
undefined is assigned to value by default by JavaScript, whereas null is never assigned as value implicitly.
typeof(undefined) provides undefined, whereas typeof(null) gives object
In numerical context undefined results as NaN, whereas null results as 0(zero)
console.log(5 * null)// Output: 0
console.log(5 * undefined)// Output: NaN
- undefined and null are treated equal when compare with "==" due to type-coercion quality with JavaScript, but finds difference when compared strictly(using "===")
console.log( undefined === null ) // Output: false
Similarities
Despite the differences , it is found that undefined and null are being used alternatively by developers, because of following commonalities there share:
Both represents the absence of value
Both being primitive values, are not considered as objects, hence do not have dedicated function or attributes. Exceptional case in the context of data type of null returning object due to historic error.
In boolean context, both are resolves as false
undefined and null are loosely equal to each other or themselves only, but not equal to other false value such as 0(zero), NaN or empty string.
var someVar;
console.log(someVar==null); // Output: true
console.log(someVar==undefined); // Output: true
console.log(someVar==0); // Output: false
console.log(someVar==NaN); // Output: false
console.log(someVar==""); // Output: false
console.log(someVar==''); // Output: false
Decide usage between undefined and null
Avoid using undefined to initialise variable, and use null instead to hold absence deal explicitly. This will help developers for clarity on declaration and avoid confusion
When checking for absence deal, check to both undefined and null must be considered. Loose equality(\==null) can be used to compare a variable holding null or undefined in a code.
Use of loose equality checking for undeclared variable, will throw a RefrenceError. In this case we can use typeof function to compare the datatype and identify whether it is declared or not, declare with or without initialisation.
References
https://www.shecodes.io/athena/2227-what-is-the-difference-between-null-and-undefined-in-javascript
https://www.udacity.com/blog/2023/04/hoisting-in-javascript.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError
Conclusion
In summary, null and undefined serve distinct purposes in JavaScript. While null represents an intentional absence of value, undefined indicates a value that hasn't been defined or doesn't exist. Understanding these differences empowers developers to write cleaner, more reliable code, handling possibility of run time errors.
I hope this blog will be helpful in understanding the difference between null and undefined and will serve as guide to contribute on code clarity and avoiding confusions beforehand.
Please feel free to provide feedback ๐. I will try my best to generate such blog in future as well ๐ค.