Understanding Variables in Javascript

js.Srijan

Table of Contents

Introduction

Variables are like containers that are used to store values. It acts as a temporary storage unit in which you can store data and recall it multiple times in your program. In short, you can keep track of information using variables. The values stored in a variable can be of any data type that javascript supports. You can go through this article for a refresher on Javascript Datatypes.

Variable Declaration

You can declare a variable in Javascript using var, let and const keywords followed by the name of the variable. Javascript defines precise rules which you need to follow while naming them. We will discuss them later in the sperate section in this article.

var myVar; let myVar;

Variable Initialization

In the above example, we created a variable but haven't initialized it with any value. To initialize a variable, you need to assign it to a value using the assignment "=" operator.

var myVar = "Hello World";

If you declare a variable using let and var and did not initialize it, it will be automatically assigned an undefined value.

var myVar; //undefined let myLetVar; //undefined

const is used to define constant/immutable value, so declaration and initialization have to take place together.

const myConstVar = "Hello World"; //Hello World

Javascript will throw an error if you will try to declare a variable without initializing it.

const myConstVar; //Uncaught SyntaxError: Missing initializer in const declaration

Naming Variables

Following are the rules which we should keep in mind while naming variables in javascript:

  • Variable names are case sensitive.
  • Variable names can only consist of letters (a-z, A-Z), numbers (0-9), dollar sign ($), and underscores (_).
  • Cannot begin with numbers or only consists of numbers
  • It cannot contain whitespaces.
  • Reserved Keywords cannot be used as variable names.

Examples

let firstVar; //undefined let secondVar = 100; //100 let thirdVar = secondVar //100 let fourthVar, fifthVar; //both undefined const constVar; //Error const constVar = 100; //100

If you liked this article, please upvote and recommend it to show your support. Feel free to ask any questions in the comments below.

We publish articles on web development and technology frequently. Consider subscribing to our newsletter or follow us on our social channels (twitter, Facebook, LinkedIn).

Share this

Share on social media