Variables

Variables

> Tutorial

Variables are a fundamental point in all programming languages. They are locations for storing values in memory in order to reuse them.

Variables can contain several types of values:

Declare a variable

To use a variable, it must be declared beforehand. This declaration is made using the var keyword as follows:

It is also possible to assign a value to your variable in the following way:

Use a variable

To use the value stored in a variable, we simply write its name:

In this first AI, we declare on line 5 the variable enemy, which we initialize with the value getNearestEnemy(), which corresponds to the nearest enemy.

We then use this enemy variable on lines 8* and *11 by supplying its value to the moveToward and useWeapon functions.

Global Variables

The variables declared with the var keyword have a lifespan of the turn of your leek, there is a second type of variable which retains their value during the entire duration of the fight: global variables. To declare a global variable, just use the global keyword instead of var:

Variables and global variables can be used in the same way in the code, in the rest of the tutorial we will mainly use normal variables (sometimes called local).

❓ Quiz

What is a variable?

A value that changes often A place to store a value

What code is used to declare a foo variable?

var foo = 12 var foo foo variable foo

Full AI