JavaScript Constants: Unlocking the Power of Immutability

Hello there, future JavaScript wizards! I'm thrilled to take you on a journey through the magical world of JavaScript constants. As your friendly neighborhood computer science teacher, I've seen countless students struggle with this concept, but fear not! By the end of this lesson, you'll be constant connoisseurs. So, grab your wands (keyboards), and let's dive in!

JavaScript - Constants

What are JavaScript Constants?

Imagine you're baking a cake. Once you've put it in the oven, you can't suddenly decide to change it into a pizza, right? That's kind of how constants work in JavaScript. They're like a promise you make to your code: "This value won't change, pinky swear!"

Constants are variables that, once assigned a value, cannot be reassigned. They're like the stubborn older sibling of variables – once they've made up their mind, there's no changing it!

Declaring JavaScript Constants

To declare a constant in JavaScript, we use the const keyword. It's as simple as saying, "Hey JavaScript, this thing right here? It's not going to change. Ever."

Let's look at some examples:

const PI = 3.14159;
const DAYS_IN_WEEK = 7;
const FAVORITE_COLOR = "purple";

In these examples, we've declared constants for the mathematical constant pi, the number of days in a week, and a favorite color. Once set, these values are locked in place.

Can't be Reassigned: The Immutable Nature of Constants

Now, here's where constants show their true colors. Once you've assigned a value to a constant, you can't change it. It's like trying to convince a cat to take a bath – it's just not going to happen!

const MY_AGE = 25;
console.log(MY_AGE); // Output: 25

MY_AGE = 26; // Throws an error: Assignment to a constant variable.

If you try to reassign a value to a constant, JavaScript will throw a tantrum (in the form of an error). It's saying, "Hey! You promised this wouldn't change!"

Block Scope: The Playground of Constants

Constants have what we call "block scope". Think of a block as a playground surrounded by fences. Constants can only play within their designated playground.

if (true) {
    const BLOCK_SCOPED = "I'm only available inside this block!";
    console.log(BLOCK_SCOPED); // Output: I'm only available inside this block!
}

console.log(BLOCK_SCOPED); // Throws an error: BLOCK_SCOPED is not defined

In this example, BLOCK_SCOPED is like a kid who's not allowed to leave the playground. It exists only within the if block and can't be accessed outside of it.

Constant Arrays and Objects in JavaScript: The Plot Twist

Now, here's where things get a bit tricky. When we use const with arrays and objects, the plot thickens! The constant binding is immutable, but the content of the array or object is still mutable. It's like having a constant pet – you can't change that it's your pet, but you can still teach it new tricks!

const MY_PETS = ["dog", "cat", "fish"];
console.log(MY_PETS); // Output: ["dog", "cat", "fish"]

MY_PETS.push("hamster");
console.log(MY_PETS); // Output: ["dog", "cat", "fish", "hamster"]

MY_PETS = ["parrot"]; // Throws an error: Assignment to a constant variable

In this example, we can add to our MY_PETS array, but we can't reassign it to a completely new array.

No Const Hoisting: Stay Where I Put You!

Unlike var, const doesn't get hoisted. Hoisting is like when you tell a kid to clean their room, and they say they'll do it later – but with const, there's no "later". You have to declare and initialize a constant before you use it.

console.log(HOISTED_VAR); // Output: undefined
var HOISTED_VAR = "I'm hoisted!";

console.log(NOT_HOISTED_CONST); // Throws an error: Cannot access 'NOT_HOISTED_CONST' before initialization
const NOT_HOISTED_CONST = "I'm not hoisted!";

Difference between var, let, and const

Now, let's compare our three variable declaration keywords: var, let, and const. They're like three siblings, each with their own unique personality:

Feature var let const
Scope Function scope Block scope Block scope
Hoisting Yes No No
Reassignment Yes Yes No
Redeclaration Yes No No

Which should you use among var, let, and const?

After years of teaching JavaScript, here's my two cents:

  1. Use const by default. It's like putting your variables in a safe – secure and trustworthy.
  2. Use let when you know the value will change, like a counter in a loop.
  3. Avoid var unless you're dealing with old code. It's like that flip phone in your drawer – it works, but there are better options now.

Remember, choosing between these is about communicating your intentions to other developers (including future you!).

In conclusion, constants in JavaScript are powerful tools for creating more predictable and error-resistant code. They're like the responsible adult in the room, keeping everything in order. As you continue your JavaScript journey, you'll find that using constants appropriately can make your code cleaner, more efficient, and easier to understand.

So go forth, young padawans, and may the const be with you!

Credits: Image by storyset