My variable is not a constant and I still get an error: "Uncaught TypeError: Assignment to constant variable." Any idea why?
snake.js
export let SNAKE_SPEED = 3;
food.js
import { snakeBody, SNAKE_SPEED } from "./snake.js";
export function update() {
let head = snakeBody[0];
if (head.x == food.x && head.y == food.y) {
food.x = Math.round(Math.random() * 21);
food.y = Math.round(Math.random() * 21);
SNAKE_SPEED++;
}
}
The variable in question being SNAKE_SPEED.
Identifiers imported from other modules cannot be reassigned. To achieve something like this, you can have the other module export a function that changes it, eg:
export let SNAKE_SPEED = 3;
export const changeSnakeSpeed = newSpeed => SNAKE_SPEED = newSpeed;
import { snakeBody, SNAKE_SPEED, changeSnakeSpeed } from "./snake.js";
and then call changeSnakeSpeed(SNAKE_SPEED + 1), and SNAKE_SPEED will have changed.
Or do something like
export const incrementSnakeSpeed = () => SNAKE_SPEED++;
incrementSnakeSpeed();
Or put the often-changeable variables into a single object that can be mutated (or reassigned and retrieved again, if you prefer immutability).