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

A function in Javascript:
- A piece of code to execute small task or operations
- The function is an instance of an object type
- So the Function almost behaves like other objects
- Any Function can be assigned to variables
- We can pass one function to another function as an argument
- We can return a function from a function
- The function can be defined with the keyword function
- Then followed by function name with parenthesis
- Arguments can be passed in parenthesis
- Then followed by open and closed curly braces.
- 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.