JavaScript Variables

Kino

EIS Game Dev
Veteran
Joined
Nov 27, 2015
Messages
556
Reaction score
794
First Language
English
Primarily Uses
RMMV
Since MZ is ES6, I've decided to repost some of the older tutorials around ES6 JavaScript.



JS Variables

For the record I own both KinoCreates and EIS

Full text transcript:

Every programming languages come with basic building blocks; variables are one of those blocks. Variables are the storage compartments that make dreams come true. In this chapter, we’ll be discussing a variable’s purpose and scope.

Purpose Of Variables
A variable’s purpose is to store values in your program. Variables act as an identifier or convenient nickname for a value. A variable will represent that value so long as it’s not changed. Here’s a quick example.

var mynumber = 2;
console.log(mynumber); //2
mynumber = 3;
console.log(mynumber); //3

This example demonstrates the fundamental idea; “mynumber” represents 2 then 3. Furthermore, “mynumber” can be anything we want. This comes with clear benefits when writing code. Now, I think you can guess what those clear benefits are before looking at the next statement.

If you guessed reusability and flexibility you’re correct; variables allow programmers to reuse values in code, reducing the amount of work you have to do. Now, not all variables are created equal; variables have scopes.

Variable Scope
As mentioned above, all variables have a scope. “Scope” is the area in the program where the variable exists. Scope also applies to when certain variables and functions are available for you to use; In most cases, the code near the top is created first and should be a rule of thumb for understanding when and where code exists.

An understanding of scope is extremely important to not just variables, but functions which will be introduced later. In JavaScript, there are three variable keywords(reserved words that have special meaning to the language), var, let, and const. Each keyword follows a different scope rule. These different scope rules are block and function scope.

Block Scope
Block scope is when you surround your variables in curly brackets; this includes functions also. Variables created with let and const fall into this category. The difference between let and const is that const can’t be reassigned to an another value. Now, here’s an example of both keywords.

{
const a = 3;
let b = 70;
console.log(a, b); //3 70
}
console.log(a, b); //Undefined error....

As you can see in this example, you don’t have access to the variable outside of the curly brackets. Which leads me the last keyword, var and function scope.

Function Scope
Function scope is when your variables only exist within a function; curly brackets will not limit the scope of the variable. Variables created with the var keyword fall into this category. Let’s use an example to compare this to block-scoped variables. Here’s an example.

{
var a = 3;
}
function Test() {
var b = 10;
console.log(b); //10
}
console.log(a); //3
Test();
console.log(b); //b is not defined...

In this example, we create both a variable a and b, but as you can see a is available even outside of the curly brackets. Within the Test function, b is not available outside of the function’s scope. Now, an important thing to note is that variables created with var can be useful if you want a wider scope. However, use let and const in most circumstances for more fine-tuned controls.

An understanding scope will be paramount when writing code for your game. This should be the basis for your understanding of coding your game. Variables are the backbone of all your game code and will make it easier to script for your game.


Regards
 

Dororo

Gespenst MKII pilot
Veteran
Joined
May 24, 2020
Messages
264
Reaction score
920
First Language
Italian
Primarily Uses
RMMV
So, assuming I'm correct, a var declared on the outermost scope work like a global.
 

Eliaquim

Hakuen Studio
Veteran
Joined
May 22, 2018
Messages
1,678
Reaction score
1,095
First Language
Portuguese - Br
Primarily Uses
RMMZ
@Dororo Yes. But in fact, any variable declared on the outermost scope will work as a global in your code, in a certain way.
If you use that:
JavaScript:
function example(){
var test1 = 'A'
let test2 = 'B'
const test3 = 'C'
return test1 + test2 + test3
}
console.log(test1)
console.log(test2)
console.log(test3)
All these 3 variables will only "live" inside that function.
If you try to check the value for any of them, you will get an undefined error in the console.log above.

But if you use that:
JavaScript:
var test1 = 'A'
let test2 = 'B'
const test3 = 'C'
function example2(){
return test1 + test2 + test3
}
console.log(example2) // I will return 'ABC'
Because all 3 variables are now declared outside the function scope.
The thing is, that when you declare a variable in a scope, all of the "nested scopes" will have access to them.

Another explanation will be the following:
You have two plugins in your plugin manager, in that order:
plugin1.js
plugin2.js

If you declare in the plugin1.js, outside of any function:
var test1 = 'A'
let test2 = 'B'
const test3 = 'C'

And you use console.log() to check any of these variables in the plugin2.js(Or in the chrome dev tools), it will return the values.
So, what you are saying is true, but there is this add on too ^^

@Kino Great explanation! I also like to add that when use let and const inside a if statement or in a loop body, also made them only available for them.
[EDIT]
So it's a good practice to use them in an if and loop body, in case we do not use these values outside them:
Unlike this code:
for(var i = 10; i < 11; i++)
Use below:
for(let i = 10; i < 11; i++)
[/EDIT]
JavaScript:
function(){
    if(condition){
        let test = 'a'
    }
console.log(test) // return undefined
}
function(){
for(let test = 10;test--){
// code
}
console.log(test) // return undefined
}
There is another difference between var to let and const.
With var you can not only reassign a value(like let) but also, declare the variable again:
var test = 'a'
var test = 'c'


But you cannot do this to let:
let test = 'a'
let test = 'b' // return error.
You have to do this:
let test = 'a'
test = 'c'


Also, there is the hoisting behavior. When we use
console.log(test) // Return 'a'
var test = 'a'


But with let:
console.log(test) // Return test is not defined.
let test = 'a'


And const variables cannot be declared without any value:
const test; // SyntaxError: Missing initializer in const declaration


Hope this information can help someone ^^
It's pretty hard to talk about these things in English for me, so hopefully, I did make a good explanation xD
 
Last edited:

Solar_Flare

Veteran
Veteran
Joined
Jun 6, 2020
Messages
533
Reaction score
235
First Language
English
Primarily Uses
RMMV
So, assuming I'm correct, a var declared on the outermost scope work like a global.
Yes, and to go even further, any variable that you don't declare is a global variable. For example:

JavaScript:
function f() {
    test = 5; // this is a global variable!
}

console.log(test); // logs undefined
f();
console.log(test); // logs 5
So basically... if you don't want your variables to be global, be sure to declare them with var or let!

So it's a good practice to use them in an if and loop body, in case we do not use these values outside them:
Unlike this code:
for(var i = 10; i < 11; i++)
Use below:
for(let i = 10; i < 11; i++)
Keep in mind that there are sometimes good reasons to use var instead of let here. In particular, if the purpose of the loop is to find the index of something matching some conditions, then the logical way to do it is to add a break statement once you find the matching index, and then reference i after the loop - if it's equal to the loop max, then the item wasn't found, otherwise it's the matching index.

(Note: usually it's better to use [].findIndex() for this kind of thing, but there are probably cases when a direct loop is easier to understand.)
 

Dororo

Gespenst MKII pilot
Veteran
Joined
May 24, 2020
Messages
264
Reaction score
920
First Language
Italian
Primarily Uses
RMMV
@Solar_Flare : thank for the extra info. I was inspecting some code and I was figuring out that no declarement was equal a LET statement. Glad you helped me out on this.
 

Kino

EIS Game Dev
Veteran
Joined
Nov 27, 2015
Messages
556
Reaction score
794
First Language
English
Primarily Uses
RMMV
I was going to reply but that's great! Glad you guys are sharing your knowledge!
 

Eliaquim

Hakuen Studio
Veteran
Joined
May 22, 2018
Messages
1,678
Reaction score
1,095
First Language
Portuguese - Br
Primarily Uses
RMMZ
Keep in mind that there are sometimes good reasons to use var instead of let here. In particular, if the purpose of the loop is to find the index of something matching some conditions, then the logical way to do it is to add a break statement once you find the matching index, and then reference i after the loop - if it's equal to the loop max, then the item wasn't found, otherwise it's the matching index.
Oh.. I think I don't get this. What am I missing?
I said to use let if we do not need to access outside if/loop:
So it's a good practice to use them in an if and loop body, in case we do not use these values outside them
I think we say the same thing?
once you find the matching index, and then reference i after the loop
Or am I missing something? =O
 

Solar_Flare

Veteran
Veteran
Joined
Jun 6, 2020
Messages
533
Reaction score
235
First Language
English
Primarily Uses
RMMV
@Solar_Flare : thank for the extra info. I was inspecting some code and I was figuring out that no declarement was equal a LET statement. Glad you helped me out on this.
I'm not quite sure what you're saying here, but just to be clear, using an undeclared variable is not equal to a let statement.

Oh.. I think I don't get this. What am I missing?
I said to use let if we do not need to access outside if/loop:

I think we say the same thing?

Or am I missing something? =O
Yeah, I think we ended up saying the same thing. I did add an example of when you might need to access it outside the loop though.
 

Users Who Are Viewing This Thread (Users: 0, Guests: 1)

Latest Threads

Latest Profile Posts

YES! officially released my games soundtrack on Itunes, Spotify, and Amazon..... kinda cool!

Another old age version of Reid. Trying out different style.
Hey everyone! Not sure how many people know about Cafofo Music on Itch.io, but I highly recommend their Sound Effects! It is amazing quality AND quantity and best of all, they are having a 50% sale! I can't express how much I love sales.
Wow.... My last map GIF got 47 likes, 16 retweet and 2,105 views on Twitter in 24 hours. My game thread here's only got 3k views in 6-7 months. I guess building my Twitter was insanely worth it. :LZSexcite:

Forum statistics

Threads
105,594
Messages
1,014,889
Members
137,265
Latest member
megawebdesign
Top