0

I have a JavaScript object:

function Thing() {
    this.number = 4;
}

I create an instance and assign a new property:

var myThing = new Thing();
myThing.newProperty = 5;

console.log(myThing.newProperty);

and the output is:

5
undefined

Why is the output also printing undefined?

opticon
  • 3,494
  • 5
  • 37
  • 61
  • 6
    If you actually ran `console.log` from the JS console, that `undefined` is the return value from `console.log`. The console printed that after calling `log()` – Paul Roub May 27 '15 at 17:36
  • If you're printing once, @PaulRoub is right. If you're printing more than once, you should include the other code. – ssube May 27 '15 at 17:37

1 Answers1

3

You don't need to type console.log() into the console. If you type in a variable, it'll print its value.

When you do console.log(myThing.newProperty); in the console, it runs it and shows you its return value.

5 is shown because you ran console.log. undefined is shown because that's console.log's return value.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337