Mhd
Mhd

Reputation: 2978

When should I use "var", "let" and "const" in TypeScript

I just start coding in TypeScript. So please excuse my newbie question.

I have this method:

public copyToDest() {
    for (var i = 0; i < this.source.length; i++) {
        var item = this.source[i];
        if (item && item.isValid)
            this.dest.push(item);
    }
}

Which is working fine. After installing a refactoring tool, I got 2 suggestions:

  1. Change var i = 0; to let i = 0;
  2. Change var item = ... to const item = ...

Is there any rule I'm missing about proper use of var, let and const? Or should I just ignore these suggestions?

Upvotes: 5

Views: 5592

Answers (1)

Craig W.
Craig W.

Reputation: 18175

Use let when the variable's value can be changed.

Use const when the variable's value cannot/should not be changed.

Do not use var.

Upvotes: 21

Related Questions