Home > Enterprise >  Javascript: What's the difference between assigning a value globally or inside an 'initial
Javascript: What's the difference between assigning a value globally or inside an 'initial

Time:11-20

I watch a lot of programming tutorials and challenges using HTML5 canvas and Javascript (mainly by Dan Shiffman or The Coding Train) and I try to follow along while changing the code in order to make it my own.

I've noticed a lot of the programmers creating variables (e.g. let num;) and then assigning the values inside of an init() function.

What is the difference between doing that and just assigning the value to the variable in the same line (e.g. let num = 1;)?

I've tried doing both and I don't see a difference so I'm thinking it's maybe a slight performance boost?

CodePudding user response:

Assigning the values inside a function will allow you to call that function from anywhere, rather than being stuck at assigning only at the initialization location. From a practical perspective, assuming you understand scope and the temporal dead zone, this can be helpful for:

  • Code organization. If you put the meat of your code into functions and then call the functions all together later, it can be easier to visualize the higher-order process of what's going on, and in what order the various chunks of code need to run in. If the code is long, it can be easier to understand what init() means than to understand what <200 lines of setup code> means.
  • Less repetitiveness. Say that at some point when the application is used, either you or the user want to reset the state of the app back to how it was originally. (For example, a "Play Again" button on a game.) Then, rather than having to write <200 lines of setup code> again, you'd just have to write init() again.

maybe a slight performance boost?

This has no effect on performance.

  • Related