10 Need to Know JavaScript Concepts: Lesson 2 of 10

Declaring JavaScript Variables: var, let and const

Defining data and then manipulating that data has always been the basis of programming. What is programming without data? I assume you guessed "nothing." Data types are basically either Variables or Constants.

  • Variables can be changed
  • Constants remain the same

Where variables can be changed, constants remain the same. In this article, we will discuss the various ways of creating variables in JavaScript.

This may seem like a simple topic, but there are subtle nuances to creating variables in JavaScript that are important to know.

Table of Contents

    What are Variables?

    Variables in JavaScript are containers which hold reusable data. They are like cups filled with stuff, and this stuff can be used over and over again depending on whichever way we choose. Before ES2015, JavaScript variables were solely declared using the var keyword.

    var x;
    var y;
    var z;

    The above code corresponds to variable x, variable y, and variable y. We are declaring these variables.

    Notice we are not assigning a value to these variables just yet. We are only saying they should exist. If you were to look at the value of each variable here, it would be undefined.

    Declaring Variables in ES2015

    ES2015 is the updated version of JavaScript (also known as ECMAScript). The more lax term for ES2015 is ES6.

    In ES2015, two other ways to declare variables were introduced. They are let and const. We shall discuss these types in later parts of this lesson.

    Using Variables

    Variable are like containers in JavaScript. Using variables to store data is the foundation of the language, and it is done in three distinct parts.

    1. Variable Declaration: Here the variable is registered in its corresponding scope, the scope of a variable is simply "where the variable can be used." We'll be talking more about scope in the next lesson.

    These are examples of variable declarations:

    var x;
    var cup;
    var car;
    1. Variable Initialization: This usually occurs when a variable is declared. Here the variable is assigned a memory or space by the JavaScript engine. Because of this, once a variable is declared, it takes a value of undefined even before assignment.

    2. Variable Assignment: Variable assignment is usually the most important step when using a variable. Here the variable is assigned data which is a value using the assignment operator "=". Values in JavaScript take one of the standard JavaScript datatypes which are:
    • String
    • Number
    • Boolean
    • Null
    • Undefined
    • Any of the complex data structures (Array and Objects)
    var x         = 5;             // Number
    var name      = "Chris";       // String
    var developer = true | false;  // Boolean
    var location  = null;          // Null
    var blue;                      // undefined

    The syntax for assigning datatypes can be seen above with only strings having single or double quotes. Also boolean values are either true or false.

    Naming Variables

    When naming variables in JavaScript, there are certain rules to be followed, they are:

    • Names should begin with lowercase string.
    • Names cannot contain symbols or begin with symbols.
    • Names cannot begin with a number.
    • Names can contain a mix of uppercase strings, lowercase strings, and numbers.

    Examples of variable names are:

    // VALID
    var man;     
    var woman3;  
    var blackDog; // This is the best way to name variables with several words
    
    // INVALID
    var 1girl;   
    var -girl;   

    Multiple variables in JavaScript can also be chained, while separated by a comma.

    var x, y, z; 

    Assigning values:

    var x = 5, y = 6, z = 7;
    
    var a = 10,
      b   = 30,
      c   = 90;

    Variables in JavaScript can also evaluate simple mathematical expressions and assume its value. Here:

    var x = 5 + 10 + 2;
    console.log(x); // 17

    After the first declaration of a variable in the global scope, subsequent declarations of a variable name using var is possible.

    Here:

    var age = 22;
    var age = 25;
    
    console.log(age) // 25

    Now we shall have a look at the other variable types, let and const.

    Let

    Introduced in ES2015 (aka ES6), the variable type let shares a lot of similarities with var but unlike var has scope constraints. let is constrained to whichever scope it is declared in. Its declaration and assignment are similar to var. let was introduced to mitigate issues posed by variables scope which developers face during development.

    In short, let helps us by making it easier to see where variables live in our code.

    In declaring variables with let:

    let x;
    let x = 5;

    Multiple declarations can also be made with let:

    let x, y, z;
    let x = 50, y = 20, z = 3;

    Unlike var, variables cannot be re-declared using let, trying to do that will throw a Syntax error: Identifier has already been declared.

    let x = 20;
    let x = 50;
    
    console.log(x); // SyntaxError: identifier "x" has already been declared.

    This modification to var goes a long way to providing a level of organization while managing large data structures as it is safer knowing that your variable cannot be reassigned anywhere in its scope.

    We'll be examining more about let and scope in the next lesson.

    Const

    Also introduced in ES2015, const, is a variable type (not really, but you’ll find out now) assigned to data whose value cannot and will not be changed throughout the script. Now, this is more strict. const is also limited to the scope which it operates. const is declared like var and let.

    Use const when you are sure a variable will not be redeclared.

    const x = 20; 
    const y = 'boy';
    const z = 'developer';

    Note: A variable declared with **const** MUST be initialized.

    const x; // SyntaxError: missing initializer

    Like var and let, variables declared with const can also be chained with commas separating each variable:

    const x = 20, y = 50, man = true;

    For different variable names, these variable types can all be used together depending on the development process.

    Changing const

    You are not allowed to change the value of a variable declared with const.

    const name = 'chris';
    
    name = 'john'; // Uncaught TypeError: Assignment to constant variable.

    However, if you declare an object as const, you are able to change the properties.

    const person = {};
    
    person.name = 'chris'; // no error

    Which to Use

    When declaring variables, it is good practice to avoid using var. Always lean towards let or const based on the following rules.

    • Use let when we will be changing the value of the variable
    • Use const when you are sure that variable won't change

    Using both let and const will keep our variables in the right scope and make our code easier to manage.

    Conclusion

    In this article, we have understood how variables are declared in JavaScript, and the differences between the variable types - var, let and const.

    These variable types are unique in their own way and serve to make code development efficient, however, it is advised to use let whenever possible and const whenever the value of the variable is to remain constant.

    Chris Nwamba

    107 posts

    JavaScript Preacher. Building the web with the JS community.