× back

Functions

Function definition

                   
// normally
var a = 10;
var b = 20; 
var sum = a + b;
console.log(sum);

// using function 
function sum(){
var a = 10, b = 40;
var total = a + b;
console.log(total);
}
                   
               

Calling a function

                            
function sum(){
    var a = 10, b = 40;
    var total = a + b;
    console.log(total);
}
sum(); // function call
                   
               

Function Parameter vs Function Arguments

                   
function sum(a, b){
var total = a + b;
console.log(total);
}
sum(40, 60);
sum(20, 30);
                   
               

Interview Question

  • Why function?
    • You can reuse code: Define the code once, and use it many times.
    • You can use the same code many times with different arguments, to produce different results.
    • A function is a group of reusable code which can be called anywhiere in your program. This eliminates the need of writing the same code again and again.
  • DRY → Do not repeat yourself.

Function expressions

                        
function sum(a, b){
    var total = a + b;
    console.log(total);
}
var funExp = sum(5, 15);
                   
               

Return Keyword

                       
function sum(a, b){
return a + b;
}
var funExp = sum(5, 25);
                   
               

Anonymous Function

                   
var funExp = function(a, b){
return a + b;
}
var sum = funExp(15, 15);
var sum1 = funExp(20, 15);
console.log(sum > sum1);