No need for let or const in getter

Hello All,

I’m doing the team-stats exercise:

https://www.codecademy.com/paths/full-stack-engineer-career-path/tracks/fscp-javascript-syntax-part-ii/modules/fecp-learn-javascript-syntax-objects/projects/team-stats

When writing the addPlayer method, I accidentally omitted the ‘const’/‘let’ keyword before ‘player =’, so I wrote this:


addPlayer(firstName, lastName, age)  {
   player = {
       firstName,
       lastName,
       age
   }
   team.players.push(player);
}

Much to my surprise this generates no error and the player gets added to the team. Why can I leave ‘let’ / ‘const’ out in this situation? The editor doesn’t pick it up correctly because the colouring is not correct (everything stays orange iso turning into cyan), but apparently the player object gets created.
Thanks!

Because working code and good code (code following good practices) are not the same thing.

let and const ensure proper scope, without these keywords the variable become global.

1 Like

Ah, coming from Python, I didn’t realise this. Thanks a lot, much appreciated!

JavaScript gives you more “freedom” in type of scopes. (using the right scope is of course the best way to go)

JavaScript has var, which is similar to variable scope in python. If we do:

def example(): 
  x = 3

x has a local scope, it only exists within the function.

same is roughly true for javascript:

function example() {  
    var x = 3;
}

however, let and const are block-scoped, something we do not have in python:

if True:
  x = 3

print(x) # prints 3
if (true) {
   let x = 3;
}
console.log(x); // gives error, x variable only exists in if block/body. 

I don’t think I need to clarify which code samples are python and which ones are javascript, right?

:smile:
In all other languages I came across variables are always block scoped, so I didn’t realise it’s different in JS. Thanks again for explaining, this will probably save me a ton of debugging in the future!

Python doesn’t have block-scope, it has function scope (or whatever you like to call it)

What other language have you done then that you encountered block-scope?

True, but I never had to use 2 separate blocks to get block scope on purpose. So what got stuck in my mind is ‘a function is also a block’ and I never gave it much further thought. But you are right, in JS you could do that.

1 Like