Search code examples
javascriptjsbinbloc.io

why is console.log output different from a return output


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?


Solution

  • 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.