Setting default parameter to a function in javascript

by  
Share:
Setting default parameter to a function in javascript

Default parameters in function comes handy for developers in cases where most of the time a certain parameter value is used.

Let’s take an example of displaying a statement with function. We will first create a function name mobile that takes two parameter viz. os (operating system like Android or IOS  ) and memory (Inbuilt or Expandable).

A normal function with two parameter for displaying the statement based on those parameter  is given below.

<script>
function mobile(os, memory ) {
alert("This phone has "+os +" Operating System with "+memory +" Memory feature." );
}

// 
// Prints: This phone has Android Operating System with Expandable Memory feature.
mobile("Android", "Expandable");

// Prints: This phone has IOS Operating System with Inbuilt Memory feature.
mobile("IOS", "Inbuilt");

</script>

Now let’s assume that the mobile has a default Inbuilt memory. So now we have to set the memory default value (default parameter) as Inbuilt.
<script>
/*
os can be Android or IOS
memory can be Inbuilt or Expandable. 
if memory parameter is not provided the Inbuilt will be used
*/
function mobile(os, memory ) {
  memory = (typeof memory === 'undefined') ? 'Inbuilt' : memory;
  alert("This phone has "+os +" Operating System with "+memory +" Memory feature." );
}

// Prints: This phone has Android Operating System with Inbuilt Memory feature.
mobile("Android");
</script>

Some parts of the code has been taken from here.

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.