zaagan
7/1/2019 - 3:25 PM

JavaScript Function

JavaScript Function

// ******** Basic ********
function functionName(param1, param2, ...) {
  // code to be executed
} 


// ******** Function Expression ********
var x = function (a, b) { return a * b };
var z = x(4, 3); 


// ******** Function Constructor ********
var multi = new Function("a", "b", "return a * b");
var x = multi(4, 3); 


/* Hoisting : moving declarations to the
   top of the current scope
   i.e Functions can be called before 
   they are declared */
myFunction(5);
function myFunction(y) {
  return y * y;
} 


/* Self Invoking function
i.e Will invoke without being called */
(function () {
  var x = "Hello !!";
})();


// ******** Arrow functions ********
// ES5
var x = function(x, y) { return x * y;}
// ES6
const x = (x, y) => x * y;


// ******** ES6 Default parameters  ********
 var x = function (a=1, b=1) 
 { /* function code */ } 
 
 
 // ******** Arguments Object ********
 x = findMax(1, 123, 500, 115, 44, 88);
function findMax() {
  var i;
  var max = -Infinity;
  for (i = 0; i < arguments.length; i++) {
    if (arguments[i] > max) {
      max = arguments[i];
    }
  }
  return max;
}


// ******** Function as methods ********
var myObject = {
  firstName:"John",
  lastName: "Doe",
  fullName: function () {
    return this.firstName + " " + this.lastName;
  }
}
myObject.fullName();  
// Output : "John Doe" 
 

/* ******** Invoke Function with
   Function Constructor ******** */
function myFunction(arg1, arg2) {
  this.firstName = arg1;
  this.lastName  = arg2;
}
var x = new myFunction("John", "Doe");
x.firstName; 
// Output : John


/* ******** call() & apply() method
 call() method takes arguments separately
 apply() method takes arguments as an array
******** */
var person = {
  fullName: function(city, country) {
    return this.firstName + " " + this.lastName
      + "," + city + "," + country;
  }
}
var person1 = { firstName:"John", lastName: "Doe" }
var person2 = { firstName:"Mary", lastName: "Doe" }

person.fullName.call(person1, "Oslo", "Norway");  
// Output : John Doe,Oslo,Norway

person.fullName.apply(person2, ["Oslo", "Norway"]);
// Output : Mary Doe,Oslo,Norway


/* ******** Closures
  Make variables private ******** */ 
var add = (function () {
  var counter = 0;
  return function () {counter += 1; return counter}
})();
add();
add();
add();
// counter value is now 3