Contact Information

KodeBlog

We're Available 24/ 7. Drop us an email.

JavaScript Variables

A variable is a named memory location that is used to store values. You can then use the variable name when you want to access the value that you have stored in the variable. JavaScript supports the concept of variables. This reason will teach you how to work with variables in JavaScript. This lesson assumes you know the basics of HTML because we will be using the JavaScript interpreter in browsers to execute the code.

Topics to be covered

We will cover the following topics in this lesson

Lesson Prerequisites

For you to successfully complete this lesson, you should have the following requirements

  • NodeJS - we will be executing JavaScript files directly using NodeJS from the command line. Alternatively you can execute the files in the web browser but that takes a a little more time and involves working with multiple programs.
  • Web Browser - a web browser can be used as an alternative to executing JavaScript files that we will be working with.
  • Visual Studio Code - we will be using it as the code editor. It comes with a built-in terminal that will allow us to easily execute JavaScript code from within the text editor. You can also use any code editor that you prefer.
  • JavaScript Basics - this is an added advantage and not mandatory. We will explain every piece of code covered in these lessons.

Lesson Practical Examples Project Setup

This is a practical based lesson. For you to successfully work out the examples given in this lesson, you will need to setup the following directories and files

Create a new directory called javascript-variables

Open the directory javascript-variables in Visual Studio Code or your favorite code editor

Create the following files inside your project folder.

  • variables.js - this file will be used to for code dealing with the switch statement

The following visualizes our project setup

javascript-variables
-variables.js
-calculator.html

How to declare a variable in JavaScript

We basically have two ways of doing this in JavaScript. we can either use the var keyword or let keyword. The let keyword is a new one that was introduced with ECMAScript 6 specifications. This is a beginners course so we will stick to the basics and use var to declare variables. We will discusses the differences between var and let in future lessons when we are familiar with JavaScript.

The following code demonstrates how to declare a variable using JavaScript.

var name = 'John';

HERE,

  • var name = 'John'; uses the var keyword to define a variable called name that we assign the value John to. You can also assign numbers or Boolean fields to variables.

Rules for defining variables in JavaScript

The following are the rules that must be followed when defining variables in JavaScript

  1. A variable name cannot start with a number. For example, you can not name a variable 1number. This will raise an error but you can use numbers within or at the end of a variable name. For example, you can define a variable named number1 and it will work just fine. You can also start a variable name with an underscore.
  2. A variable name cannot be a reserved keyword - Reserved keywords have special meanings in JavaScript. For example, the name word var has a special meaning in JavaScript so you cannot use it to define a variable. Other reserved keywords include if,let,for etc.
  3. A variable name cannot contain spaces - The variable name should be a single word like firstName defining a variable name like first name does not work.
  4. Variable names are case sensitive - For example, if you create a variable name then you try to access it using NAME, then this will raise an error because the two variables are not the same.

The following are examples of variable names that follow the above rules.

var pi = 3.14; //starts with a letter - VALID
var _name = 'Jane'; //starts with an underscore VALID
var animal = 'Cat'; //the variable name is not a reserved word - VALID
var first_name = 'Jane' // multiple words separated by underscore - VALID

The following are examples of bad variable names

var 2number = 9; //starts with number - INVALID
var for = 4; //uses a reserved keyword - INVALID
var last name = 'Smith'; //variable name contains space - INVALID

Best Practices for Defining Variables in JavaScript

Technically all you need is follow the above rules and you are good to go but they are a few rules that if followed will make your life easier as a JavaScript Developer. The following are some of the best practices for naming variables.

  • Use descriptive names - while names such as x are accepted variable names, it is better to use descriptive name like latitude,firstName etc. This makes it easier when reading the code because the person reading the code will know what the variable is intended for unlike names like x,x2 etc.
  • User lower case names - given the case-sensitivity for variable names in JavaScript, sticking to lower case letters and making it a habit simplifies life. You will know that all variable names are lower case so mistakes become minimal. You can separate variables that have multiple works like first name using either an underscore like first_name or using camel case like firstName. The key thing is to be consistent with whichever style that you choose.
  • Do not be afraid of longer variable names - most developers love short variable names because they take less time to type. It is common to find names like fnum and snum. Variable names like first_number or second_number are longer but they make more sense compared to fnum and snum. Besides, most code editors will pick up variable names automatically so even if you have longer names, you still have to type only a few keys press enter and you are good to go.
  • Avoid names that resemble JavaScript keywords to avoid confusion. This makes its easy to tell which words are variables and which ones are reserved keywords.

The following are examples that follow the best practices defined above

var api_base_url = 'http://example.com'; //uses a descriptive name
var customers_endpoint = '/customers'; //all lower case letters
var images_storage_path = '/root/images'; // use a descriptive name

The following examples show variable names that do not follow best practices

var n = 'Jane'; //the name is not descriptive, too short
var SECONDNAME = 'Smith'; //use all upper case letters, lower case letters are prefered

JavaScript Variables Scope

The scope of the variable defines the visibility of the variable within the program. Global variables are accessible from anywhere while local variables are accessible only in the sections where they are defined. Let's now look at an example.

Let's now look at a practical example. Open the file variables.js and add the following code

var vat_percentage = 0.18; //Global scope. Can be accessed outside and inside the function

function calculateVAT(amount){
    var vat = amount * vat_percentage; //local scope accessible only inside the function
    
    return vat;
}

console.log(calculateVAT(100));

console.log(vat); //raises an error because the variable vat does not exist outside the function

HERE,

  • var vat_percentage = 18; defines a variable that has a global scope within the JavaScript file. It can be accessed outside and within functions.
  • var vat = amount * vat_percentage; defines a local variable vat that is only accessed within the function calculateVAT. Trying to access the variable vat outside the function raises an error for trying to access a variable that does not exists.
  • console.log(vat); tries to access a variable that only exists inside the function scope

Open the terminal and run the following command

node variables.js

You should be able to get the following error

18
ReferenceError: vat is not defined

JavaScript Constant Variables

Constants are variables whose value cannot be change. The value for the constant is set at the time that the variable is been declared. Trying to assign a value to a constant variable after it has already been declared raises an error.

Constants are useful when you want to work with values that should remain the same during the lifecycle of the program. For example, if you can use a constant variable to keep the API URL, database path or mathematical values such as PI or the value of gravity.

Let's now look at the a practical example. Open the file variables.js and add the following code

const api_ulr = 'http://api.example.com/v1';

console.log(api_ulr);

HERE,

  • const api_ulr = 'http://api.example.com/v1' the keyword const is used to declare a constant variable named api_url.
  • console.log(api_ulr); logs the value of the variable api_url to the console.

Open the terminal and run the following node command

node variables.js

You should be able to get the following results

http://api.example.com/v1

Let's now modify our above example as follows

const api_ulr = 'http://api.example.com/v1';

console.log(api_ulr);

api_ulr = 'http://api.example.com/v2';

HERE,

  • api_ulr = 'http://api.example.com/v2'; attempts to assign a value to the constant variable.

We will now use NodeJS to execute our JavaScript file like so

node app.js

You should be able to get the following error

api_ulr = 'http://api.example.com/v2';
        ^

TypeError: Assignment to constant variable.

Executing our code raises a TypeError exception because we are trying to assign a value to a constant variable.

JavaScript Basic Calculator

Let's now create a simple calculator using JavaScript. We will have two input boxes that will accept input then assign the values to variables and perform arithmetic operations.

Open the file calculator.html

Add the following code

<!doctype html>
<html lang="en">
    <head>
        <title>JavaScript Calculator</title>

        <!-- Bootstrap CSS -->
        <link rel="stylesheet"
            href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
            integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
            crossorigin="anonymous">
    </head>
    <body>
        <div class="container">
            <h2>JavaScript Calculator</h2>
            <form>
                <div class="form-group">
                    <label for="first_number">First Number</label>
                    <input type="text" class="form-control" id="first_number"
                        aria-describedby="emailHelp" placeholder="First Number">
                </div>
                <div class="form-group">
                    <label for="second_number">Second Number</label>
                    <input type="text" class="form-control" id="second_number"
                        aria-describedby="emailHelp" placeholder="Second
                        Number">
                </div>
                <button onclick="addNumbers()" type="button" class="btn
                    btn-primary">Add Numbers</button>
            </form>
            <p id="message">Your message will be displayed here</p>
        </div>
        <script>
            function addNumbers(){
                var first_number = document.getElementById('first_number').value;
                var second_number = document.getElementById('second_number').value;

                var result = parseInt(first_number) + parseInt(second_number);

                document.getElementById('message').innerHTML = 'The sum is ' + result;
            }
        </script>
    </body>
</html>

HERE,

  • function addNumbers(){...} defines a function addNumbers that performs the arithmetic operation
  • var first_number = document.getElementById('first_number').value; defines a variable first_number that is assigned the value of the first number.
  • var second_number = document.getElementById('second_number').value; defines a variable second_number that is assigned the value of the second number.
  • var result = parseInt(first_number) + parseInt(second_number); defines a variable result that holds the sum of first_number and second_number.

Load the file calculator.html into your web browser.

You should be able to see the following page

JS Calculator

Enter the first and second numbers then click on Add Numbers

You should be able to get the following results

JavaScript Calculator

Summary

A variable is a named memory location that we can use to store values. A variable in JavaScript should start with either a letter or an underscore, we cannot be a reserved word and should not contain spaces. Good variable names are descriptive and follow a consistent naming standard.

Author: Rodrick Kazembe

Rodrick is a developer who works on Desktop, Web and Mobile Applications. He is familiar with Python, Java, JavaScript, C++, C#, Kotlin, PHP, Python and the list goes on. Rodrick enjoys sharing knowledge especially when it comes to technology.

JavaScript in Node

JavaScript Primitive Types

Leave A Reply