The KIRUPA orange logo! A stylized orange made to look like a glass of orange juice! Tutorials Books Videos Forums

Change the theme! Search!
Rambo ftw!

Customize Theme


Color

Background


Done

Table of Contents

Values and Variables in JavaScript

by kirupa   |   filed under JavaScript 101

In JavaScript, every piece of data that we provide or use is considered to contain a value. In the example we saw from our introduction, the words hello, world! might just be some words that we pass in to the alert function:

alert("hello, world!");

To JavaScript, these words have a specific representation under the covers. They are considered values. We may not have thought much about that when we were typing those words in, but when we are in JavaScript-country, every piece of data you touch is considered a value.

Now, why is knowing this important? It is important because we will be working with values a whole lot. Working with them in a way that doesn't drive you insane is a good thing. There are just two things we need to simplify our life working with values. We need to:

  1. Easily identify them
  2. Reuse them throughout your application without unnecessarily duplicating the value itself

Those two things are provided by what we are going to be spending the rest of our time on: variables. Let's learn all about them here.

Onwards!

Using Variables

A variable is an identifier for a value. Instead of typing hello, world! everytime you want to use that phrase in your application, you can assign that phrase to a variable and use that variable whenever you need to use hello, world! again. This will make more sense in a few moments - I promise!

There are several ways to use variables. For most cases, the best way is by relying on the let keyword followed by the name you want to give your variable:

let myText

In this line of code, we declare a variable called myText. Right now, our variable has simply been declared. It doesn't contain anything of value. It is merely an empty shell.

Let's fix that by initializing our variable to a value like...let's say...hello, world!:

let myText = "hello, world!";

At this point, when this code runs, our myText variable will have the value hello, world! associated with it. Let us put all of this together as part of a full example. If you still have hello_world.htm open from earlier, replace the contents of your script tag with the following...or create a new HTML file and add the following contents into it:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>An Interesting Title Goes Here</title>

  <style>

  </style>
</head>

<body>
  <script>
    let myText = "hello, world!";
    alert(myText);
  </script>
</body>

</html>

Notice that we are no longer passing in the hello, world! text to the alert function directly. Instead, we are now passing in the variable name myText instead. The end result is the same. When this script runs, an alert with hello, world! will be shown. What this change does allow us to do is have one place in our code where hello, world! is being specified. If we wanted to change hello, world! to The dog ate my homework!, all we would have to do is just make one change to the phrase specified by the myText variable:

let myText = "The dog ate my homework!";
alert(myText);

Throughout our code, wherever we referenced the myText variable, we will now see the new text appear. While this is hard to imagine for something as simple as what we have right now, for larger applications, this convenience with having just one location where we can make a change that gets reflected everywhere is a major time saver. You'll see more, less trivial cases of the value (🤣) variables provide in subsequent examples.

More Variable Stuff

What we learned in the previous section will take us far in life. At least, it will in the parts of our life that involve getting familiar with JavaScript. We won't dive too much further into variables here, for we'll do all of that as part of future tutorials where the code is more complex and the importance of variables is more obvious. With that said, there are a few odds and ends that we should cover before calling it a day.

Naming Variables

We have a lot of freedom in naming our variables however we see fit. Ignoring what names we should give things based on philosophical / cultural / stylistic preferences, from a technical point of view, JavaScript is very lenient on what characters can go into a variable name.

This leniency isn't infinite, so we should keep the following things in mind when naming our variables:

  1. Variables can be as short one character, or they can be as long as you want - think thousands and thousands...and thousands of characters.
  2. Variables can start with a letter, underscore, or the $ character. They can't start with a number.
  3. Outside of the first character, our variables can be made up of any combination of letters, underscores, numbers, and $ characters. We can also mix and match lowercase and uppercase to our heart's content.
  4. Spaces are not allowed.

Below are some examples of valid variable names:

let myText;
let $;
let r8;
let _counter;
let $field;
let thisIsALongVariableName_butItCouldBeLonger;
let __$abc;
let OldSchoolNamingScheme;

To see if a variable name is valid, check out the really awesome and simple JavaScript Variable Name Validator.

Outside of valid names, there are other things to focus on as well. In the near future, we will touch upon those other things such as naming conventions and how many people commonly name variables and other things that you identify with a name.

More on Declaring and Initializing Variables

One of the things you will learn about JavaScript is that it is a very forgiving and easy-to-work with language. That has some implications, but we'll party tonight and deal with the consequences.

Declaring a Variable is Optional

For example, we don't have to use the let keyword to declare a variable. We could just do something as follows:

myText = "hello, world!";
alert(myText);

Notice the myText variable is being used without formally being declared with the var keyword. While not recommended, this is completely fine. The end result is that we have a variable called myText. The only thing is that, by declaring a variable this way, we are declaring it globally. Don't worry if the last sentence makes no sense. We'll look at what globally means when talking about Variable Scope.

Declaring and Initializing on Separate Lines is Cool

There is one more thing to call out, and that is this: the declaration and initialization of a variable does not have to be part of the same statement. We can break it up across multiple statements:

let myText;
myText = "hello, world!";
alert(myText);

In practice, we will find ourselves breaking up our declaration and initialization of variables all the time.

Changing Variable Values and the const Keyword

Lastly, we can change the value of a variable declared via let to whatever we want whenever we want:

let myText;
myText = "hello, world!";
myText = 99;
myText = 4 * 10;
myText = true;
myText = undefined;
alert(myText);

If you have experience working with languages that are more strict and don't allow variables to store a variety of data types, this leniency is one of the features people both love and hate about JavaScript. With that said, JavaScript does provide a way for you to restrict the value of a variable from being changed after you initialize it. That restriction comes in the form of the const keyword that we can declare and initialize our variables with:

const siteURL = "https://www.google.com";
alert(siteURL);

By relying on const, we can't change the value of siteURL to something other than https://www.google.com. JavaScript will complain if we try to do that. There are some gotchas with using the const keyword, but it does a great job overall in preventing accidental modifications of a variable. For those pesky gotchas, we'll cover those in bits and pieces when the time is right.

Jump Ahead: Variable Scoping

Now that you know how to declare and initialize variables, a very important topic is that of visibility. You need to know when and where a variable you declared can actually be used in your code. The catch-all phrase for this is known as variable scope. If you are really curious to know more about it, you can jump ahead and read the Variable Scope tutorial.

Conclusion

That's all there is to the basics of declaring and using variables. I initially tried to elegantly combine variables, functions, and variable scoping into one tutorial, but I failed. I only covered variables and didn't even bother covering functions and variable scoping. Please don't tell my Asian parents that.

Up Next: Functions

Just a final word before we wrap up. If you have a question and/or want to be part of a friendly, collaborative community of over 220k other developers like yourself, post on the forums for a quick response!

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends