Empowering you to understand your world

JavaScript Variables: A Bite-Sized Introduction

By Nicholas Brown.

Virtually every programming language has them, and they are indispensable. Variables make the world go round by enabling programmers to store and work with values of various data types quickly and easily.

Fortunately for those learning multiple programming languages, JavaScript variables are similar to the others. While there are strings, integers, booleans, arrays, and objects like there are in many other languages, they don’t have to be declared with their data types like they are in Java and C (to be clear, ‘array’ is not a data type).

  1. Introduction.
  2. Strings.
  3. Booleans.
  4. Arrays.
  5. Objects.
  6. JS Variables Are Case Sensitive.
  7. Scope.

Introduction

Before continuing, press F12 to display your browser’s console, so you can see the output of the ‘console.log’ statements used below.

First, let us use a variable to do the simplest task — Storing a value. A value can be a number or string. To be clear, a string is a data type consisting of text.

var myName = "Nicholas";

That was quite simple! That line of code tells the computer to store ‘Nicholas’ at a location in memory called myName. myName is called a variable name, and you can set it to anything you’d like, provided that you abide by JavaScript’s syntax (rules).

That line of code assigns a value to the variable myName (the equal sign is called an assignment operator). Variables are first declared using the var keyword, and then you can assign a value to them during declaration as I just did, or later (after declaring myName) like this: myName = “Nicholas”;. This must be done after the var declaration.

Example:

var myName;
myName = "Nicholas";

myName is a string, and “Nicholas” is too. You’re simply storing “Nicholas” in myName. You may not use the following symbols in JavaScript variable names: + = – / * [ ] { } | \ ^ % # @ ! ., and no spaces. JavaScript variables must start with either an underscore or letter, then numbers can be used afterwards. For example: 1variable can’t work, but variable1 is acceptable.

You can display the value stored in a variable by simply typing the variable name wherever you need it, or enter it as a parameter in whichever function it’s needed in. For example: console.log(yourvariablename);, or anothervariablename = yourvariablename + 10;

It’s best to use only letters in the names of JavaScript variables, and they should be written in camel case. This means the first letter in your variable names should be lowercase, and the first letter of the rest of the words in it should be uppercase, as shown below.

var myTestVariable = 23;

See what I did there? I assigned the value 23 to the variable myTestVariable. When assigning a numeric value to a JavaScript variable, you don’t use quotes. Quotes are only required for strings. You can optionally store a numeric value as a string, as shown below, but that isn’t recommended, as you won’t be able to make calculations with it unless you convert it to another numerical data type.

var mytestVariable = "23";

JavaScript variables make it easy to conduct calculations using familiar arithmetic operators such as + – * /. If you haven’t seen the last two before, the means multiply, and the means divide. You can use a variable to store the result of a calculation, making the calculation process almost effortless, as shown below.

var result = 2 + 6;
var multiplicationResult = 2 * 10;
var divisionResult = 2 / 10;

This means that result will store the value 8, which is the sum of 2 and 6. multiplicationResult will be equal to 20, and divisionResult will be equal to 0.2.

JavaScript Strings

The string is a data type used to store letters, numbers, and some symbols. A common reason for the use of strings is their ability to store a mixture of data types, for example:

var myString = "There are 2 bees on the wall!";
//OR
var myString2 = "Bee";
//OR 
var myString3 = "80";
//OR
var myString4 = "true";

All of the above are valid strings. Whenever you want to create such a variable in JavaScript, simply declare it using the var statement, and enclose the contents of it with quotes to clearly indicate that it is a string. Just bear in mind that you won’t be able to do arithmetic operations on the numerals a string contains as easily as you would on the numerals in an integer.

Notice what I did with string numbers 3 and 4? 80 is a string in this case, and true is also a string, but only in this case. myString4 might resemble a boolean, but it is not because it’s enclosed with quotes. Always remember that quotes are for strings. If you changed the last line to var myString4 = true;, then it would become a boolean with the value true.

JavaScript Booleans

As for booleans, those have a value of either true or false, as shown below. To a computer, a true value equates to a 1, and a false value equates to a 0.

var isTheSkyBlue = true;
var isTheSkyBlue = false;

Due to the top-down execution of JavaScript code, the last statement (instruction) will prevail over the first, therefore, the boolean’s value will be false. You can learn more about the use of booleans in the conditional statements tutorial.

JavaScript Arrays

An array is a variable, but it is a collection of multiple values, each of which has an index/position within the array. Arrays make it easier to work with many values so that you don’t have to declare too many variables. For example, an array can store 5 persons’ names.

var personsnames = []; //The square brackets indicate that it's an array.

personsnames[0] = "Jake";
personsnames[1] = "Beatrice";
personsnames[2] = "Nicholas";
personsnames[3] = "Clarissa";
personsnames[4] = "Danielle";

Each person’s name can be accessed in the ‘personsnames’ variable using its corresponding index in square braces to the left. For example, Clarissa’s index is 3. This means she is the fourth member of the array, as the first position in the array is 0.

You can display the name of the fourth member of the array in the browser console by typing the following:

console.log(personsnames[3]);

You can change the value of any one array member easily by using the binary operator ‘=‘. For example, if you’d like to change Clarissa’s name to Li, you could add the following line:

personsnames[3] = "Li";

Another way to create our array members is during declaration. We can do that by simply placing the members’ names in those empty square brackets we started out with, but in the same order:

var personsnames = ["Jake", "Beatrice", "Nicholas", "Clarissa", "Danielle"];

Jake’s index is still 0, Clarissa’s is still 3, and so forth. The array remains the same, it was just declared in a different way.

The alternative to arrays for our little task is:

var person1 = "Jake";
var person2 = "Beatrice";
var person3 = "Nicholas";
var person4 = "Clarissa";
var person5 = "Danielle";

The inconvenience isn’t only that you have to type var for every single person. It is compounded by the fact that it is not suitable for looping through the array members.

Determining The Length Of An Array

You can determine the length of an array in JavaScript using the ‘.length‘ method. For example, personsnames.length will return 5, which is the number of members in the array (members 0 to 4). The ‘.length’ method is useful when looping through arrays. It facilitates an easy way to stop the loop just in time. Here’s an example use case in which the loop stops at the end of the array:

for (i = 0; i < personsnames.length; i++) {
console.log(personsnames[i]);
}

JavaScript Objects

Another gem to discover in JavaScript is the object. Objects in JavaScript are variables. They are declared like variables, and can be parsed with refreshing ease, as shown below.

var Comment = { //This creates the object.
    userName : "nicholas",
    commentBody : "This is the comment itself.",
    userAge : 26
};

console.log(Comment.userName); //This displays the username that posted the comment.

Objects enable you to store data using fields (fields are often referred to as ‘properties’ in JavaScript. The fields above are purple, and the values are blue. In our object above, we use the ‘var’ statement to declare our object, just like we would with a variable. What’s happening above is that the username ‘nicholas’ is being stored in the userName field of the Comment object.

Another way to access a field within an object is by typing the field name in a pair of quotes and square braces, as shown below:

Comment["userName"];

Just like we do with variables, we use quotes for strings, but not for numerals. No comma is needed at the end of the last value (26). The code above uses JavaScript Object Notation (JSON).

Another common way to write JSON, so that you can identify JSON objects even more quickly, is like this:

var myObject = {Name: "Nicholas", Age: 26};

Another capability of JavaScript objects that you may need to utilize later is the assignment of a variable’s value to a field in your objects. For example, the values in the personsnames array (mentioned in the array section above) can be assigned to a field in myObject as shown below.

var myObject = {Name: personsnames[0], Age: 28};

The string stored in personsnames[0] is ‘Jake’, therefore, the value in the ‘Name’ field is now ‘Jake’.

The process of storing a variable’s value in an object is similar if it isn’t an array. So to store the value of any other variable in your object, you can simply type the variable name where the value goes, as shown below:

var myObject = {Name: yourVariable, Age: 28};

Variables In JavaScript Are Case Sensitive

JavaScript variables are case sensitive. This means that you have to consistently use the same case that you used when declaring your variables. For example, if you declared a variable with the name myvariable and stored a value of 6 in it, then you’ll find that Myvariable doesn’t contain that value. Myvariable is not the same as myvariable.

Actually, Myvariable doesn’t even exist because I didn’t declare it. This also applies to myvariable vs myVariable. They are two entirely different variables. So, to access or change the value of myvariable, you have to type myvariable exactly as it is.

The Scope Of JavaScript Variables

JavaScript variable declarations apply only to the scope they are declared in, meaning that you can only access them in the function you declared them in. If you declare your variables globally (outside of all the functions in your JavaScript file), you will be able to access them from within all of the functions. If you declare them in one of the functions, you can only access them within that function.

Variables declared globally or outside of all functions are called global variables. Generally, it’s a good practice to declare variables within the function they will be used in.

JavaScript variables can be declared with the same name twice, provided that the declarations are not in the same scope, but they will be treated as two different variables. For example: If you declare a variable in the function testFunc and also declare it globally, the in testFunc will not store values assigned to the that you declared globally, and vice versa.

Learn about functions in the Introduction To Functions tutorial. Then, you can learn more about objects at W3Schools.

Further Reading

JavaScript Tutorials: How To Set The Title Of A Page Using JavaScript

JavaScript Tutorials: How To Change Meta Tags Dynamically Using JavaScript

JavaScript Tutorial – Variables (Brown University)

Leave a Reply

Subscribe to our newsletter
Get notified when new content is published