Numbers

What are numbers?

Numbers are numerical values used for counting, measurements, and calculations. JavaScript supports both whole numbers (integers) and decimal numbers (floats).

Benefits of using numbers?

  • Track game scores and health points
  • Store positions and coordinates
  • Perform mathematical calculations
  • Handle timing and animations
  • Manage game parameters and settings
const playerHealth = 100;
const playerScore = 2500;
const playerX = 150.5;
const playerY = 300.75;

// Basic arithmetic
const totalScore = playerScore + 500;
const damage = playerHealth - 25;
const multiplier = playerScore * 2;
const halfDamage = 50 / 2;
const remainder = 10 % 3;

console.log("Score: " + playerScore);
console.log("Position: " + playerX + ", " + playerY);
console.log("Health after damage: " + damage);

// Math methods
console.log(Math.round(playerY)); // 301
console.log(Math.floor(playerY)); // 300
console.log(Math.ceil(playerY)); // 301
console.log(Math.random()); // random 0-1

layout: post title: Numbers description: Learn about numbers permalink: /numbers author: Vihaan Budhraja —

// Distance calculation and more advanced math
const player = { x: 100, y: 100 };
const target = { x: 300, y: 150 };

const dx = target.x - player.x;
const dy = target.y - player.y;
const distance = Math.sqrt(dx * dx + dy * dy);

console.log("Distance: " + distance);

// Percentage and scaling
const maxHealth = 100;
const currentHealth = 75;
const healthPercent = (currentHealth / maxHealth) * 100;

console.log("Health: " + healthPercent + "%");

// Clamping values
function clamp(value, min, max) {
    if (value < min) return min;
    if (value > max) return max;
    return value;
}

const playerX = 500;
const screenWidth = 800;
const clampedX = clamp(playerX, 0, screenWidth);

What does this code do?

  • Calculates distance using Pythagorean theorem with Math.sqrt()
  • Computes percentage of health remaining
  • Creates clamp() function to keep values within a range
  • Essential math operations used constantly in games
  • Shows how to handle positions, health bars, and boundaries

Try It Yourself

%%js // CODE_RUNNER: numbers const health = 100; const damage = 25; const newHealth = health - damage; console.log(newHealth); console.log(Math.max(0, newHealth)); console.log(Math.sqrt(100));