Edabit: Return the sum of two numbers
// from the 'Very Easy' page:
simple_sum = (a,b)=>{return a+b};
Now let's take it up one notch by returning a new function that hard-codedly adds the two arguments.
This is just for fun to explore some more of JavaScript.
function make_adder(a,b){
var fnStr = "function adder(){return " + a + " + " + b + "}";
window.eval(fnStr);
try{
console.log('Using created function, ' + a + ' + ' + b + ' = ' + window['adder']());
}catch{
console.log('failed to call function');
}
}
make_adder(1,2) // expecting 3
make_adder(1,20) // 21
make_adder(13,17) // 30
make_adder(99,1) // 100
interestingly, just eval(fnStr) doesn't work ( i guess because of the function's scope?), but window.eval(fnStr) works as expected.
No comments:
Post a Comment