0

I'm trying to better understand the use of this. In experimenting with this code, I found I can access the items in arr by using something like console.log(this.arr[4]), but only if arr is declared using var. If I declare arr using let or const, I get a TypeError.

First, I do understand this is verbose. Like I said, I am just experimenting to try and get a better understanding and came across this issue that piqued my curiosity.

const arr = [
  1,
  false,
  {
    name: 'John',
    address: '123 Peachtree Drive'
  },
  function(name = 'new user') {
    const greeting = 'Hello there, '
    console.log(greeting + name)
  },
  'foo',
]

console.log(this.arr[4])

Again, if I simply declare arr using var instead of let I can log it just fine.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
sirCastle
  • 11
  • 2
  • 1
    `this` makes no sense, should just be `console.log(arr[4])` – epascarello Jul 05 '19 at 19:13
  • 1
    You should just read up on ["this"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this), there's no proper question to answer here. – Yannick K Jul 05 '19 at 19:14
  • You are not using `let` in your code sample... That said, good job using "piqued" :). – Heretic Monkey Jul 05 '19 at 19:17
  • @epascarello. I understand I could just use `console.log(arr[4])`. The idea was that I thought `console.log(this.arr[4])` would have the same result, and it did not. – sirCastle Jul 05 '19 at 23:57

2 Answers2

4

In a browser, top-level this is window, and top-level var declarations also make variables accessible as properties of window, while let and const do not. The correct way to reference arr is simply

console.log(arr[4])

I would discourage you from using top-level this to even access var declarations, because code which relies on that behavior of var is obviously confusing, as this case is a perfect example of.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
0

The behavior you're getting confused about is not specific to 'this'. It is related to scope. 'var' has a different scope than 'let' or 'const'.

var - has function level scoping and can change the value reference
let - has block level scoping and can change the value reference
const - has block level scoping but cannot change the value reference

https://love2dev.com/blog/javaScript-var-let-const/

Be precise about how and where you declare your variables as this is an important part of JavaScript syntax/interpretation.

JDH
  • 99
  • 4