Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Understanding "this" in JavaScript

Leonardo Motta
Leonardo Motta
11,284 Points

Why my template literals does not work with this arrow function?

const portland = {
  bridges: 12,
  airport: 1,
  soccerTeams:1,
  logNumberOfBridges: () => {
    console.log(`There are ${this.bridges} bridges in Portland!`)
  }
}

portland.logNumberOfBridges();
#############
###CONSOLE###
#############
leonardo@leo:~/firstApp$ node script.js
There are undefined bridges in Portland!

I found that without arrow function it works just as expected, but I am really confused here.

const portland = {
  bridges: 12,
  airport: 1,
  soccerTeams: 1,
  logNumberOfBridges: function() {
    console.log(`There are ${this.bridges} bridges in Portland!`)
  }
}
portland.logNumberOfBridges();

3 Answers

Steven Parker
Steven Parker
231,264 Points

One of the ways arrow functions are different is that they do not define a "this" like conventional functions do.

For more details, see the MDN page on arrow functions.

Leonardo Motta
Leonardo Motta
11,284 Points

You are always helping us, TY!

I think its the this binding of this one of the offsets about using arrow functions

Steven Parker
Steven Parker
231,264 Points

I believe that's what I said!

Yes that is what you said i am allowed to comment. I am not saying your wrong