DEV Community is a community of 785,073 amazing developers

We're a place where coders share, stay up-to-date and grow their careers. Roshan kumar

Posted on • Updated on

Create function in JavaScript that's takes single arguments and return sum of all previous arguments without using global variable.

Here we always try to find short and smart 🏆 code for doing same task.

First we try to do this task with simple approach then move forward.

When we create diagram in mind first we think to take an global variable that store data for you, But that's always a bad idea for smart 😎 developer.

function calc() {
// creating private valriable
let value = 0;
// private function
function changeBy(val) {
value += val;
}
// returning an object
return {
changeBy(i);
},
// return value
value: function () {
return value;
}
}
}

// making mycalc function with calc
let mycalc = calc()

// print to console
console.log(mycalc.value())

// output is 27

Here we seem like we have long code, and also we don't have es-6 smart features, so let's begin 🎉.

let calc = () => {
// creating private valriable
let value = 0;
// private function
let changeBy = val => value += val;
// returning an object
return {
// return value
value: () => value
}
}

// making mycalc function with calc
let mycalc = calc()

// print to console
console.log(mycalc.value())

// still output is 27 but with smart code.

Now if see code, that's pretty short.

let calc = () => {
let value = 0;
let changeVal = val => (value += val);
return {
}
}

But a thing is noticeable why we use private function 😋 let's remove it.

let calc = () => {
let value = 0;
return {
add: i => value += i
}
}

We removed many lined of code to making simpler, but still we have an issue with that code. We need a function that's take arguments every time and return sum of all previous and current arguments. But when use our function we feel like we using any class methods and it's properties, let's solve this issue.

• To solving this issue we need to wrap calc function in () parenthesis, and change the name of function calc to sum and call that's function in sum function 😝.
• And replace object with function in return statement.
let sum = (
i => {
let v = i;
return i => v += i
}
)(0);

Here we change many things like we don't return a object return value only, Zero is starting value of sum function.

let sum = (i => { let v = i; return i => v += i })(0);

console.log(sum(14)) /* output --> 14 */
console.log(sum(13)) /* output --> 27 */
console.log(sum(10)) /* output --> 37 */

final result

let sum = (a => b => a += b )(0)

😁😁😁🎉

Discussion (1) 