user17938748
user17938748

Reputation: 1

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

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?

Upvotes: 0

Views: 172

Answers (2)

varaprasadh
varaprasadh

Reputation: 505

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));

Upvotes: 1

Eduard
Eduard

Reputation: 1374

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));

Upvotes: 1

Related Questions