- Function is represented as Object in Javascript
- Has 2 phases – Function Definition and Function Execution
- Two ways of defining function
Function Declaration / Named Function – Function object would get created at scope creation phase
Function Expression / Anonymous Function – Function object would get created at execution phase – Interepreter would throw error incase the function is called before anonymous definition.010203040506070809101112//Named Function
displayAge();
function
displayAge(){
console.log(
'My Age is 33'
)
}
//Anonymous Function
var
age =
function
(){
//Context/scope execution phase
console.log(
'My Age is 33'
)
}
age();
- No concept of function overloading. Function with near matching argument would be called.In the below code getSum has 2 arguments but still it gets called.
1234
function
getSum(num1, num2) {
console.log(
'Function overloading is not possible'
);
}
getSum();
Function overloading is not possible
- Function namespace context would be created with the samename as the function namespace
- In the below code the getLunch appears to be overloaded but there would be only one namespace in context with name getLunch
- So you may expect the output to be different but all the times getLunch(buffey, paid) would be called in below code
0102030405060708091011121314
function
getLunch() {
console.log(
'Free Lunch'
);
}
function
getLunch(paidLunch) {
console.log(
'paidLunch'
);
}
function
getLunch(buffey, paid) {
console.log(
'paidLunch buffey'
);
}
getLunch();
getLunch(5);
getLunch(5,10);
Output
paidLunch buffey paidLunch buffey paidLunch buffey
- So what would be the workaround. Check the code as below
0102030405060708091011121314
function
getLunch() {
if
(arguments.length === 0)
console.log(
'Free Lunch'
);
if
(arguments.length === 1)
console.log(
'paidLunch'
);
if
(arguments.length === 2)
console.log(
'paidLunch buffey'
);
}
getLunch();
getLunch(5);
getLunch(5,10);
Output
Free Lunch paidLunch paidLunch buffey
- Using Restparameter feature from ECMAScript6
1234567
function
getLunch(bill, space, ...menu) {
console.log(bill);
console.log(space);
console.log(menu);
}
getLunch(150,
'Open Terrace'
,
'idly'
,
'dosa'
,
'vada'
);
Output
150 Open Terrace ["idly", "dosa", "vada"]