Q on JavaScript function relating to Rock Paper Scissors project


#1

Hello there,

I finally completed the Rock Paper Scissors project using JavaScript after spending a lot of hours on it. It feels great!

My question is related to this project, as I stumbled onto this. I do not understand it and would like some advice on the topic.

Q: What is the difference between 1 and 2? or am I missing something here?

  1. let play = getPlayFootball(teamName, winNumber, lossNumber, drawNumber);

  2. play = getPlayFootball(teamName, winNumber, lossNumber, drawNumber);

where,
getPlayFootball(teamName, winNumber, lossNumber, drawNumber) {
statement
}

Thank you.


#2

Using let scopes the variable to the block it was declared it. Using a variable name directly creates a global variable accessible throughout all the code. Where this can be problematic is it’s common to use many local variables in different functions with the same name and that’s fine because by using let or const they are scoped to that function. If you use a global variable it changes its value everywhere it is references so you might find that it has unexpected consequences elsewhere.

It is generally only recommended to use global variables where there is a clear use case.


#3

Hey @CouchofTomato, thanks for the quick reply.

Ok, I did not know #2 is a Global Variable. I thought it was only with “var play”, that play becomes a Global Variable.

Now I know. Appreciate for sharing the info.