skip to content
Dev Journal

Declare Variable

/ 2 min read

If you have 4 apples and buy 27 more, how many apples do you have ? Take a second and write your answer in your text editor. What’s your answer ?

// This ?
31
// Or this ?
4 + 27

Both answers are correct, but the second method is better because it lets JavaScript do the calculation. However, without context 4 + 27 doesn’t tell us we’re talking about apples.

A better approach is to use variables to give meaning to the numbers:

// 4 + 27
initialApples + applesBought

Using variables like initialApples and applesBought makes the code more meaningful. The process of replacing 4 with initialApples is called declaring variables.

Declaring variables

Declaring variables in JavaScript uses the syntax:

const variableName = 'value'

The key parts are the variableName, value, = sign, and the const keyword. Variable names must be one word, start with a letter, and not be a reserved keyword.

In JavaScript, = means assignment, not equality. For example:

const initialApples = 4

this assigns the value 4 to initialApples.

Evaluate expressions

To evaluate expressions before assignment, JavaScript substitutes variables and evaluates the expression, like:

const initialApples = 4
const applesBought = 27
const totalApples = initialApples + applesBought // resulting in totalApples = 31.

Use const for variables that should not change and let for those that can. Avoid using var.

Notes:

  1. Variables hold a value.
  2. Variables can hold primitives and objects.
  3. The = sign means assignment (not equality).
  4. Use camelCase for variable names and avoid reserved keywords.
  5. Prefer const over let.
  6. Don’t use var anymore.