Function is a block of statements to execute a particular task.
Functions are building blocks of any programming language.
The fundamental purpose of the function is – take some input, use inputs and do some particular task/calculation and return the output.
Every time function returns the same output for the same input. Output differs according to input values.
Once the function is defined, as far as it is in the scope it can be called any number of time. It reduces the size of the file and increases the readability of the code.
Function declaration/definition
Syntax
function functName(para1, para2,...) {
// function body
}
Function is declared or defined using function keyword followed by function name, followed by any number of parameters ( separated by comma and enclosed in parenthesis) followed by function body in a curly braces.
Functions may or may not return any value. There is a very little use of the functions which do not return anything as they do not solve the main purpose of the functions – return different output for different inputs.
To use the function in a program we need to call (or invoke) it. The () operator is used to call the function.
Calling the function
functName(arg1, arg2, ...)
Function is called by just writing function name followed by arguments in parenthesis.
Note: Arguments are the values passed in function at the time of invoking/calling it. Parameters are passed during the declaring (defining) function.
Example
function findMax(a, b) {
if(a > b) return a
else return b
}
let max = findMax(100, 200)
console.log(max) // 200
Note: JavaScript functions are objects. The function name is just a pointer to that function object. To invoke the function we need to write function name followed by parenthesis.
Function expression
JavaScript functions can be defined as function expression too.
Syntax
let functName = function(arg1, arg2, ...) { // statements }
Note that there is no function name after function keyword as it is not required.
If you want to call the same function inside the function (recursion), you need to give name.
Example
// find the sum of the numbers from 1 to given number
let sum = function recSum(n) {
if(n <= 1) return n
else return n + recSum(n - 1)
}
console.log(sum(10)) // 55
The above function returns the sum of all the numbers starting from 1 to n. The function expression is given name so it can recall the same function until it reaches to if condition.
Function constructor
It is another way to define a function which takes any number of arguments but the last argument is considered as a function body.
Syntax
let max = new Function('a', 'b', 'if(a>b) return a; else return b;')
console.log(max(55, 10)) // 55
This syntax is not recommended because it causes double interpretation. Security problem is another important thing to consider while using this syntax.
Difference between function declaration and function expression
Example
console.log(mul(5, 10)) // 50
function mul(a, b) {
return a * b
}
In the above code function is called before declaration, still it works properly. JavaScript hoists the declaration at the top of the scope. The declaration is added to the execution context before the code begins running. But the same thing is not true with function expression.
Example
console.log(mul(5, 10))
let mul = function (a, b) {
return a * b
}
output:
Uncaught ReferenceError: mul is not defined
This code causes an error because the function is a part of initialization statement not part of a function declaration. So the function is not available until the line let mul = function(a, b) is executed.
Function name as a pointer to the function
JavaScript functions are objects and function names are only pointers to the function.
Example
function add(a, b) {
return a + b
}
let anotherFunction = add
console.log(anotherFunction(10, 20)) // 30
add = null
console.log(anotherFunction(30, 40)) // 70
The above code has a function called add which adds two numbers.
When the function is assigned to another variable without parenthesis, they both points to the same function. If the add function is assigned to null, just that pointer points to null but the anotherFucntion still points to the same function and returns result properly.
Functions as variables
JavaScript function names are mostly same as variables.
The function can be passed in other function as an argument.
The fucntion can return another function.
Let’s see an example converting number to an array.
Example
function convert(num) {
return Array.from(''+num, Number)
}
function f(someFunct, n) {
return convert(n)
}
let resultArr = f(convert, 458)
console.log(resultArr) // [4, 5, 8]
Function properties and methods
Function properties
Functions are objects therefore each function has two properties: length and prototype.
The length property returns the number of arguments that function expects.
Example
function mul(a, b) {
return a * b
}
function sayHi() {
console.log('Hello there!')
}
console.log(mul.length) // 2
console.log(sayHi.length) //0
The prototype property is very important. Methods such as toString() and valueOf() exists on the prototype and can be accessed from the object instances.
If you want to define your own reference type, this property is very useful. Inheritance is possible through prototype property.
It is not enumerable and so will not be found using for-in.
Functions have methods like apply(), call() and bind().
The methods apply() and call() both call function with a specific this value.
The apply() method accepts two arguments: the value of this inside the function and array of arguments.
Note: arguments object is also allows as a second argument in apply() method.
Example
function mul(a, b) {
return a * b
}
function appMul1(n1, n2) {
return mul.apply(this, [n1, n2])
}
function appMul2(num1, num2) {
return mul.apply(this, arguments)
}
console.log(appMul1(5, 6)) //30
console.log(appMul2(10, 20)) //200
In the above example this points to the window object. The appMul1 uses array as the second argument while appMul2 uses arguments object. Both functions return the result properly.
call() function does the same thing but the arguments passed to it differently.
The first argument is this value but the second argument is not an array but direct arguments.
We will see the same example as above.
Example
function mul(a, b) {
return a * b
}
function callMul1(n1, n2) {
return mul.call(this, n1, n2)
}
console.log(callMul1(2, 4)) // 8
There is no specific rule for using apply() over call() or vice versa. If passing an array is an easiest, you can use apply or else use call.
If there is no second argument to pass, then both are identical.
The true power of call() and apply() lies on the value of this. Let’s see an example:
Example
window.name = 'Mary'
let person = {
name: 'John'
}
function sayHi(name) {
return "Hello "+ this.name
}
console.log(sayHi.apply(this)) // Hello Mary
console.log(sayHi.apply(person)) // Hello John
The function sayHi is defined as a global function and when is called in the global scope, this points to window.name. When this points to person object it uses this.name as a person.name.
The bind() method creates a new function instance whose this value is bound to the value that was passed into bind().
Example
window.name = 'Mary'
let person = {
name: 'John'
}
function sayHi(name) {
return "Hello "+ this.name
}
let bindSayHi = sayHi.bind(person)
console.log(bindSayHi()) //Hello John
The other methods like toLocaleString() and toString() returns the function’s code.
Summary
- Function is a king in JavaScript.
- Functions are objects and function name is the pointer to the function.
- Function can be declared using declaration method, function expression method or function constructor method.
- Functions too have properties and methods.
- Function can be passed as a parameter in another function as well as function can return another function.