Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

What is the function in javascript?

In this chapter, you will learn about what is the function in javascript.

What is function Javascript

A function in Javascript:

  1. A piece of code to execute small task or operations
  2. The function is an instance of an object type
  3. So the Function almost behaves like other objects 
  4. Any Function can be assigned to variables
  5. We can pass one function to another function as an argument
  6. We can return a function from a function
  7. The function can be defined with the keyword function
  8. Then followed by function name with parenthesis
  9. Arguments can be passed in parenthesis
  10. Then followed by open and closed curly braces.
  11. We can pass 0 or n number of arguments

Let’s create a small function that returns the employee name.

function fullName(firstName, lastName) {
    return firstName + ' '+ lastName;
}
console.log(fullName('John','Mickel'));

// output
// John Mickel

Now we will at look the point “we can pass one function to another function as an argument” and write an example for the same

function netPayable(salary, callBack) {
    var netPay = [];
    for (let i=0;i< salary.length;i++){
        netPay.push(callBack(salary[i]));
    }
    return netPay;
}

function getPayable(salary){
    return salary - 200;
}

var salaries = [30000,40000,50000,24000];
var payableSalaries = netPayable(salaries,getPayable);
console.log(payableSalaries);

// output 
// (4) [29800, 39800, 49800, 23800]

Now look at the point “we can return a function from a function” and write an example for the same

function getExamDate(student){
    if(student === 'be'){
        return function(name){
            console.log('Dear '+name + ' your exams will start on monday 10:30 AM...');
        }
    } else if (student === 'medical'){
        return function(name){
            console.log('Dear '+name + ' your exams will start on tuesday 10:30 AM...');
        }
    } else {
        console.log('Dear '+name + ' your exams will start on thursday 10:30 AM...');
    }

}

var beStudent = getExamDate('be');
beStudent('Stark');

var medicalStudent = getExamDate('medical');
medicalStudent('Mickel');

// output
// Dear Stark your exams will start on monday 10:30 AM...
// Dear Mickel your exams will start on tuesday 10:30 AM...

 

One thought on “What is function in javascript

Comments are closed.