Labanino Labanino - 8 days ago 7
Javascript Question

Two different results using console.log and return

I've been playing with chapter 3, Parameters and Scopes of Eloquent Javascript and I understand the difference between

console.log
and
return
but what I don't understand is why the developer tools console gives me two different results:
inside f1
and
"inside f1"




var x = "outside";
var f1 = function() {
var x = "inside f1";
console.log(x);
};
f1(); // inside f1







var x = "outside";
var f1 = function() {
var x = "inside f1";
return x;
};
f1(); // "inside f1"




Answer

console.log and return do entirely different things.

console.log takes a value and shows it on the console. return stops a function running and (optionally) sends a value back to the calling context. console.log does not exit the function.

Let's explore both options.

var x = "outside";
var f1 = function() {
  var x = "inside f1";
  console.log(x);
};
f1(); // inside f1

Here, console.log simply outputs the value of x to the console. This involves no formatting and no other modification. The function f1 does not return anything at all (there is an implicit return; at the end of the function).

Now let's look at the other bit of code:

var x = "outside";
var f1 = function() {
  var x = "inside f1";
  return x;
};
f1(); // "inside f1"

Here, the function f1 has a return value, because you used the return statement. So f1 returns a string inside f1. Because you are calling f1 from the console, the console outputs the return value of the function to the console. If other code called f1 (e.g. elsewhere in your application) there would be no output on the console.

The reason it is in "" quotation marks is that the console, for reasons known only to the developers, opts to show string values in this way.

Comments