Fun with Functions : The JavaScript Way – Part 3

This is in continuation to the series about functions. And we have lot more to discuss about functions. So let’s get started.

8. Functions are Objects

In JavaScript functions are treated same as objects. Just like any other objects it has properties and additional properties can be added to the function.

const sayHello = function(name){
    console.log('Hello ' + name);
}

console.log(typeof sayHello);
console.log(sayHello);
sayHello.age = 25;
console.log(sayHello.name);

In the above code snippet we have a function call sayHello which console logs a string. Now if we see the typeof the function we will get function. If we try to print the function itself in the console log we can see the function definition. Also we can attach properties like age and do a console log of that as well. Interesting isn’t it?

Now let us see some properties of function object. See the below code snippet.

const greetPeople = (timeOfDay) => {
    greetPeople.counter++;
    function greet(name){
        return 'Good ' + timeOfDay + ' ' + name;
    }
    return greet;
}

greetPeople.counter = 0;
const greetMorning = greetPeople('Morning');
const greetEvening = greetPeople('Evening');

let functionName = greetMorning.name;
console.log(functionName);

let functionLenghtOfArgument = greetMorning.length;
console.log(functionLenghtOfArgument);

let functionCounter = greetPeople.counter
console.log(functionCounter);

We have a simple function called greetPeople which takes an argument timeOfDay i.e.., “Morning” or “Evening”. Now inside it there is another method which takes a name and console logs a greeting message to the name. Also if you see there is a counter property associated in the main function which increments on every time we call the function. The property is initialized with zero.

The first thing we have done is created two constants called greetMorning and greetEvening. Now we know that greetMorning and greetEvening will hold the function which is returned by the greetPeople method. Now let us see some properties. First there is a name property called greetMorning.name which will give us the name of the inner function in this case, which is greet. Second, there is a property called length with has the number of arguments that is passed to the parameter. Third, there is a counter property which is incremented every time we call the function. Just try the same code and log it into your console and comment below what values you find for each property.

9. Methods : Functions inside Objects

Now we will start looking into objects. Any function that is part of an object is called a method. Consider the below code snippet.

let student = {
    name: 'Jeremy',
    marks: [80, 90, 87, 71, 88],
    calculateAvg : function() {
        let sum = 0, i;
        for(i = 0; i < this.marks.length; i++){
            sum += this.marks[i];
        }
        return sum / this.marks.length;
    }
}

result = student.calculateAvg();
console.log(result);

Here we are creating a student object which has name, marks and a function or method calculateAverage of the marks. To call the calculageAverage we use the student object with a dot notation to call the function then we store and display the result.

Now there is one interesting thing we can do to the student object. We can bind an external function to the student object using the bind method of a function. See the code below.

function showName(){
    console.log(this.name);
}
let newStudent = showName.bind(student);
newStudent(); // call to the new function

First we have created a new function called showName which displays the name of the student in the console. Then we bind the function using the new function name dot bind and then pass the object to which we want it to bind to. Then store the return in a variable called new student which is a function. Then we call newStudent which displays the student name. Is it complicated ,simple, tell me in comment section.

10. Functions as Class

In JavaScript, strangely though, we use the function to create instance of classes. Usually here we use first letter as caps in function name. We pass arguments to the function which works as constructor and initializes values. And obviously we can have functions inside the class, which we now call as method. See the below code snippet.

function Employee(name, age, salary){
    this.name = name;
    this.age = age;
    this.salary = salary;
    this.showDetail = function(){
        console.log(`${name} is ${age} years old`);
    }
}

const Peter = new Employee('Peter', 44, 5000);
Peter.showDetail();

const Marshal = new Employee('Marshal', 30, 1000);
Marshal.showDetail();

We created a class called Employee and passed name, age, salary. We initialized the class members with these arguments. Next we create two objects called Peter and Marshal using the new keyword and passed the name, age and salary values. Then we call showDetail method using the object name with dot notation to call the function which displays the respective employee details.

Now there is an interesting concept of prototype which is available in functions through which we can add new functionality to the class. See the below code snippet.

function showSalary(){
    console.log(this.salary);
}

Employee.prototype.showSalary = showSalary;

Marshal.showSalary();

Here first we created a function called showSalary. Then using the prototype of the Employee class we attach the showSalary function. Now showSalary is part of the Employee class just like showDetail. And then we used the object to call the showSalary method to show the respective salary.

I hope you all liked the three part series on JavaScript function. If you like it consider subscribing and leave a comment. Have a great day !

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 )

Connecting to %s

%d bloggers like this: