Variables

JS4Scratch Reference Manual:

Unlike regular JavaScript you can make (declare) your variables in the "Global Variables" TAB. If you want to display the variable value on the scratch screen then you must tick the "Display" box for that variable. However, you can declare variables in your code just like regular JavaScript using "const", "let" or "var" as per normal. Furthermore, you can start using variables in our coding system without making/declaring them because we will automatically declare them.

Make a Variable

Variables are made (declared) in the "Global Variables" TAB. If you don't have that TAB then use the "+" to add it to your project. You don't have to declare these Global Variables in your script (js file) like normal JavaScript, however, you may declare variables in your script file as per normal JavaScript if you wish. Do not declare the same variable twice because it won't run.

Variable Types:

  • String: "word" or "text" eg 'clicked'
  • Number: mathematical number eg 24
  • Boolean: value can be either "true" or "false" but this is NOT a "string" variable.
  • Array: same as Scratch3 "List"
  • Function: same as "Create your own block" in Scratch i.e. run a code snippet - sometimes called a sub-routine.
  • Timer: uses the internal clock to track time in seconds

Set Variable

my_variable = 0

Change Variable

my_variable = my_variable + 1

Display Variables

Variables are displayed or hidden on the Scratch Stage by selecting/deselecting the "Display" box on the right hand side of that variable in the "Global Variables" TAB.


Example

The variable "score" is declared as a "number" and checked to display on the stage.

spriteA.whenFlag(function () {
score = 0
this.show()
    this.say('click me to add 1 to displayed score variable')
    this.whenClicked(function (){
        score = score + 1
    })
})