Functions as Value in JavaScript

Before reading this article, you may want to go through the following articles:

JavaScript Functions:

  1. Can be defined
  2. Can be invoked

Apart from this, JavaScript functions can be treated as values as well. JavaScript functions act as values. They can be:

  1. Assigned to a variable
  2. Set as a property of an Object
  3. Passed as argument to other function
  4. Returned from a function
  5. and so on...

Let us say there is a function as below:

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

You can assign this function to a variable as in the following:

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

You can assign a function as an Object property also. This can be done as in the following:

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

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

Up Next
    Ebook Download
    View all
    Learn
    View all