TypeScript Primer

TypeScript is a rich and expressive programming language, based on JavaScript, and used in a number of applications.

You may be familiar with JavaScript through its use on the web. While Zappar's TypeScript integration shares much with web JavaScript, there are a number of differences, both in style and function, so it's important to make good use of this documentation.

This page gives a general primer on TypeScript as a language. It's the place to start if you have little or no JavaScript experience. Other pages in this documentation go into detail about how to use TypeScript to build Zappar experiences.

Comments

Comments are lines that the computer ignores when executing a program. They're a great way to document your code and make it easier to read and maintain.

In JavaScript there are two ways to comment. You can use two forward slashes to comment a single line:

// This is a single line comment

You can use /* and */ to enclose multi-line comments:

/* This comment spans
   multiple lines */

In general code is read much more often that it is written so make sure to write clear, well commented code.

Variables

Variables allow us to store and modify values. Values can be numbers, strings of text, arrays (of multiple numbers), and more.

Variables must be declared before they can be used. Variables are declared using the var keyword, like this:

var mynumber = 1.5;
var mystring = "Tequila";

Most lines of code in JavaScript, including variable declarations, have a semi-colon after them. There are some cases where they are not required - these will be highlighted as we discuss them.

You can perform mathematical operations on variables using +, -, /, *, and others.

var mynumber = 3;
var myresult = mynumber / 2; // Divide
// myresult now has the value 1.5

Strings can be concatenated with other strings using the + operator. You can even concatenate numbers and other variables into strings using +:

var myname = "Joe";
var mysentence = "My name is " + myname;
// mysentence now has the value "My name is Joe"

var myage = 35;
var mynewsentence = "My age is " + myage;
// mynewsentence now has the value "My age is 35"

When you declare a variable it has an explicit "type". TypeScript has a built-in set of types: string, boolean (true/false), number and object. You can indicate the type of a variable to TypeScript like this:

var myname : string;

Alternatively TypeScript can automatically infer the type of a variable if you give it a value immediately:

var myname = "Joe";
// myname is type string

Once a variable has been declared, TypeScript ensures it can only take values of its type:

var myname = "Joe";

myname = 5;
// Error - myname is not of type number

Variable Keywords

As well as the var keyword there is also const and let that can be used to declare variables. The examples below help to describe the differences and show when you might want to use them.

let

This declares a new variable. You can use the variable until the end of the block (i.e. the current { and } section) that it's declared in. This is called block scope.

function myExample() {
    if (true) {
        let myVariable = 5;
        myVariable = 6;
        console.log(myVariable); // <- prints '6'
    }
    console.log(myVariable); // <- this is an error, myVariable is no longer 'in scope'
}

const

This works like let except you can't change its value after it's been declared. It's useful for things that you know will never change while your script runs and want to prevent changing accidentally, e.g. 'const pi = 3.14;'.

function myExample() {
    if (true) {
        const myVariable = 5;
        myVariable = 6; // <- this is an error, myVariable can't be changed
        console.log(myVariable); // <- if the error above wasn't there then this would print '5'
    }
    console.log(myVariable); // <- this is an error, myVariable is no longer 'in scope'
}

var

Just like let this declares a new variable, but instead of it being 'block scoped', it's 'function scoped'. That means you can use the variable anywhere in the current function. We recommend using let for all variable declarations instead since the scope is easier to understand.

function myExample() {
    if (true) {
        var myVariable = 5;
        myVariable = 6;
        console.log(myVariable); // <- prints '6'
    }
    console.log(myVariable); // <- if the 'if' statement above is true then this prints '6' otherwise it prints 'undefined' since 'myVariable' is never given a value
}

Conditionals

The if statement can be used to perform different actions depending on the value of variables.

var myage = 35;
if (myage >= 18) {
  // You may be served tequila
}

Inside the "()" brackets is the "condition". If it's true then the code inside the "{}" brackets will be executed.

  • a === b

    Three equals signs means the condition will be true if a and b are both the same value.

  • a !== b

    An exclamation mark followed by two equals signs means the condition will be true if a and b are different values.

  • a > b and a >= b

    True if a is greater than b, and true if a is greater than or equal to b.

  • a < b and a <= b

    True if a is less than b, and true if a is less than or equal to b.

JavaScript also has the "double equals" equality operators == and != which you may have come across in other programming languages. However in JavaScript these operators do not ensure that the two values being compared are of the same type which can lead to some unexpected behavior. This is why we suggest sticking with the "triple equals" operators above.

You can also perform actions in the case that the condition evaluates as false:

var myage = 35;
if (myage >= 18) {
  // You may be served tequila
} else {
  // You will be served apple juice
}

Loops

Sometimes you want to perform a block of code multiple times. While you could just write the block out again and again it's often more readable to use a loop.

There are a number of ways to loop in TypeScript; perhaps the most common is the for loop. Here's a quick example:

var mytotal = 0;
for (var i = 0; i < 5; i++) {
  mytotal = mytotal + i;
}
// mytotal is now 10

The general format for a for loop is the following:

for (initial, condition, increment) {
  // Code
}
  • initial

    This term is executed before the first run of the loop. In the example above we use it to declare and initialize i to 0.

  • condition

    If the condition evaluates to true then another iteration of the loop will be performed.

  • increment

    This term will be executed at the end of each iteration of the loop. We use it in the example to increment i by 1 each time.

Arrays

In addition to numbers and strings, variables can hold arrays. Arrays have multiple elements, each of which can be a different type of value, as in this example:

var myarray = [12, "A string", 14];

You can access a single element of an array using [] brackets. Inside the brackets you give the index of the entry you'd like to access. The first entry is at index 0, the second at 1, and so on.

var myarray = [12, "A string", 14];
// myarray[0] is 12
// myarray[1] is "A string"

myarray[3] = 26;

The length parameter of an array tells you how many elements there are in an array. You can use the length to loop through all of the elements:

var myarray = [5, 2, 8];
var mysum = 0;
for (var i = 0, total = myarray.length; i < total; i++) {
  mysum = mysum + myarray[i];
}
// mysum is now 15

There are a good number of functions that you can use to manipulate arrays. Some examples that you might like to look up are push(...), for adding new entries to the end of an array; and splice(...) for removing entries from the middle of an array.

Arrays are used frequently in Zappar. The position of an object, for instance, is represented by an array of three numbers [x, y, z].

Dictionaries

Variables can hold dictionaries. These are mapping of a name to a value. Here's an example:

var mydictionary = {
  "favoriteColor": "blue",
  "favoriteNumber": 71.4
};

Once the dictionary is defined, you can add entries to, and access the entries of the dictionary in one of two ways:

var myfavoritecolor = mydictionary["favoriteColor"];
// method number 1 - myfavoritecolor will have the value "blue"

var myfavoritecolor = mydictionary.favoriteColor;
// method number 2 - myfavoritecolor will again contain the value "blue"

mydictionary.favoriteAnimal
// will return undefined

mydictionary.favoriteAnimal = "Dog";
// mydictionary.favoriteAnimal is now "Dog"

Dictionaries are useful for grouping related variables together into one place.

Functions

Sometimes it's useful to build blocks of code that can be reused in multiple circumstances. TypeScript provides functions for this purpose. Functions are declared like this:

var myfunction = function() {
  // Code goes in here
  console.log("Running inside the function!");
};

You can cause the code inside a function to be executed by "calling" it:

myfunction();
// "Running inside the function!" will have been output to the console

You can pass variables into function. These variables are then accessible inside that function as if they had been declared there. Using the return command you can provide a value back to the place that the function is called. Here's a simple example:

var myAddingFunction = function(a, b) {
  return a + b;
};

var myresult = myAddingFunction(3, 1);
// myresult is 4

It's also possible to require the variables that are passed in to a function to have a specific type:

var myAddingFunction = function(a : number, b : number) {
  return a + b;
};

var myresult = myAddingFunction(3, "hello");
// Error: "hello" is not of type number

Math Library

ZapWorks Studio's scripting environment gives you access to JavaScript's powerful Math library. There are some useful functions within the library such as random, ceil, floor and abs.

Ceil and Floor

Math.ceil() rounds a number upwards to it's nearest integer.

var myNumber = Math.ceil(1.4); // myNumber = 2

Math.floor() rounds a number downward to it's nearest integer.

var myNumber = Math.floor(1.6); // myNumber = 1

Absolute Value

Math.abs() returns the absolute value of a number, that is its non-negative value, regardless of sign.

var myNumber = Math.abs(-3); // myNumber = 3

Random

Math.random() returns a random value between 0 (inclusive) and 1 (exclusive).

// myNumber could equal any value between 0 and up to (but not including) 1
var myNumber = Math.random();

Math.random() can be used with Math.floor() to return a random number within any range.

In the below example we multiply random by 11 and then floor it to give a random whole number between 0 and 10.

var myNumber = Math.floor(Math.random() * 11);

This is only a taster of the functionality the library provides, for more on the JavaScript Math library and the functions it provides, see the following documentation:

What's Next?

This primer has only scratched the surface of what's possible with the scripting language. There are lots of resources on the web for improving and broadening your understanding of the language, here are some we recommend:

It's recommended that you continue by reading the sections following this page in the documentation in order to get a feeling for how scripting can be used to build engaging and interactive Zappar experiences.

Next section: General Principles

zapcode branded_zapcode i