0

function foo() {
  console.log('always');
  return 'once'
}

foo()
foo()
foo()

The output looks like - always always always once

I want to know what happens during execution so that "always" is printed thrice but "once" is printed (returned) only once.

Rakesh
  • 1
  • 1
  • 4
    Your function is returning a string and you're not doing anything with it. – Triby Jun 01 '20 at 20:02
  • 1
    Just do `foo(); 'repl result'` instead to understand what's going on. – Bergi Jun 01 '20 at 20:02
  • 1
    Also see https://stackoverflow.com/questions/14633968/chrome-firefox-console-log-always-appends-a-line-saying-undefined – Bergi Jun 01 '20 at 20:03

1 Answers1

4

The reason is JS console always evaluates the last expression and prints its output to the console. In reality, your foo() function is returning a value in all 3 calls. It is your last call of foo() that gets printed to the console. To see this yourself, append another expression to the end of your code:

function foo(){
  console.log('always');
  return 'once'
}

foo()
foo()
foo()
a = 42

This time your output would be

always
always
always
42