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

Why are instance variables not required in JS?

I'm used to Typescript, where instance variables must be defined in a class. In Typescript, the code below would throw an exception saying Property 'name' does not exist on type 'Pet'.

class Pet {
  constructor(name) {
    this.name = name;
  }
}

But this code works fine in Javascript. I can even retrieve this.name with a function. Is an instance variable implicitly created for every variable I declare inside a constructor?

Thank you!

Just for clarification,

are you wondering why you don't have to declare the type of the variable like you do in TypeScript? Like:

class Pet {
  name: string;
  constructor(name) {
    this.name = name;
  }
}

As from what I understand, you define Classes in Javascript in almost the exact same way you would in TypeScript..

Hi, Brandon:

No, my question wasn't about types.

Typescript requires an explicit declaration of instance variables like this...

class Pet {
 name; <--- this guy
  constructor(name) {
    this.name = name;
  }
}

Javascript doesn't require it.