Variables and Constants

Variables

A variable is a named value that can change at any time. Imagine working on a navigation control system, you would need to have a variable called currentSpeed.

let currentSpeed=100; //miles per hour

With the above expression we have done two things:

  • Declared a variable currentSpeed.
  • Assigned it a value using an assignment operator.

So, given that it's a variable and its value can change, it can get updated as our jet cruises over the sky.

currentSpeed=110

Note: Do not use the 'let' keyword again while updating the value. 'let' is used to create/declare our variable and we have already done that.

You can create/declare a variable and ommit the initial value:

let currentAltitude;

The default value for the above will be undefined. undefined is a special global variable in javascript that is indicates an absence of a value.

It is also possible to declare multiple variables using the same let statement.

 let currentAltitude=5000,currentSpeed=100;

RUN FULL EXAMPLE HERE

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Variables Example</title>
</head>
<body>
<script>
    let currentAltitude=5000,currentSpeed=100;
    document.writeln("Altitude is "+currentAltitude+ " while speed is "+currentSpeed);
</script>
</body>
</html>

Constants

Constants were introduced in ES6(ECMAScript2015). Unlike variables constants cannot be changed after initialization. They are constant as the name suggests.

const BEST_LANDING_SPEED=50;
const ROOM_TEMPERATURE=37;

RUN FULL EXAMPLE:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Constants Example</title>
</head>
<body>
<script>
    const BEST_LANDING_SPEED=50;
    const ROOM_TEMPERATURE=37;
    document.writeln("Best landing speed is "+BEST_LANDING_SPEED+ " while room temperature is "+ROOM_TEMPERATURE);
</script>
</body>
</html>

As a convention, programmers normally use capital/uppercase letters while naming constants. However, it's just a convention and breaking it doesn't affect your code in any way. Writing constants in uppercase makes constants easily spottable in code.

Recommendation

Prefer using Constants over variables unless in situations where you would variables whose values will change during program execution. This helps in avoiding accidentally changing the value of a variable that shouldn't be changed given that constants are immutable.