Sample Video Frame

05: Constants

Sometimes you need to create a variable that can never change. In programming this is usually called a "constant". A constant is more like a fact that should be the same value all the time. The concept of a constant is fairly new to JavaScript, so there are not too many guidelines on how to use them. I would say, use them sparingly until you figure out what works best. One place you will see them used is when you create functions in new JavaScript code.

The Code

const invincible = 94;
let changeme = 82;

console.log(`invincible=${invincible} but changeme=${changeme}`);

// this will work just fine
changeme = 100;

// uncomment this to see how you can't do it
// invincible = 100000;


console.log(`After change: invicible=${invincible} but changeme=${changeme}`);

As you can see here the keyword const is used to create a constant. This means a variable cannot change, so if you look at lines 9 and 10, you will see they are commented out (meaning disabled). You should remove the comment in front of line 10 to see thet error message you get. You should watch me do this in the video as it is easier to see it being done than to read about it.

What You Should See

When you run the code normally you should see this output:

$ node "code.js" 
invincible=94 but changeme=82
After change: invicible=94 but changeme=100

However, if you had the error of attempting to change the constant invincible then you should see this instead:

$ node ex05-constants.js
invincible=94 but changeme=82
/Users/zedshaw/Books/learn-js-the-hard-way/ex05-constants.js:7
invincible = 100000;
       ^

TypeError: Assignment to constant variable.
    at Object.<anonymous> (/Users/zedshaw/Books/learn-js-the-hard-way/ex05-constants..js:7:12)
    at Module._compile (module.js:660:30)
    at Object.Module._extensions..js (module.js:671:10)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
    at Function.Module.runMain (module.js:701:10)
    at startup (bootstrap_node.js:194:16)
    at bootstrap_node.js:618:3

In the video for this exercise I explain how to read this error message, and you should've seen me purposely make errors in all the videos leading up to this one. If you don't know how to read this error message yet, then be sure to study it carefully as understanding error messages is a very important skill in programming. As I mentioned before, programming is nothing but a series of failures until everything works. Maybe.


Learn JavaScript Today

Register today for the Early Access course and get the all currently available videos and lessons, plus all future modules for no extra charge.


Still Not Sure? Try the next FREE Lesson!