JavaScript

The following is a JavaScript tutorial. This tutorial, after completing Blockly, should get you up and running to script spells in JavaScript for CodeSpells.

This tutorial was prepared by the community member, Bandersnatch.

Intro to JavaScript

This tutorial will introduce you to JavaScript if you’ve never used a programming language before. This tutorial assumes you’re familiar with coding in CodeSpells using Blockly.

Create a JavaScript Spell

To create a JavaScript spell, create a spell the same as you would a Blockly spell, but select JavaScript instead of Blockly. You’ll immediately be shown some code that’s premade for you, and it’ll look something like this:

function onCreate()
{
 orb.setVelocity( 50 );
}

function onHit()
{
 orb.setVelocity( 0 );
}

This is the same as what was shown to you in Blockly when you first created a spell.

Basic Syntax

Syntax is essentially the basic structure of the JavaScript. Simpler than grammar, it’s used to tell you things about the language itself being spoken. Examples of syntax in English are periods, commas, exclamation marks, and so on. These all tell you to interpret things differently when you encounter them. Similarly, syntax in a programming language tells the computer how to interpret the rest of what you’ve written. JavaScript uses a syntax that is very similar to that of many popular programming languages.

Comments // /* */

Comments are how we write text that is not run within our code. Comments are mostly used as documentation to describe what the code is doing at this point. Upon finding two slashes in a row, the computer will not read the rest of the code:

  //This is a comment
  thisIsNotAComment(); //This is though

Multiline comments can be created using the /* and the */ character sequences:

/*
This is a comment
Same with this
And this
*/
thisIsNotThough();

The Semicolon ;

The Semicolon looks like this: ; and is the simplest piece of syntax. We put this at the end of commands when we’re telling the computer to do something. When the computer encounters a semicolon, it interprets what it sees next as a new command. You should put a semicolon at the end of almost every line, the exception being when you declare a function (since declaring a function is not a command). Use it like this:

x=y;

Assignment Operator =

The Assignment Operator is how we set a variable to something else. For example:

x=56;

Operators + - * / %

Operators are what we use for basic math. You should already understand how to use all of these but modulus which looks like the percent symbol. Modulus is the equivalent of the “remainder of” block in Blockly. Modulus subtracts the first number by the second number as many times as it can while remaining a whole number, then returns the remainder of the first number. As such, 5%3 is 2, 10%5 is 0, 100%1 is 0, 53%5 is 3, and so on. Math will follow the order of operations, with modulus being at the same level of precedence as multiplication and division. There are additional operators, called bitwise operators, which will not be covered in this tutorial. If you would like to know more about bitwise operators, a quick Google search would suffice. In the following example, x would be set to 3534:

x=36*97+42;

Advanced Assignment Operators

There are more assignment operators other than just =.

x += 5; // The same as x = x + 5;
x -= 6; // The same as x = x - 6;
x *= 4; // The same as x = x * 4;
x /= 3; // The same as x = x / 3;
x %= 2; // The same as x = x % 2;
x++; // //The same as x = x + 1; Only works if x is an integer.
x--; // //The same as x = x - 1; Only works if x is an integer.

Parenthesis ()

Parenthesis are how you tell the compiler to execute a function. You already know functions from Blockly since literally every block that does something is a function. Things inside of parenthesis are called parameters, and are variables that you give to the function that change how the function works. This looks like this:

doSomething(parameter1);

Parenthesis can also be used to group operations to achieve the desired order of operations. In the following example, x would be set to 5004:

x=36*(97+42);

Commas ,

Commas are used to separate the parameters to a function like this:

doSomething(parameter1, parameter2);

Declaration Keywords function var

Declaration keywords are how you create variables and functions. To declare a variable, you call:

var newVariable;

You may immediately set this new variable by calling:

var newVariable = 56;

Functions are declared like this:

function newFunction()
{
//Do Stuff Here
}

Functions can be declared with parameters by putting the parameters in the declaring line:

function newFunction(parameter1, parameter2)
{
var parameter3 = parameter1 + parameter2;
}

Curly Brackets {}

Curly brackets are used when defining a function, using if statements, or using loops to define the scope.

Conditionals

Conditionals are how we check if a statement is true or false, or meets certain criteria.

Equality

Equality is checked by using the == operator. Example:

5==5; // Would return true
5==6; // Would return false

Less Than or Greater Than

This is checked using the < operator or the > operator.

5<6; // Returns true
5>6; // Returns false
5<5; // Returns false

You can also use the <= or the >= operators to check if it is less/greater than or equal to.

5<=6; // Returns true
5>=6; // Returns false
5<=5; // Returns true

Inequality

You can check for inequality by using !=.

5!=6; // Returns true
5!=4; // Returns true
5!=5; // Returns false

Logic Gates

Logic gates allow us to modify conditionals.

And

And is done using the && operator returns true if and only if both of the conditionals are true.

true && true; // Returns true
true && false; // Returns false
false && true; // Returns false
false && false; // Returns false

Or

Or is done using the || operator (the | character is over the backslash on your keyboard). Or returns true if at least one of the statements is true.

true || true; // Returns True
true || false; // Returns True
false || true; // Returns True
false || false; // Returns False

Not

Not returns the opposite of a conditional.

!true; // Returns false
!false; // Returns true

Conditionals and Logic Gates can be combined to create complex checks. The order of operations can also be controlled through parenthesis.

(5<6) && (6>7); // Returns false
(3<2) || !(4>9); // Returns true
((5<6) && (6>7)) && !((3<2) || !(4>9)); // Returns true

The Dot .

Used to descend once down the hierarchy. We will discuss what this means later.

camelCase

There are many different methods for making names of variables and functions easier to see at a glance. CodeSpells uses a common one called camel case. In camel case, the first word is completely in lower case, then the start of any subsequent word is capitalized. Here’s some examples:

thisIsAVariableInCamelCase;
alsoInCamelCase();
testVar;

There’s no reason why you have to use camel case, but it makes things a lot easier to see and read.

BLOCK_CASE

Block case is a case we use for constants. Constants are variables which should never be changed. By putting something in block case, we can easily see if we’re doing something wrong by accident, along with seeing which variables we should modify to tune the program. Functions should never be in block case unless you want to confuse everyone. Here are some examples:

THIS_IS_IN_BLOCK_CASE;
SO_IS_THIS;
CONSTANT_VARIABLE;
TEST_VAR;

Types of Variables

Integers(Ints)

Integers (often abbreviated to Int) are whole numbers such as 0, 1, -43, and 17673. Functions that are expecting a Float will automatically convert an Int to a Float. You can call paseInt(variable) on a string or float to attempt to convert the number to an integer. When converting from a float to an integer precision will be lost.

Floats

Short for floating point numbers, these are numbers with decimals. To convert a string to a Float, use paseFloat(variable). Note: In the documentation for CodeSpells, floats are listed as doubles. In many languages there is a difference, however JavaScript treats doubles and floats the same.

Strings

Strings are sentences or phrases with words in them. There will rarely be a reason to use strings in CodeSpells. To declare a string, surround the string in parenthesis.

var x = “This is a string”;

Strings can also be added together through a process called concatenation:

var x = “This is” + “ a string”; // Sets to X to “This is a string”

Booleans

Boolean variables are always true, or false. We use them with conditionals and logic gates.

Arrays

Arrays are lists of other variables. This is useful when you need to store a lot of variables but don’t know how many. You can declare an array like this:

var arrayVar = [variable1, variable2, variable3]; // Declares an array containing variable1, variable2, and variable3.
var emptyArrayVar = []; // Declares an empty array

To add data to an array call arrayName.push(newData); this will add it at the start of the array. To remove data from the end of an array call arrayName.pop(); this will remove the last element in the array. To access data in the array, call arrayName[index]. Index is the position of an element in an array beginning at zero. So an array with 3 elements in it would have data at the index of 0, 1, and 2.

emptyArrayVar.push(“test1”);
emptyArrayVar.push(“test2”);
emptyArrayVar[1]; // Returns “test2”
emptyArrayVar[1] = “test3”; // Deletes “test2” from the index of 1 and replaces it with “test3”

Arrays are quite complex and cannot be covered thoroughly here, for a list of all functions that can be called on array, go to W3Schools.

Functions

Functions are technically variables and can be passed through functions as such.

function foo() {
// Do Something
}
var functionVar = foo;
functionVar(); // Will execute foo.

Objects

Another type of variable in JavaScript is an object. This allows you to create more complicated variable types but are much more complicated and will not be covered in this tutorial.

NaN

Not a Number. You’ll see an error containing this if you try to give a function which requires a number something that is not a number. To check if a variable is a number, we can call isNaN(variableToTest); if it returns true, the variable is not a number.

Functions

Functions make up the majority of the things you’ll be doing in your code. A function is a reusable piece of code that takes parameters and either does something, or gives you back a new variable (sometimes both). A function which does not return anything is called a void function. Void functions just do something else. A function is a void function by default. To make a function which returns something, we use the return command. Here’s an example:

function foo(input){
var x = input * 3;
return x;
}
var result = foo(5); // Result would be 15.

CodeSpells has three special functions which are automatically called at the proper time, onCreate(), onHit(), and onActivate(). These will be called at their proper times if they exist.

If Statements

One of the most basic ways to control the structure of your program is the if statement. If is formatted like this:

if(conditional){
// Do something
}

The code in the if statement will only be executed if the conditional is true. You can also make more complex if statements.

if(conditional){
// Do something
}else {
// Do something else
}

In an if else statement, the code in the else block will be executed if the conditional is false. If statements can be even more complex:

if(conditional1){
// Do something
}else if(conditional2){
// Do something else
}else if(conditional3){
// Do a third thing
}else {
// If none of the conditionals are true, do this
}

An else if block will only be called if all previous if statements were false (including previous else if statements). If all else if checks are false, then else is executed if it exists.

Loops

Loops are something quite common in programming as they allow you to do something several times. There are several types of loops.

While Loops

The easiest to use, and the most dangerous. A while loop will execute it’s contents while it’s conditional is true. The danger of this is that if the conditional never becomes false, the game will freeze. While loops are done like this:

while(conditional){
// Do something
}

Do While Loops

A slight variant on while loops, do while loops will always do at least one iteration.

do{
// Do stuff
} while(conditional);

For Loops

For loops do things a specified number of times. They look like this:

for(var varName = initialNumber; conditional; varName = varName [operator] changeAmount){
// Do something
// You can access and use varName’s current amount within the for loop
}

This looks really confusing, but it’s much easier to give two common examples.

for(i = 0; i<10; i++){
print(i);
}

This executes the function print() 10 times such that it first executes print(0), then print(1) and so on with the last one being print(9).

for(j = 10; j>0; j--){
print(j);
}

This also executes print() 10 times, but does it in reverse order. It called print(10) then print(9) and so on, with the last one being print(1).

As you can see, what the for loop does is first define the variable (i=0;), then executes the code inside the loop (print(i);). Next it applies the modification to the variable (i++) then checks whether the condition is true(i<10). If the condition is still true, it executes the code in the loop and repeats until the condition is no longer true.

You can define the variable any way, use any conditional, and use any change.

For In Loops

For in loops are a much simpler way to do for loops, but require that you have an array of data you want to iterate over. They work like this:

var data = [“data1”, “data2”, “data3”];
for(dataPiece in data){ print(dataPiece); }

This would execute print() 3 times, once as print(“data1”), once as print(“data2”) and once as print(“data3”). Not that the for in loop does not guarantee that the array will be iterated over in order.

Hierarchy

You may have notice that many functions that we call in CodeSpells are not just called, instead they are called in the format of object.function(); This is because of Objects. As stated above, this tutorial will not discuss how to create objects, but it is important to understand what they are. An object is just a variable, however many variables are more complicated than they first appear and contain their own variables and functions. These are called the children of the object. Most variables are simple variables, meaning they just store a certain type of data, and that you don’t have to access their children often. A good example of this is the integer. Others are more complex, and require you to use their child functions often, such as arrays. In most programming languages to create your own object you’d create what’s called a class. In JavaScript though, you must use a prototype. Why is this important? Well CodeSpells has several custom objects (and thus custom variable types) which you need to access and work with. For example, one type is Vector3. A Vector3 is created by calling var vector = new Vector3(x, y, z); where x, y, and z are the coordinates. It then stores this data and is treated as a single variable. You can then call vector.x at any time to retrieve the child x variable, or call vector.magnitude to get the magnitude of the vector. Vector3 and other objects are fully documented in the CodeSpells documentation so go there to learn more. Due to the fact that most of the interactions with the world of CodeSpells are done through the orb, you’ll usually be calling orb.functionName(); when you want to do something. These are the functions that cost mana to use. Orb is a global variable, meaning you can access it anywhere in your code.

Publicity of a Variable or Function

Variables and functions are not always available to everything. In some programming languages, you can manually set what can access what functions and variables. That is not the case in JavaScript. Instead, it’s automatically set which areas can access which variables. The way to figure out what can access your variable or function is to look at which block it’s in. A block of code (meaning code within the curly brackets { }) will share it’s variables and functions with all code inside that block, and all code in blocks in that block (and so on). It will not share variables and functions outside of it though. Here’s an example of this:

var variable1 = 15; // Everything can access this
function foo1(){
  print(variable1); // Works fine
  foo2(); // Works fine
  function foo2(){
   var variable2 = 26; // Can only be accessed by things inside foo2()
   print(variable1); // Works fine
  }
  print(variable2); // Will throw an error
}
function foo3(){
  print(variable1); // Works fine
  print(variable2); // Will throw an error
  foo2(); // Will throw an error
  foo1(); // Works fine
}

Conclusion

You should now be set to work with JavaScript in CodeSpells. If you don’t know how to do something in JavaScript but do know how in Blockly then create the Blockly spell and click the “JS” button on the right. This will show you the JavaScript that the Blockly spell is using. If you have any questions you should ask around on the CodeSpells forums! Lastly, a small warning. While CodeSpells is using real JavaScript, the way it uses JavaScript is different from some of the actual circumstances JavaScript is used in. Not all of them, but some of them.

If you'd like to learn more JavaScript, with a tutorial for the entire langauge rather than just CodeSpells, these tutorials are recommended:

Congratz for completing the tutorial! Happy spellcrafting!

-The CodeSpells Network