Values and Variables in JavaScript

by kirupa   |   25 January 2014

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

alert("hello, world!");

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

Now, why is knowing this important? It is important because you 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 two things you need to simplify your life working with values. You 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 spend the rest of our time on: variables. Let's learn all about them here.

Onwards!

Using Variables

A variable is basically 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!

The way to use variables is by using the var keyword followed by the name you want to give your variable:

var myText;

In this line of code, I declared a variable called myText. Right now, your 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!:

var myText = "hello, world!";

You probably shouldn't be too surprised that I ended up using that phrase haha. Anyway, let's modify our original example that you saw earlier to use our newly declared (and initialized) variable:

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

Notice that I am no longer passing in my hello, world! text to the alert function directly. Instead, I am passing in my 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 me to do is have one place in my code where hello, world! is being specified. If I wanted to change hello, world! to The dog ate my homework!, all I would have to do is just make one change to the phrase specified by the myText variable:

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

Throughout your code, wherever you referenced the myText variable, you 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 you can make a change that gets reflected everywhere is a major time saver. You'll see more, less trivial cases of the value (ha!) variables provide in subsequent examples.

More Variable Stuff

What you learned in the previous section will take you far in life. At least, in the part of your life that involves getting familiar with JavaScript. I am not going to go very deep 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 I want to cover before calling it a day.

Naming Variables

You have a lot of freedom in naming your variables however you see fit. Ignoring what names you 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.

Basically, keep the following things in mind when naming them:

  1. Your 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. Your variables can start with a letter, underscore, or the $ character. They can't start with a number.
  3. Outside of the first character, your variables can be made up of any combination of letters, underscores, numbers, and $ characters. You can also mix and match lowercase and uppercase to your heart's content.
  4. Spaces are not allowed.

I've posted some examples of valid variable names below:

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

To check if your 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, I 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. For example, you don't have to use the var keyword to declare a variable. You 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 you have a variable called myText. The only thing is that, by declaring a variable this way, you 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.

One more thing to call out. The thing you should know is that the declaration and initialization of a variable does not have to be part of the same statement (fancy way of saying line). You can break it up across multiple statements:

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

In practice, you will find yourself breaking up your declaration and initialization of variables all the time.

One more thing to call out...yes, this time I am not lying. You can change the value of a variable whenever you want to whatever you want:

var 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. You'll see more about what makes these values different later on when we talk about Objects.

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 if you already know about JavaScript functions. If you are not familiar with JavaScript functions, I strongly suggest you read about them first before venturing into the dark world of scoping which you will learn immediately after that anyway.

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.

Getting Help

If you have questions, need some assistance on this topic, or just want to chat - post in the comments below or drop by our friendly forums (where you have a lot more formatting options) and post your question. There are a lot of knowledgeable and witty people who would be happy to help you out

Share

Did you enjoy reading this and found it useful? If so, please share it with your friends:

If you didn't like it, I always like to hear how I can do better next time. Please feel free to contact me directly via e-mail, facebook, or twitter.

Brought to you by...

Kirupa Chinnathambi
I like to talk a lot - A WHOLE LOT. When I'm not talking, I've been known to write the occasional English word. You can learn more about me by going here.

Add Your Comment (or post on the Forums)

blog comments powered by Disqus

Awesome and high-performance web hosting!
BACK TO TOP
new books - yay!!!