Variables (JavaScript)

Variables

> Tutorial

Variables are a fundamental concept in every programming language. They're places that keep values in memory so you can reuse them.

Variables can hold several types of values:

Declaring a variable

To use a variable, you first need to declare it. In JavaScript, you do this with the let keyword (for a value that can change) or const (for a value that never changes):

You can also assign a value to your variable right away:

Use const by default, and let only when you really need to reassign the variable. In TypeScript, you can also annotate the type: const enemy: Entity = Fight.getNearestEnemy().

Using a variable

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

Here me is your own leek, obtained with Fight.me, and enemy is the nearest enemy, obtained with Fight.getNearestEnemy(). We then pass enemy to the moveToward and useWeapon methods.

Keeping a value from one turn to the next

Your code runs again from the start every turn, so variables declared with let or const only live for the duration of the turn. To keep a value from one turn to the next, define a turn() function: the code outside turn() runs only once (when the AI loads), while turn() runs again every turn.

In the rest of the tutorial, we'll mostly write simple AIs (without turn()) that run in full every turn.

❓ Quiz

What is a variable?

A value that changes often A place to store a value

Which code declares a foo variable?

let foo = 12 const foo = 12 foo variable foo

Full AI