0

I have the following code:

var object = {
    name: 'hello!',
    func: function(){
        console.log(this);
    }
}

console.log(object.func());

What I expect is to see the object whenever I log object.func and this does happen, I get to see the object. But right after the expected behavior I get unexpected behavior, undefined is shown.

Here's what the result looks like:

{ name: 'hello!', func: [Function: func] }
undefined

What's the reason this is happening?

Side note:

I know I'm console logging something I shouldn't. However, this still doesn't explain to me why the undefined.

f-CJ
  • 4,235
  • 2
  • 30
  • 28
kevin seda
  • 396
  • 1
  • 3
  • 16

2 Answers2

4

object.func() doesn't return anything (so it returns undefined)

no need to log the result of object.func()

amd
  • 20,637
  • 6
  • 49
  • 67
2

You are trying to log the result of a function that does not return anything, hence, undefined. Just call obj.func() since you already handle the logging there anyway.

Or return a value on the function and log outside

var obj = {
    name: 'hello!',
    func: function(){
        return this;
    }
}
Abana Clara
  • 4,602
  • 3
  • 18
  • 31
  • `console.log(obj.func());` returns two lines: 1 .`{name: "hello!", func: ƒ}` and 2. `undefined` . <-- why undefined? – zipzit Apr 12 '19 at 07:59
  • @zipzit You are doing a `console.log` twice. First one inside your `.func()` method, second one outside the object, which is undefined since `obj.func()` does not return anything – Abana Clara Apr 12 '19 at 08:01
  • I'm using your function. `return this`, not the original submitted stuff. Note: I'm using browser console. – zipzit Apr 12 '19 at 08:02
  • @zipzit If you are testing this on a browser's dev tools, it is because `console.log()` does not return anything either, that is why the browser shows undefined after the actual only `console.log(value)` that we wrote. If you try OP's submitted code, you will get three lines of results – Abana Clara Apr 12 '19 at 08:04
  • My bad. Right you are. Thx. – zipzit Apr 12 '19 at 08:12