Sobes.tech
Junior

What are undeclared variables?

sobes.tech AI

Answer from AI

Undeclared variables are variables that are used in code without prior declaration using the keywords var, let, or const (in JavaScript).

In strict mode ('use strict'), referencing an undeclared variable results in a runtime error (ReferenceError). In non-strict mode, such a variable is automatically created as a global, which can lead to hard-to-debug bugs.

Example:

'use strict';

function test() {
  x = 10; // ReferenceError: x is not defined
}

test();

Here, x is not declared, so an error occurs.

To avoid issues, always declare variables explicitly:

let x = 10;

This improves readability and prevents errors related to scope and unintended creation of global variables.