Functions

Default values

With ES6 we can now pass through default values for variables.

function (x = 12, y = 22) {
   console.log(x,y);
}

You can now also do Default Fault Expressions

function bar(val) {
   return val;
}
 
function foo(x = 12 + 3, y = bar(12), z = ()=>{ return 22 }) {
   console.log(x,y); // 15, 12
}
 
bar(1); // 1
foo(); // 15, 12

Callbacks

function bar(val) {
   return val;
}
 
function foo(
  x = 12 + 3, 
  y = bar(12), 
  z = (function(val) { return val  })(10), // ES5
  p = ((val)=>{ return val  })(5)) { // ES6
  console.log(x,y,z,p); // 15, 12, 10
}
 
bar(1); // 1
foo(); // 15, 12, 10, 5
 
// Simple callback example : 1
function ajax(url, fnCallback) {
  // Do some stuff
  fnCallback(url);
}
 
function message() {
  console.log('Ajax call done');
}
 
ajax('http://www.google.com', message); // 'ajax call done'
 
// Simple callback example: 2
function doAJax(
  url, fnCallback = ()=> {
   addUrl(url);
   message('Callback triggered');
   return true;
  }) {
  return fnCallback();
}
 
function addUrl(url) {
  console.log('Url added to the database');
}
 
var ajax = doAJax('http://www.google.com');
console.log(ajax);
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License