RPGMaker MV ES6 Part 5: Block Scope Variables


Today we continue our incentive to expand on the ES6 features available in RPGMaker MV. Today’s feature is block scoped variables. But  first, we have to go over block scoping.

Block Scoping

Consider all of the code you have in your program. Every part of your program, there is something known as scope. Scope is where the variables, functions, and all other parts of your program available in that scope live. You can think of it as a bubble, or shield around the variables and functions in that part of your code, to protect it from being accessed outside. Which is why scoping is very important.

Scoping allows the developer to improve their code and split functionality into smaller parts that do one thing. Now, let’s talk about scoping in JavaScript.

A scope in JavaScript is created when you create a new function. This is why functions are used to organize code in JavaScript, to prevent variables from being accessed from the outside. Or, why in ES5, functions are used as classes, because the function acts as a scope. However, creating new functions just to create a new scope can be bad for your program, for example when working inside of a function, bringing me to “Block Scope Variables”.

Block Scope Variables

Block scope variables are variables that exist within a specified scope. Before ES6, you had to create a new scope using a function. This means that if you were working within a function, and wanted to create a new variable with “var”, that variable would be available throughout the whole function, even if you only want it to exist inside of an if statement. Now, we have the let keyword, which allows us to create variables that only exist within a block scope. In this case, a block is considered anything with curly brackets ( {} ).  Below is an example of the difference.

Code Example


As you can see let clearly defined a scope; where var operates isn’t as clear. This can lead to variables not being destroyed leading to memory leaks in a program.

With the let keyword now a part of JavaScript, we can clearly declare where the scope ends for a variable. And should forgo using var in most cases, because of how var works.

With that said, I hope this post helps you improve your code in some way.

Leave a Reply

Your email address will not be published.