-2

I'm new to JavaScript so sorry for the amateur question but I feel as through the answer would help to make more sense of the course material, and assignments, in my online course. Here it is. When I write console.log like this:

var getKeys = function(objOne){
  for(var property in objOne){
    console.log(property);
  }
};

console returns: "name" "age"

...but if I change console.log to "return", like this:

var getKeys = function(objOne){
  for(var property in objOne){
    return property;
  }
};

output returns: "name"

Why are the returns different?

  • I copied and pasted your code into the console, and I receive the exact same output. – Richard Kho Jul 15 '15 at 01:14
  • Because as soon as you `return` - you return. – zerkms Jul 15 '15 at 01:15
  • Because after a `return` you’re no longer in the function, so the loop is interrupted as well. – Sebastian Simon Jul 15 '15 at 01:16
  • Oh OK. That sorta makes sense. The console.log is just showing me the possible outcome of the function but if I want to return all Keys of an Object, I need to figure out how to compile each index of the loop and pass it to the return statement? – Jeffrey Nixon Jul 15 '15 at 01:36

5 Answers5

1

Because return exits the function. You exit the function on the first property, hence why it is only one.

MDN return

The return statement ends function execution and specifies a value to be returned to the function caller.

epascarello
  • 204,599
  • 20
  • 195
  • 236
0

According to the spec, (emphasis mine)

A return statement causes a function to cease execution and return a value to the caller.

So your for...in loop will never reach a 2nd iteration.

Oriol
  • 274,082
  • 63
  • 437
  • 513
0

console.log and return are completely different things.

For the first case, you see

"name"
"age"
> undefined 

because you tell the console to explicitly log the keys, but the second case, with the return keyword, you tell the function to terminate and return the value "name", that's why you only see

> "name"
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
0

console.log() will print to the console your passed in arguments, where as return stops the execution of your function and returns whatever you tell it to.

Richard Kho
  • 5,086
  • 4
  • 21
  • 35
0

Once a function hits a return statement, it will stop executing; so in the first example, it loops through both. In the second, it hits that return statement and says, "Ok, I'm done."

Chad Hedgcock
  • 11,125
  • 3
  • 36
  • 44