Advance part in Functions

  • Functions are special type of Objects

Function stored in Object

  • Function as Methods
  • Function stored in an object termed as Methods
const person = {
  age: 20
  greet: function greet(){
    console.log('Methods')
  }
}
person.greet()
const todo = {
  // way1
  add: function(){
    console.log('Add todo..');
  },
  //way2
  edit(id){   
    console.log(`Edit todo ${id}`);
  }
}
// way 3
todo.delete = function(){
  console.log('Delete todo...');
}

todo.add();
todo.edit(22);
todo.delete();

Argument and Parameter in JS function

  • Can pass any no. of argumenst
  • But, accepts only no. of parameters defined
function sum(a, b) {  
  return a + b;
}
// adds only first 2
console.log(sum(1, 2, 3, 4, 5));
// 1+2=3

Rest Operator(Parameters)

  • Accepts any no of parameters
// args is the name for the array
function sumAll(...args) {
  let sum = 0;
  for (let arg of args) sum += arg;
  return sum;
}
console.log(sumAll(1)); 
// 1
console.log(sumAll(1, 2)); 
// 3
function sumAll(a, b, ...args) {
  let sum = a + b;
  for (let arg of args) sum += arg;
  return sum;
}
console.log(sumAll(1, 2, 1, 1));
  • Old way(before Rest operator), not recomende now
const sumAll = function() {
  let sum = 0;
  // arguments stores all the params
  for (let arg of arguments) sum += arg;
  return sum;
}
console.log(sumAll(1, 2, 1, 1));

Default Arguments

function sum(a, b=2) {  
  return a + b;
}
console.log(sum(1);
// 1+2=3

Callback Function

const sumUp = (resultHandler, ...numbers) =>{
  let sum = 0;
  for (let arg of numbers) sum += arg;
  resultHandler(sum)
}

const showResult = (result) =>{
  console.log("Result:" + result)
}

sumUp(showResult, 1,2,3);
// "Result:6"

bind methods

  • Binds is used in callback function
  • Without executing the function we can set this and certain parameters that are known now.
// Without callback
const module = {
  x: 42,
  getX: function(a) {
    console.log(this.x, a);
  }
};
module.getX(10)
// 40 10
  • With callback, without bind function
const module = {
  x: 42,
  getX: function(a) {
    console.log(this.x, a);
  }
};

const unboundGetX = module.getX
unboundGetX(10)
// undefined 10
  • With callback and bind function
  • The argument in unboundGetX(20) will be the last parameter for the function
const module = {
  x: 42,
  getX: function(a,b) {
    console.log(this.x, a, b);
  }
};

const unboundGetX = module.getX.bind(module, 10)
unboundGetX(20)
// 42 10 20

apply() and call()

Indirect vs Direct Function Execution

function add() {
  something = someNum + someOtherNum;
}
  • Two ways of executing a function:
    • add() vs add
  • add()
    • Execute fxn immediately
    • This is how you execute a function from your code.
  • add
    • Don’t execute fxn immediately
    • someButton.addEventListener(‘click’, add);
      • when the button is clicked, go ahead and execute add fxn.