Add

Add

Adding two or more numbers(array of numbers ).

Example:
console.log(add(1,2,3,4,5)); 15
console.log(add(2,3)); 5

function add(...param1){
	let total = 0;
	param1.forEach(num => {
		total += num;
		});
		return total;
}

console.log(add(1,2,3,4,5)); 15
console.log(add(2,3)); 5

We create a function add with parameter using spread that can be as many as possible parameters named …param1 and local variable total = 0

Spread syntax (…) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected. MDN

param1.forEach(num => { total +=num }) We take the parameter we chain the forEach loop and inside the forEach we have parameter num and num is current number so total += num

Finally we return total

comments powered by Disqus