Why don't you need to use `const` or `let` keywords when declaring variables with `this`?

Hi folks, maybe I’ve been looking at my screen for too long, but I’m wondering why you don’t seem to have to use const or let keywords when declaring variables with this. In this exercise (shared snippet below), const oneSecond = 1000; requires use of const, but the very next line does not…even though we’re storing the setInterval() method in a variable! What gives?

import React from 'react';

export class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = { date: new Date() };
  }
  render() {
    return <div>{this.state.date.toLocaleTimeString()}</div>;
  }
  componentDidMount() {
    const oneSecond = 1000;
    this.intervalID = setInterval(() => {
      this.setState({ date: new Date() });
    }, oneSecond);
  }
}
1 Like

The ‘this’ keyword is a complicated topic. There are a lot of different scenarios that can effect what ‘this’ refers to. The MDN reference for this provides a lot of detail, but it can be challenging to understand it all (frankly I don’t understand it all!).

In a class constructor call, ‘this’ is bound to the object being constructed. Either to the class or the instance depending on the type of property. Using const, var or let would be inappropriate for several reasons. First, the language prohibits combining these keywords with the ‘this’ keyword. Second, the other variable keywords are used to identify the scope/behavior of a variable for different contexts, whereas ‘this’ is used to declare a property in the case of a class. Here is a little overview on variable declaration: Var, let and const in JS

Hope that at least provides some help in understanding this complex topic.

2 Likes

Thanks for chiming in. In the Codecademy Discord server someone responded with the following:

  1. When using this in an object, this will refer to the object itself. const is being used for the variable called oneSecond which equals to 1000( or 1s).

So, basically, if I were instead initializing oneSecond as an object instead of an integer, I would need to declare it with this inside the class constructor. Does that sound right?

One small change. You would be initializing ‘oneSecond’ as a property of the object if you use ‘this’.

Using const, as in your your code example, creates a locally scoped variable for use within the componentDidMount method, but nowhere else in the Component class.

1 Like