EMZETT.
Login

Declaring Variables

In short: The process of introducing a new variable by name (and, depending on the language, data type) before it can be used.

In more detail: In statically typed languages (Java, C, C#), the data type has to be fixed at declaration (e.g. int age;); in dynamically typed languages (JavaScript, Python), a keyword without a type is often enough (let age;). Declaration (introducing the variable) and initialisation (giving it a starting value) can happen in one step or separately.

In Depth

int age;          // declaration without initialisation
age = 30;          // initialisation in a separate step
 
int height = 180;  // declaration and initialisation in one step

If a variable in Java is declared but not initialised, the compiler rejects local variables (inside a method) as soon as they’re read without a prior assignment — a safety net against accessing undefined memory. Class fields, by contrast, automatically get a default value (0 for numbers, false for boolean, null for objects) if no explicit initialisation is given.

In dynamically typed languages like JavaScript, the line between declaration and first assignment blurs more: let x; declares x with the value undefined, a later x = 5; is then a pure assignment, not a re-declaration. Some languages (e.g. Python) have no explicit declaration at all — a variable there simply comes into existence through its first assignment.

Scope

Where a variable is declared determines its scope — the region of code where it’s visible and usable. In Java and most modern languages, block scope applies: a variable declared inside a { } block (e.g. an if condition or a loop) only exists within that block and is no longer accessible afterwards. Older JavaScript declarations with var (unlike modern let/const), by contrast, followed function scope instead of block scope, which led to a well-known class of bugs — a variable declared with var in a loop would unintentionally “leak” out of the loop into the surrounding code, behaviour that surprised many developers and was one of the main reasons for introducing let/const in modern JavaScript.

See also: Identifiers, Constants (final), var Keyword