TIL Rest Parameters
POSTED ON:
TAGS: javascript gotchas
You don't know how many params the function may use.
function add(...theArgs) {
// return param1 + param2;
let total = 0;
for (let arg of theArgs) {
total = total + parseInt(arg);
}
//foreach version
theArgs.forEach(argument => {
total += argument;
})
return total;
}
I originally used a for..in
instead of a for..of
.
The difference:
for..in
iterates over all enumerable property keys of an objectfor..of
iterates over the values of an iterable object.
Another way would be to use a foreach loop.
TEST SUITE (using Jasmine):
describe('add()', () => {
it('adds two numbers', () => {
// arrange
const num1 = 1;
const num2 = 2;
// act
const result = add(num1, num2);
// log
console.log("result: ", result);
// assert
expect(result).toBe(3);
});
//remove x to add it as the testing suite
xit('adds any ammount of numbers', () => {
// arrange
const num1 = 1;
const num2 = 2;
const num3 = 3
// act
const result = add(num1, num2, num3);
// log
console.log("result: ", result);
// assert
expect(result).toBe(6);
});
});
Related TILs
Tagged: javascript