30 Days Of JavaScript

Day 1: Simple Types

Lesson 2: Constants

In our console.log example we printed the word hello. You then manually changed it to hello world and it printed that.

What if we wanted to store those greetings and then quickly swap between them? Well, we could store each of them in a constant like this.

1const shortGreeting = "hello";
2const longGreeting = "hello World";

This stores "hello" inside a constant called shortGreeting and "hello world" in longGreeting. As constant implies, these can never be changed, they are constant and no matter what greetingShort will always hold "hello".

Now we can tell console to log either one of these like this:

Add a new line at the end that logs longGreeting.

The key thing to know about constants is that once create one you can never change its value. Hence the name constant.

Now that we have more than one line of code I'll explain some of the syntax (like grammar) of the code above.

  • All JavaScript lines should end with a semi-colon (fine, this isn't strictly true BUT the rules are so specific about what you do and don't need a semi-colon for, so you might as well always use them)
  • const names must be a single word and if you shove two words together like we have above, use a capital letter for the start of each word except the first. This is called camelCase
  • const names can't start with a number (go try it, you'll see your console stops updating)
  • A single equals is used to store (assign) whats on the right into whats on the left


Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co