1

I am new to programming and js and I am trying to learn crux of javascript.

var obj1 = {
    name: 'rawn',
    fn: function() {
        console.log(this);
    }
};
console.log(obj1.fn());

When I output this I get the object(as expected) - {name: "rawn", fn: ƒ} and on another line I get - undefined. So my question is why and how do I get undefined?

My understanding is that, we are writing this line - console.log(obj1.fn()); as , console.log(console.log(this)), so how does javascript engine gives the result as undefined (what was put as undefined in the execution context)?

2
  • What would you expect as result here…? Commented Nov 10, 2018 at 10:50
  • @deceze i though it will simply print the object 2 times Commented Nov 10, 2018 at 11:29

2 Answers 2

2

console.log(obj1.fn()) and console.log(console.log(this)) are not equivalent at all, but they actually have the same result for the same reason: the inner function does not return anything. The return value of these functions is undefined. Which is what the outer console.log logs.

Sign up to request clarification or add additional context in comments.

3 Comments

console.log(obj1.fn()) and console.log(console.log(this)) are not equivalent at all, but I thought when I say () in the fn(), it executes the my written code part i.e console.log(this)
oh yeah, i din't mean it literally, I meant console.log(this) is called first from the obj.fn() and then the outer console.log is called
If the function is passed to the function console.log(), then the function will display the value of the passed function(). Now I know whats going on !
1

This is because of two reasons. First, in console.log(this); the context of this inside the fn function is the object itself. Hence it prints the guts of obj1.

Secondly, in console.log(obj1.fn());, you are actually calling the method which returns nothing. Instead if you say console.log(obj1.fn); it will return:

ƒ () { console.log(this); }

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.