JavaScriptmancy - ES6 - Functions - Multiple Parameters (Rest)
by vintharas
HTML
<a class="btn" target="_blank" href="https://babeljs.io/repl/#?experimental=true&evaluate=true&loose=false&spec=false&playground=false&code=%2F%2F%20Run%20on%20babeljs%20(https%3A%2F%2Fbabeljs.io%2Frepl%2F)%0A%2F%2F%20Taking%20a%20variable%20number%20of%20parameters%20in%20JavaScript%20in%20ES2015%20is%20easy%0Afunction%20obliterate(...victims)%7B%0A%20%20%20%20victims.forEach(function(victim)%7B%0A%20%20%20%20%20%20%20%20console.log(victim%20%2B%20%22%20wiped%20out%20of%20the%20face%20of%20the%20earth%22)%3B%0A%20%20%20%20%7D)%3B%0A%20%20%20%20console.log('*Everything*%20has%20been%20obliterated%2C%20oh%20great%20master%20of%20evil%20and%20deceit!')%3B%0A%7D%0A%0Aobliterate(%22John%20Doe%22%2C%20getPuppy()%2C%201%2C%20new%20Minion('Willy'%2C%20'troll'))%3B%0A%2F*%0A%3D%3E%20John%20Doe%20wiped%20out%20of%20the%20face%20of%20the%20earth%0A%3D%3E%20cute%20puppy%20wiped%20out%20of%20the%20face%20of%20the%20earth%0A%3D%3E%201%20wiped%20out%20of%20the%20face%20of%20the%20earth%0A%3D%3E%20Willy%20the%20troll%20wiped%20out%20of%20the%20face%20of%20the%20earth%0A%3D%3E%20*Everything*%20has%20been%20obliterated%2C%20oh%20great%20master%20of%20evil%20and%20deceit!%0A*%2F%0A%0Afunction%20getPuppy()%7B%0A%20%20%20%20return%20%7B%0A%20%20%20%20%20%20%20%20cuteWoof%3A%20function()%7Bconsole.log('wiii')%3B%7D%2C%0A%20%20%20%20%20%20%20%20toString%3A%20function()%7Breturn%20'cute%20puppy'%3B%7D%0A%20%20%20%20%7D%3B%0A%7D%3B%0A%0Afunction%20Minion(name%2C%20type)%7B%0A%20%20%20%20this.name%20%3D%20name%3B%0A%20%20%20%20this.type%20%3D%20type%3B%0A%20%20%20%20this.toString%20%3D%20function()%7B%20return%20name%20%2B%20%22%20the%20%22%20%2B%20type%3B%7D%3B%0A%7D%0A%20%20%20%20%20%20%20%20">Test on Babel.js</a>
CSS
a.btn {
display: inline-block;
padding: 6px;
background: #f5da55;
text-decoration: none;
color: black;
font: 1.5em sans-serif;
box-shadow: 2px 2px 1px grey;
}
JavaScript
// Run on babeljs (https://babeljs.io/repl/)
// Taking a variable number of parameters in JavaScript in ES2015 is easy
function obliterate(...victims){
victims.forEach(function(victim){
console.log(victim + " wiped out of the face of the earth");
});
console.log('*Everything* has been obliterated, oh great master of evil and deceit!');
}
obliterate("John Doe", getPuppy(), 1, new Minion('Willy', 'troll'));
/*
=> John Doe wiped out of the face of the earth
=> cute puppy wiped out of the face of the earth
=> 1 wiped out of the face of the earth
=> Willy the troll wiped out of the face of the earth
=> *Everything* has been obliterated, oh great master of evil and deceit!
*/
function getPuppy(){
return {
cuteWoof: function(){console.log('wiii');},
toString: function(){return 'cute puppy';}
};
};
function Minion(name, type){
this.name = name;
this.type = type;
this.toString = function(){ return name + " the " + type;};
}