Monday, 21 January 2019

Functions in JavaScript

Functions in Javascript behaves pretty much the same way as they do in other languages.  Consider a simple example of a function:

 let cube = function(number) {  
   return number * number * number;  
 }  
 let result = cube(4);  
 console.log(result);  

It gives 64 as output.

Undefined and Null Values:



Before moving to advance features of functions in Javascript, we need to understand what are these Undefined and Null Values in Javascript.
Consider a code snippet:

 let name;  
 console.log(name);  

It prints "undefined" in the console. Actually, Undefined is used to represent the absence of a value in Javascript. Hence, when we don't assign any value to a variable declared in javascript, "undefined" is set implicitly for us.

Consider one more example where Javascript sets "undefined"  implicitly for us:

 let test = function(num) {  
   console.log(num);  
 };  
 test();   

Again, as expected, Javascript assigns "undefined" to num variable implicitly for us and hence it produces "undefined" for us.

Now, Consider one last example where Javascript implicitly assigns "undefined" for us:

 let test = function(num) {  
   console.log(num);  
 };  
 let result = test();  
 console.log(result);  

It Produces This Output:

 undefined  
 undefined  

To understand the use of "null" in Javascript, consider the following example:

 let age = 27;  
 age = undefined;  
 console.log(age);  
 let name;  
 console.log(name);  
 let gender = null;  
 console.log(gender);  

It produces the output:

 undefined  
 undefined  
 null  

As it is very clear from the above example, Javascript outputs undefined for both of the first two cases and hence we pretty much lose the context between Javascript setting undefined implicitly for us and US assigning it explicitly. Here, null comes to rescue.

So, to have "undefined" functionality explicitly, use null. That's it.


Default Argument in Javascript Functions:

Default Arguments are great if you want a single function to be used with a different number of arguments being passed.
Consider the following code snippet to understand more:
 let getScore = function(name = 'ABC', age = 18) {  
   console.log(name);  
   console.log(age);  
 }  
 console.log('Calling Get Score with no arguments......');  
 getScore();  
 console.log('Calling Get Score with one argument......');  
 getScore('Ayush');  
 console.log('Calling Get Score with two arguments......');  
 getScore('Ayush', 13);  


It Produces the Output:

 Calling Get Score with no arguments......  
 ABC  
 18  
 Calling Get Score with one argument......  
 Ayush  
 18  
 Calling Get Score with two arguments......  
 Ayush  
 13  


As you can see, Javascript enables the function to use default arguments in case the calling statement doesn't pass some of its arguments.

If you have any doubts, write down in comments so that we can discuss that further.
Thanks!

No comments:

Post a comment