Programming

How to Declare Variables in JavaScript

Anthony Grant 28-01-2020

Working with variables is one of the first things you learn as a JavaScript programmer. JavaScript is widely used in web development, so it’s important to build a good foundation of knowledge.

Advertisement

Declaring a variable in JavaScript is easy because it is a developer-friendly language. The challenge comes with the keywords used to create variables. There are three of these keywords and each will give you a different result.

If you know all three ways to declare a variable, you can make the right decisions for your app. Let’s examine these three keywords, how they work, and when they are used.

Three Ways to Declare a JavaScript Variable

There are three keywords used to declare a variable in JavaScript:

  • var
  • let
  • const

It’s easy to code a variable in JavaScript. For example, here is how to do it using the var keyword:

var myVariable = 15;

These new methods were established with JavaScript ES6 What Is ES6 and What Javascript Programmers Need to Know ES6 refers to version 6 of the ECMA Script (Javascript) programming language. Let us now look at some major changes that ES6 brings to JavaScript. Read More . Before learning about how they work, it helps to have a background on some common programming terms.

Advertisement

Key Terms

Scope

Variable scope is what parts of your program can see the variable. Some variables will be limited in scope, others are available to your entire program. Variables that are available to your entire program have a global scope.

You need to know about scope rules. As programs get bigger you will use more variables. Losing track of scope can lead to errors in your programs.

Block

Functions created in JavaScript use curly braces. The code inside the curly braces is known as a block, and you can nest as many blocks as you want inside a function.

Knowing about code blocks is key to understanding how each variable type works. Here is a visual example of blocks using a JavaScript function.

Advertisement
function blockTest(){
//This is a block
     {
       //This is a nested block
     }
};

With this in mind, let’s learn about JavaScript variables!

1. JavaScript Variable: var

When you declare a variable with var, the scope of the variable is either:

  • If declared inside a function: the enclosing function
  • If declared outside a function: global scope

This is a basic variable declaration with var. There are some comments in the code to help guide you through these definitions.

var test = 5; //Variable declaration

function varTest(){ 
console.log(test); //This prints the variable
};

varTest();

>> 5

In this example, the variable test was declared with var and assigned the value of 5. The function varTest() prints the variable in the console. The output of the function is 5.

Advertisement

The variable was declared outside the function, so it has a global scope. Even though the variable test was not declared inside the function, it works just fine.

If you change the variable inside the function, the program produces a different result.

var test = 5; 

function varTest(){ 
var test = 10;
console.log(test); 
};

varTest();

>> 10

The updated function declares a variable test inside the function, and the console reads the new value (10). The variable was declared inside a function, so the block scope overrides the global scope.

If you print the variable by itself without running the function:

Advertisement
console.log(test);
>> 5

You get the result of the global variable.

2. JavaScript Variable: Let

Using let to declare variables gives them a more specific scope. Variables declared using let are scoped to the block in which they are declared.

This is a function with multiple blocks, and it will help show the difference between var and let.

Here is a function that uses var inside multiple blocks. Take a look at the code and see if you can figure out what is going on.

function varTest(){
var test = 5;
     {
       var test = 10;
       console.log(test);
     }
console.log(test);
};
varTest();
>> 10
>> 10

Both outputs are 10.

Variables declared with var are available to the entire function. The variable test was declared as 5 in the first block. In the second block, the variable was changed to 10.

This changed the variable for the entire function. By the time the program gets to the second console.log() the variable has been changed.

Here’s the same example with comments to follow the variable:

function varTest(){
var test = 5; // Variable created
     {
       var test = 10; //Variable changed, 5 is overriden
       console.log(test); // 10
     }
console.log(test); // 10, The variable is now 10 for the entire function
};

Here’s the same example with let, watch what happens inside the blocks.

function letTest(){
let test = 5;
     {
       let test = 10;
       console.log(test);
     }
console.log(test);
};
letTest();
>> 10
>> 5

The result has changed. Here is the same code with comments. Let’s call the first block “Block A” and the second “Block B”.

function letTest(){
let test = 5; // Variable created in Block A
     {
       let test = 10; // Variable created in Block B, this is a new variable
       console.log(test); // Prints 10
     }
console.log(test); // Prints 5, since we're back to Block A
};
letTest();
>> 10
>> 5

3. JavaScript Variable: Const

Using const to declare a variable is block-scoped just like let.

When you use const to declare a variable, the value cannot be reassigned. The variable also cannot be redeclared. This should be reserved for important variables in your program that never change.

Think of const as shorthand for constant. It’s permanent, and it does not change. If you’re coming over from another programming language like Java you may already be familiar with this concept.

Let’s declare a const variable and try it out.

const permanent = 10;

Now let’s try to make some changes to the variable and see what happens. Try and change the value of the variable:

const permanent = 20;
>> Uncaught SyntaxError: Identifier 'permanent' has already been declared

The value cannot be changed, JavaScript throws an error in the console. Let’s be clever and try to use a new variable keyword to change the value:

let permanent = 20;
>> Uncaught SyntaxError: Identifier 'permanent' has already been declared

Still, no luck changing the variable. How about the same value, with a new keyword?

let permanent = 10;
>> Uncaught SyntaxError: Identifier 'permanent' has already been declared

This still does not work. Even though the value is the same, trying to change the keyword will throw an error.

That’s all there is to using the const keyword. Save it for the special variables you need to protect in the program.

Becoming a JavaScript Expert

This tutorial broke down the three keywords used to declare JavaScript variables. You will see all three of these types throughout your web development career so it’s important to get familiar.

There’s so much more to learn. Learning what JavaScript is and how it works What Is JavaScript and How Does It Work? If you're learning web development, here's what you need to know about JavaScript and how it works with HTML and CSS. Read More will prepare you for modern web development. Now that you’re comfortable with variables, learn more about how JavaScript interacts with the Document Object Model JavaScript and Web Development: Using the Document Object Model This article will introduce you to the document skeleton that JavaScript works with. Having a working knowledge of this abstract document object model, you can write JavaScript that works on any web page. Read More and try out a practical project like building a JavaScript slideshow How to Build a JavaScript SlideShow in 3 Easy Steps Today I'll be showing you how to build a Javacript slideshow from scratch -- let's jump right in! Read More .

Related topics: JavaScript, Programming Languages.

Affiliate Disclosure: By buying the products we recommend, you help keep the site alive. Read more.

Whatsapp Pinterest

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. Kenn Gorman
    January 29, 2020 at 2:29 pm

    Although it is possible with var, let and const to use the same name for different variables, I often wonder why people do. As a programming teacher (mostly middle and high school) I do my best to inform students to use not only unique variable names but informative names. Since I do not program in "the real world" I often wonder do "real programmers" use single letter variable names and/or variable names like "name" or "test"?