Stay organized with collections
Save and categorize content based on your preferences.
Variables are an important programming concept. Blockly supports dynamically
typed languages such as Python and JavaScript and with a little extra work, you
can add information to support strongly typed languages (or static typed
languages) such as Java or C.
Blockly supplies variable fields which are dynamic dropdown boxes that show
the names of variables the user has provided. Below is an example of one.
By default, Blockly allows any type to be assigned to a variable and all of
Blockly's provided generators are for dynamically typed languages. If you are
using a typed language instead, you can configure Blockly to support it by doing
the following:
The most basic blocks for accessing and manipulating a variable are the getter
and setter blocks. Let's walk through the getter and setter blocks that Blockly
provides.
JSON
// Block for variable getter.{"type":"variables_get","message0":"%1","args0":[{// Beginning of the field variable dropdown"type":"field_variable","name":"VAR",// Static name of the field"variable":"%{BKY_VARIABLES_DEFAULT_NAME}"// Given at runtime}// End of the field variable dropdown],"output":null,// Null means the return value can be of any type...},// Block for variable setter.{"type":"variables_set","message0":"%{BKY_VARIABLES_SET}","args0":[{"type":"field_variable","name":"VAR","variable":"%{BKY_VARIABLES_DEFAULT_NAME}"},{"type":"input_value",// This expects an input of any type"name":"VALUE"}],...}
JavaScript
// Block for variable getter.Blockly.Blocks['variables_get']={init:function(){this.appendDummyInput().appendField(newBlockly.FieldVariable("VAR_NAME"),"FIELD_NAME");this.setOutput(true,null);...}};// Block for variable setter.Blockly.Blocks['variables_set']={init:function(){this.appendValueInput("NAME").setCheck(null).appendField("set").appendField(newBlockly.FieldVariable("VAR_NAME"),"FIELD_NAME").appendField("to");this.setOutput(true,null);...}};
This creates the following two blocks:
An important detail to notice is that by setting the variable getter's "output"
to null, the return value can be of any type. Also, notice that variable
setter's input does not specify any checks. As a result, the variable can be set
to any type of value.
Typed Variable Blocks
You can add getters and setters that enforce type checking. For example, if you
have created a variable of type "Panda", the following definitions create a
getter and setter with the appropriate types.
JSON
// Block for Panda variable getter.{"type":"variables_get_panda","message0":"%1","args0":[{"type":"field_variable","name":"VAR","variable":"%{BKY_VARIABLES_DEFAULT_NAME}","variableTypes":["Panda"],// Specifies what types to put in the dropdown"defaultType":"Panda"}],"output":"Panda",// Returns a value of "Panda"...},// Block for Panda variable setter.{"type":"variables_set_panda","message0":"%{BKY_VARIABLES_SET}","args0":[{"type":"field_variable","name":"VAR","variable":"%{BKY_VARIABLES_DEFAULT_NAME}","variableTypes":["Panda"],"defaultType":"Panda"},{"type":"input_value","name":"VALUE","check":"Panda"// Checks that the input value is of type "Panda"}],"previousStatement":null,"nextStatement":null,...}
JavaScript
// Block for Panda variable getter.Blockly.Blocks['variables_get_panda']={init:function(){this.appendDummyInput().appendField(newBlockly.FieldVariable("VAR_NAME",['Panda'],'Panda'),"FIELD_NAME");this.setOutput(true,'Panda');...}};// Block for Panda variable setter.Blockly.Blocks['variables_set_panda']={init:function(){this.appendValueInput("NAME").setCheck('Panda').appendField("set").appendField(newBlockly.FieldVariable("VAR_NAME",null,['Panda'],'Panda'),"FIELD_NAME").appendField("to");this.setPreviousStatement(true,null);this.setNextStatement(true,null);...}};
This creates two types of blocks, a getter and a setter. Their dropdowns only
display variables of type Panda. Their inputs and outputs only accept
connections with type Panda. The defaultType of the field must be set to one
of the values in the variableTypes array. Not setting the defaultType while
providing a variableTypes array will cause an error to be thrown.
By default there is no visual indicator to tell the user which type is being
used. One easy way to differentiate variable types is by
colour.
Add Variables to Toolbox
To make this new type of variable useful to your users, you need to add a way to
create and use the new variables.
Create a new dynamic category
for variables if you do not already have one.
Add your new getters and setters to the category.
Create Variable Button
Next, your user needs a way to create variables. The simplest way is with a
"Create Variable" button.
The easiest way to allow users to create variables of multiple types is to have
one "create" button per type (e.g. Create String Variable, Create Number
Variable, Create Panda Variable).
If you have more than two or three variable types, you can quickly end up with
too many buttons. In that case, consider using
@blockly/plugin-typed-variable-modal
to display a popup from which users can select their desired variable type.
Define Generators
Finally, you will need to define block-code generators
for your new variable blocks. You can also access the list of variables directly
with Workspace.getVariableMap().getAllVariables() to get all variables of all
types or Workspace.getVariableMap().getVariablesOfType() to get all variables
of a specific type.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-05 UTC."],[[["\u003cp\u003eBlockly supports dynamically typed languages like Python and JavaScript by default and can be configured to support statically typed languages like Java or C.\u003c/p\u003e\n"],["\u003cp\u003eUsers can create and utilize typed variables by specifying variable types, configuring the toolbox with relevant blocks, and defining block-code generators.\u003c/p\u003e\n"],["\u003cp\u003eBlockly provides getter and setter blocks for variable manipulation, and you can customize these blocks to enforce type checking for specific variable types, like "Panda" in the example.\u003c/p\u003e\n"],["\u003cp\u003eTo accommodate multiple variable types, consider using individual "create" buttons for each type or using a modal popup for type selection when numerous types are involved.\u003c/p\u003e\n"],["\u003cp\u003eVariable types can be visually differentiated by assigning unique colors to their blocks for better user understanding.\u003c/p\u003e\n"]]],["Blockly, which supports dynamic typing, can be configured for static typing. To do this, users must: specify variable types with corresponding getter and setter blocks, configure the toolbox to use these blocks, and define code generators for the variable blocks. Getter blocks output a specified type, while setter blocks verify the input matches the variable type. Users can add a \"Create Variable\" button to generate these variables or utilize a plugin for multiple types. Ultimately, generators need to be defined for these blocks.\n"],null,["# Variables are an important programming concept. Blockly supports dynamically\ntyped languages such as Python and JavaScript and with a little extra work, you\ncan add information to support strongly typed languages (or static typed\nlanguages) such as Java or C.\n\nFor more information on dynamic versus static typed languages, see [Introduction\nto Data Types: Static, Dynamic, Strong \\&\nWeak](https://www.sitepoint.com/typing-versus-dynamic-typing/).\n\nBlockly supplies variable fields which are dynamic dropdown boxes that show\nthe names of variables the user has provided. Below is an example of one.\n\nBy default, Blockly allows any type to be assigned to a variable and all of\nBlockly's provided generators are for dynamically typed languages. If you are\nusing a typed language instead, you can configure Blockly to support it by doing\nthe following:\n\n- [Specify a variable type and its blocks](#typed_variable_blocks), including getters and setters.\n- [Configure the toolbox](#add_variables_to_toolbox) to use your variable type and blocks.\n- [Define generators](#define_generators) for variables and their blocks.\n\nUntyped Variable Blocks\n-----------------------\n\nThe most basic blocks for accessing and manipulating a variable are the getter\nand setter blocks. Let's walk through the getter and setter blocks that Blockly\nprovides. \n\n### JSON\n\n // Block for variable getter.\n {\n \"type\": \"variables_get\",\n \"message0\": \"%1\",\n \"args0\": [\n { // Beginning of the field variable dropdown\n \"type\": \"field_variable\",\n \"name\": \"VAR\", // Static name of the field\n \"variable\": \"%{BKY_VARIABLES_DEFAULT_NAME}\" // Given at runtime\n } // End of the field variable dropdown\n ],\n \"output\": null, // Null means the return value can be of any type\n ...\n },\n\n // Block for variable setter.\n {\n \"type\": \"variables_set\",\n \"message0\": \"%{BKY_VARIABLES_SET}\",\n \"args0\": [\n {\n \"type\": \"field_variable\",\n \"name\": \"VAR\",\n \"variable\": \"%{BKY_VARIABLES_DEFAULT_NAME}\"\n },\n {\n \"type\": \"input_value\", // This expects an input of any type\n \"name\": \"VALUE\"\n }\n ],\n ...\n }\n\n### JavaScript\n\n // Block for variable getter.\n Blockly.Blocks['variables_get'] = {\n init: function() {\n this.appendDummyInput()\n .appendField(new Blockly.FieldVariable(\"VAR_NAME\"), \"FIELD_NAME\");\n this.setOutput(true, null);\n ...\n }\n };\n\n // Block for variable setter.\n Blockly.Blocks['variables_set'] = {\n init: function() {\n this.appendValueInput(\"NAME\")\n .setCheck(null)\n .appendField(\"set\")\n .appendField(new Blockly.FieldVariable(\"VAR_NAME\"), \"FIELD_NAME\")\n .appendField(\"to\");\n this.setOutput(true, null);\n ...\n }\n };\n\nThis creates the following two blocks:\n\nAn important detail to notice is that by setting the variable getter's \"output\"\nto null, the return value can be of any type. Also, notice that variable\nsetter's input does not specify any checks. As a result, the variable can be set\nto any type of value.\n\nTyped Variable Blocks\n---------------------\n\nYou can add getters and setters that enforce type checking. For example, if you\nhave created a variable of type \"Panda\", the following definitions create a\ngetter and setter with the appropriate types. \n\n### JSON\n\n // Block for Panda variable getter.\n {\n \"type\": \"variables_get_panda\",\n \"message0\": \"%1\",\n \"args0\": [\n {\n \"type\": \"field_variable\",\n \"name\": \"VAR\",\n \"variable\": \"%{BKY_VARIABLES_DEFAULT_NAME}\",\n \"variableTypes\": [\"Panda\"], // Specifies what types to put in the dropdown\n \"defaultType\": \"Panda\"\n }\n ],\n \"output\": \"Panda\", // Returns a value of \"Panda\"\n ...\n },\n\n // Block for Panda variable setter.\n {\n \"type\": \"variables_set_panda\",\n \"message0\": \"%{BKY_VARIABLES_SET}\",\n \"args0\": [\n {\n \"type\": \"field_variable\",\n \"name\": \"VAR\",\n \"variable\": \"%{BKY_VARIABLES_DEFAULT_NAME}\",\n \"variableTypes\": [\"Panda\"],\n \"defaultType\": \"Panda\"\n },\n {\n \"type\": \"input_value\",\n \"name\": \"VALUE\",\n \"check\": \"Panda\" // Checks that the input value is of type \"Panda\"\n }\n ],\n \"previousStatement\": null,\n \"nextStatement\": null,\n ...\n }\n\n### JavaScript\n\n // Block for Panda variable getter.\n Blockly.Blocks['variables_get_panda'] = {\n init: function() {\n this.appendDummyInput()\n .appendField(new Blockly.FieldVariable(\n \"VAR_NAME\", ['Panda'], 'Panda'), \"FIELD_NAME\");\n this.setOutput(true, 'Panda');\n ...\n }\n };\n\n // Block for Panda variable setter.\n Blockly.Blocks['variables_set_panda'] = {\n init: function() {\n this.appendValueInput(\"NAME\")\n .setCheck('Panda')\n .appendField(\"set\")\n .appendField(new Blockly.FieldVariable(\n \"VAR_NAME\", null, ['Panda'], 'Panda'), \"FIELD_NAME\")\n .appendField(\"to\");\n this.setPreviousStatement(true, null);\n this.setNextStatement(true, null);\n ...\n }\n };\n\nThis creates two types of blocks, a getter and a setter. Their dropdowns only\ndisplay variables of type Panda. Their inputs and outputs only accept\nconnections with type Panda. The `defaultType` of the field must be set to one\nof the values in the `variableTypes` array. Not setting the `defaultType` while\nproviding a `variableTypes` array will cause an error to be thrown.\n\nBy default there is no visual indicator to tell the user which type is being\nused. One easy way to differentiate variable types is by\n[colour](/blockly/guides/configure/web/appearance/block-colour).\n| **Note:** The `variableTypes` key is optional on a field_variable. If it is undefined only variables of the empty string type `\"\"` will be shown. To show all variables of any type use `\"variableTypes\": null`.\n\nAdd Variables to Toolbox\n------------------------\n\nTo make this new type of variable useful to your users, you need to add a way to\ncreate and use the new variables.\n\nCreate a new [dynamic category](/blockly/guides/configure/web/toolboxes/dynamic)\nfor variables if you do not already have one.\n\nAdd your new getters and setters to the category.\n\n### Create Variable Button\n\nNext, your user needs a way to create variables. The simplest way is with a\n\"Create Variable\" [button](/blockly/guides/configure/web/toolboxes/buttons).\n\nWhen creating the button, make the callback call \n\n Blockly.Variables.createVariableButtonHandler(button.getTargetWorkspace(), null, 'panda');\n\nand a Panda typed variable will be created!\n\nThe easiest way to allow users to create variables of multiple types is to have\none \"create\" button per type (e.g. Create String Variable, Create Number\nVariable, Create Panda Variable).\n\nIf you have more than two or three variable types, you can quickly end up with\ntoo many buttons. In that case, consider using\n[@blockly/plugin-typed-variable-modal](https://www.npmjs.com/package/@blockly/plugin-typed-variable-modal)\nto display a popup from which users can select their desired variable type.\n\nDefine Generators\n-----------------\n\nFinally, you will need to [define block-code generators](/blockly/guides/create-custom-blocks/code-generation/overview#block-code_generators)\nfor your new variable blocks. You can also access the list of variables directly\nwith `Workspace.getVariableMap().getAllVariables()` to get all variables of all\ntypes or `Workspace.getVariableMap().getVariablesOfType()` to get all variables\nof a specific type."]]