Functions as Value in JavaScript

JavaScript Functions

  • Can be defined
  • Can be invoked

Apart from this JavaScript function can be treated as value as well. JavaScript functions act as Value. They can

  • JavaScript function can be assigned to a variable
  • JavaScript function can set as property of an Object
  • JavaScript function can be passed as argument to other function
  • JavaScript function can be returned from function etc…

Let us say there is function as below,


function FindGrade(e) {

if (e > 60)
 return "Grade A"
 else
 return "Grade B"
 }

You can assign this function to a variable,


var abc = FindGrade;
 var result1 = FindGrade(20);
 alert(result1);
 var result2 = abc(70);
 alert(result2);

You can assign function as Object property also. This can be done as following,


var obj =
 {
 grade : FindGrade
 }
 var result = obj.grade(70);
 alert(result);

 

You see that above we assigned a JavaScript function as Object’s Property. You can use JavaScript function as argument of another function etc. I hope you find this post useful. Thanks for reading.

Published by

Dhananjay Kumar

Dhananjay Kumar is Developer Evangelist for Infragistics. He is a 8 times Microsoft MVP and well respected Developer Advocate in India.He is the author of 900+ Blog Posts, and can often be found speaking around India at conferences and hosting free workshops for programmers across the country. So far, he has hosted 60 free workshops on various topics like JavaScript, Angular, WCF, ASP.NET MVC, C#, Azure etc. Follow him on twitter @debug_mode for all the updates about his blog posts and workshops. You can send him email at debugmode [at] outlook [dot] com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s