Most of us would have come across the JS data types
null. But we don't know the real difference between both of them. Let's start with
undefined type is an object, which represents that the declaration of the variable done, but it is not assigned. This comes under the
undefined, as its name suggests. This is literally lack of value for the variable.
null is a value assigned to a variable. Unlike
undefined it's not the lack of value, as we know that
null by itself is a value.
null is voluntary absence of the value for the variable.
The below picture clearly explains the difference.
We'll see how they compare with each other in the below gist, where we use a simple conditional statement to know how
Note: Line numbers referred as L below.
Here, we only get to run L4 and L8 in our code. Which means that the variable
a is not assigned a value and thus gives
undefined, whereas variable
b is assigned the value of
null which make the L8 to execute.
You can also use this JSFiddle https://jsfiddle.net/Vishwa_R/ha8tqL69/5/ for execution.
Let's see a simple example, let us take the operation of reading a file and displaying its size. Here we have two functions to perform, they are,
- Reading a file.
- Displaying size.
This must be done in sequence, we cannot display the size first without reading the file. Scenarios like this, make Callback functions “HEROES”.
We'll see an example where we mimic the above operation (we are not going to actually read a file and display the size). Let us take a look at the below gist.
So here in this example, we have two functions, namely
sizefinder. As per our sequence of execution, we want
Readfile to be first executed, So, we call the
sizefinder inside the
Readfile function as an argument. Finally, we can asynchronously do two functions using callbacks. This makes Callback functions to be widely used.
You can also use this JSFiddle https://jsfiddle.net/Vishwa_R/hce58f39/9/ to have a look at execution.
Thanks for reading and give a 💖 if you liked the content, have some feedbacks? Put them down in the comments. Have a great time😄🎉