# Variables

> Naming values so you can use them later.

Source: https://aminbytes.dev/bytes/programming/variables/


A **variable** is a name that points to a value. You give a value a name once, then use the name instead of repeating the value.

## Declaring a variable

Most languages have a keyword for creating a variable: (Side note: Older JavaScript uses `var`. It ignores block scope, which is one reason `let` and `const` were added.)

```js {title="variables.js"}
let count = 0;        // can change later
const name = "Amin";  // can't be reassigned

count = count + 1;
console.log(name, count); // Amin 1
```

> [!NOTE]
> In JavaScript, prefer `const` and only use `let` when the value really changes.

## Types

The *type* of a value decides what you can do with it. Some languages check types before running the code:

```go {title="main.go" hl_lines="4"}
package main

func main() {
	var age int = 30
	age = "thirty" // compile error: cannot use "thirty" (untyped string) as int
}
```

## Scope

A variable only exists inside the block where it's declared. That's its scope:

```python
def area(r):
    pi = 3.14159
    return pi * r * r

print(area(2))
print(pi)  # NameError: name 'pi' is not defined
```

> [!WARNING]
> Reusing the same name in an inner block *shadows* the outer variable. That's legal but a common source of bugs.


## Byte check

1. In JavaScript, which keyword do you use for a name that will never be reassigned?
   - `let`
   - **`const`** (correct)
   - `var`
   Prefer `const`, and use `let` only when the value really changes.

2. In the Python example, what does `print(pi)` outside `area()` do?
   - Prints `3.14159`
   - **Raises `NameError`: `pi` only exists inside the function** (correct)
   - Prints `None`
   That's scope: a variable lives only in the block where it's declared.

3. In Go, `var age int = 30` then `age = "thirty"` gives…
   - **A compile error** (correct)
   - `age` becomes a string
   - A warning at runtime
   Go checks types before running, so the mistake is caught early.


