30 min·advanced

Lesson 2

State & environment variables

Build a practical mental model for state & environment variables and use it in working JavaScript.

By the end, you will be able to…

  • Explain state & environment variables in your own words
  • Use state & environment variables in a small program
  • Recognize and debug a common failure mode

Build the mental model

Application state is the data that changes over time and drives what's rendered; environment variables configure how the app behaves per environment (development, production) without hardcoding secrets into source code.

Syntax and working example

Read the code from inputs to output. Predict what it prints, then run it and change one value.

Working example
Expected output: Secrets stay out of source control and version-specific per environment

Why this matters

Committing an API key directly into source code is a real, common security incident; environment variables exist specifically to prevent it.

Real-world example

Every production app's database URL and API keys are injected via environment variables, never committed to Git.

Common mistakes

  • Committing a real API key or secret directly into a source file
  • Reading environment variables inside client-side code where they'd be exposed to every visitor
  • Mixing UI state with configuration that should be an environment variable

Try it yourself

Challenge

Write buildApiUrl(base, path) that safely joins a configurable base URL with a path.

Practice

Knowledge check

Why should secrets like API keys live in environment variables instead of source code?

Summary

Keep secrets and per-environment configuration in environment variables, never hardcoded in committed source.