Home > other >  Javascript - Why does a function work on the last call only?
Javascript - Why does a function work on the last call only?

Time:01-15

Just started learning how to code. The first lesson taught how functions are used. For the below add function, whenever I call the function more than once, the output is displayed only for the last one. Does a function have to be written separately for each time I call?

function add(first, second) {
  return first   second;
}

add(1,2);
add(7,9);
add(3,5);

Output: 8

How can I get an output to all three?

CodePudding user response:

Your add function returns the computation, it does not print anything. So once you call it, all the work will be done and returned, and if you want to see what is returned, all you need is to console them in order to appear in the developer panel

function add(first, second) {
  return first   second;
}

console.log(add(1,2)); // <- HERE
console.log(add(7,9);
console.log(add(3,5));

CodePudding user response:

i think you are trying this on developer console. if you run this code as a file, you even doesn't get any output.

The developer console typically logs out the output from the codeblock. once the execution is done.

use console.log() in order to see all outputs.


console.log(add(1,2));
console.log(add(7,9));
console.log(add(3,5));

CodePudding user response:

Above answers are correct, but if you need to get the sum of all values you need to put everything into another function which returns its values.

function add(first, second) {
 return first   second;
}

add(1,2);
add(7,9);
add(3,5);

function sum() {
 const sum = add(1,2)   add(7,9)   add(3,5);

 return sum;
};

console.log(sum())
  •  Tags:  
  • Related