-1

I am trying to understand how "this" keyword works and trying to increase the count variable using a function. But If i use let to declare count, count does not increase , but if i use var to declare count it works. I don't know why is this happening.

let count = 0;
function increaseCounter() {
  this.count++;
};
increaseCounter()
console.log(count)

3 Answers3

2

The this keyword in JavaScript refers to the object that is currently executing the code. In the case of a function, the this keyword refers to the object that the function is a property of.

In your case, you are trying to increase the value of the count variable by using the this keyword inside the increaseCounter function. However, the count variable is not a property of any object, so the this keyword inside the function is not referencing the count variable as you'd expect.

this has a different context depending where it is being used . Check out MDN and/or W3 for a good explanation.

As far as the let vs var problem. Each have a different scope. Read this post about that.

Cody
  • 467
  • 2
  • 11
  • Your "W3" link is broken. – Bergi Dec 30 '22 at 19:22
  • Avoid links to w3schools, they're famous for their horrible explanations - their page on `this` is no exception. Also they are not affiliated with the W3C, so beware the name. Better link [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this). – Bergi Dec 30 '22 at 19:33
0

The function and variable is not in a class, which means you do not need to use the this keyword. You can omit it and just use count++;.

If the function and variable is in a class, then the this keyword is necessary.

Since the code is not working for you, that means you are not in a class, and you should use the first option. The let keyword does not affect this.

For more information, I recommend checking out Classes, Let vs. Var, and The this Keyword

MrDiamond
  • 958
  • 3
  • 17
-1

"var" is global scoped whereas let is function scoped. Thats why when you "var", the "this" which you used inside the function can find property "count" which is available globally.