Introduction
In this article we will learn what is the difference between null and undefined in javascript. When this problem occurs in our program and how to overcome from this null and undefined issue in javascript.
Previous Updates
In previous articles we have learnt Why every business needed digital Marketing ,Transaction Commit and Rollback in sql server with example.What is Lock and how to achieve lock on sql table. Authorization in Asp.Net. How high quality content affects your Website. What is Blocking and Deadlock In SQL. Top 30 Asp.net interview question
Many times when we thinking about null value handling in javascript , we often get confused between null and undefined and what is the difference between these.
Undefined in JavaScript
Undefined means a variable is declared but has not yet been assigned any value. or value of the variable is not defined. JavaScript has a global variable undefined whose value is "undefined" and typeof undefined is also "undefined".
If a variable in javascript is not initialized then javascript assigned undefined value to it.
Just keep in mind that undefined is not a Keyword or Constant, undefined is a type itself (undefined).
When undefined error displayed
1. A declared variable without assigning any value to it.
2. Implicit returns of functions due to missing return statements.
3. return statements that do not explicitly return anything.
4. Lookups of non-existent properties in an object.
5. Function parameters that have not passed.
6. Anything that has been set to the value of undefined.
7. Any expression in the form of void(expression)
8. The value of the global variable undefined
var myVar;
alert(myVar); //Will shows
undefined
alert(typeof myVar); //Will shows
undefined
|
Null in JavaScript
Null is an assignment value means null can assign any variable to display as no value on that variable.null is a primitive value and you can assign null to any variable. null is not an object, it is a primitive value. Null is an object.
Just like undefined javascript never set default value as null on any variable. It is must be done programmatically.
var myVar = null; //we assigned null is an assignment value
alert(myVar); //Will shows null
alert(typeof myVar); //Will shows object
|
Now it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.
You can even compare a variable that is undefined to null or vice versa, and the condition will be true:
undefined == null
null == undefined
|
0 comments:
Post a Comment