passing function as arguments - Javascript Function

Javascript examples for Function:Function Argument

Description

passing function as arguments

Demo Code

var years = [1990, 1986, 1980, 2000, 1970];
function calculateAge(el) {
  return 2017 - el; //return is required to avoid the undefined value!!!
}

function arrayCalc(arr, fn) {
  var arrRes = [];
  for(var i = 0; i < arr.length; i++) {
    arrRes.push(fn(arr[i]));//from  w  w w .  j a v  a  2s . co  m
  }
  return arrRes;
}

//let do other functions
function isFullAge(limit, el) {
  return el >= limit;
}

function masHeartRate(el) {
  if (el >= 18 && el <= 81) {
    return Math.round(206.9 - (0.67 * el));
  }else {
    return -1;
  }
}


var ages = arrayCalc(years, calculateAge); //callback function wich is called later
var fullJapan = arrayCalc(ages, isFullAge.bind(this, 20)); //=> define the first argument wich will be the same 
var rates = arrayCalc(ages, masHeartRate);
console.log(ages);
console.log(fullJapan);
console.log(rates);

Related Tutorials