Operators (JavaScript)

Operators

> Tutorial

Operators

Operators let you perform mathematical calculations or all kinds of data manipulation.

Here are the main operators:

To get the quotient of an integer division, use Math.floor(a / b).

In an expression with several operators, the operators follow the usual precedence rules, so * comes before +.

Example with different operators:

// Declare the variable a
let a
// Do a few calculations:
a = 2 + 8 // a takes the value 10
a = 5 - 4 // a takes the value 1
a = 3 * 5 // a takes the value 15
a = 6 / 2 // a takes the value 3
a = 8 % 3 // a takes the value 2

// You can combine operators:
a = 1 + 2 * 3 // a takes the value 7
a = 4 / 2 + 1 // a takes the value 3

You can also use parentheses, as in: (5 + 7) * 2.

Assignment operators

Besides the = operator, there are many assignment operators, such as +=, -=, *= etc., which combine a calculation and an assignment.

An example with *=, which performs a multiplication and stores the result in the same variable:

let x = 5
x *= 3
// x is 15

A smarter healing condition

Our current healing condition makes us heal as soon as we've lost 1 life point. We can improve it by healing only if our life is

To display the value of a variable or an expression in the fight's actions, use console.log(). Example: console.log(me.maxLife * 0.75).

❓ Quiz

What is the result of the code 10 + (5 * 7) - 20 / 4?

40 25 18 -30

What is the value of x at the end of the code let x = 10 x *= 2 x += 5 x /= 5?

5 15 22 12

What is the result of the code (true && false) || (true && true)?

1 3 true false

Full AI

const me = Fight.me

// Equip the pistol if it isn't equipped yet
if (me.weapon == null) {
	me.setWeapon(Weapon.pistol)
}

// Get the nearest enemy
const enemy = Fight.getNearestEnemy()

// Move toward the enemy
me.moveToward(enemy)

// Boosts, shield and heal
me.useChip(Chip.motivation)
me.useChip(Chip.protein)
me.useChip(Chip.helmet)

// Heal ourselves if our life is below 75% of our max life
if (me.life < me.maxLife * 0.75) {
	me.useChip(Chip.bandage)
}

// Try to shoot it!
me.useWeapon(enemy)