JavaScript Variables and Constants

JavaScript Variables and Constants

In the previous article, we got an introduction to JavaScript. As the first step in moving forward in the series, let us understand how we declare variables and constants in JavaScript. Before moving on, it's fair to understand what are variables and constants in JavaScript and why are they required. In a nutshell, variables serve as data storage containers. Primarily, high-level languages like JavaScript work with information, hence storing and retrieving information becomes basic essential, and variables play a vital role in doing so.

The identifier is a user-defined name which is assigned to that particular container so that we can store, retrieve and manipulate data according to our requirements.

Variables in JavaScript can be declared in three ways:

  • var
  • let
  • const

Though var, let, and const in JavaScript appear similar and almost interchangeable, one should be very cautious in using them according to the requirements. Let's explore them and understand their use cases well in order to use them effectively.

var in JavaScript

Syntax:

var identifier = value;

It's that simple to declare a variable in JavaScript where typecasting is not needed, unlike other high-level languages. JavaScript presumes datatype at the time of declaration and acts accordingly. For instance, consider the following case.

var a = 2; // declaration of number type
var b = 'coding minutes'; // declaration of string type
var c = '3' ; // declaration of string type

The above example demonstrates how to declare numeric variables and string variables in JavaScript. Remember, anything enclosed with ' ' and " " shall be treated as string irrespective of the information contained by those quotation marks. One has to be very cautious while dealing with these as they can be very tricky.

Do's and Don't while declaring a variable:

  • Identifier should start with an alphabet or _ (underscore).

    var num1=23 //this is correct
    var _num1=23 //this is also correct
    
  • Do not start with any other symbols such as $ or with numeric.

    var @gmail=46 //this is wrong
    var 7up=23 //this is also wrong
    
  • Do not assign any keyword as an identifier.

    var some_random_name=100 //this is correct
    var console=100 //this is wrong as console is a keyword
    
  • Do not give any space, separators like commas, or full stops between the characters.

    var coding minutes="Awesome" //incorrect
    
  • Use (_) to separate between characters. For example: "coding_minutes"

    var coding_minutes=true //correct
    
  • JavaScript is case sensitive. While declaring a variable, be cautious about upper and lower cases.

    var firstName="Mike"
    console.log(FirstName) //error as firstName is not the same as FirstName
    
  • It's a good practice to use camelCase while declaring a variable.

JavaScript is a loosely/weakly typed language. Loosely typed language is flexible with its declarations, consider the following case

var a=10;
console.log (a); // output is 10
var a="hello world";
console.log (a); // output is hello world

Shocked? Okay, hear me out! Unlike other high-level languages, where a number cannot be redefined as a string, JavaScript is different and redeclaration IS possible.

var is the oldest and is the only variable in use until 2015. let and const are two keywords introduced in the ES6/ES2015 version of JavaScript. They are "block-scope variables". This whole concept of block-scope was in the limelight after they were introduced. Before learning about let and const, it's important to understand block-scope and why they were introduced in spite of var, which was satisfying the requirement pretty well for JavaScript developers.


JavaScript var let const


Block-scope

Anything enclosed between curly brackets { } is considered a block, while the scope is apparently the extent or reach. Variables that only exist inside that block and are accessible only within those brackets are known as block-scoped variables.

Let's try to understand the block-scope concept through analogy. Let's assume you were rigorously coding in your room for hours together, you eventually became hungry and decided to grab an apple. You get up walk up to your kitchen and grab an apple. Isn't it easy? Now hypothetically you don't have any apples in your kitchen and your neighbour's kitchen has them, can you go and grab them the same way you could from your kitchen? obviously not. Because it's out of your reach/extent to grab those apples. In JavaScriptThe same goes for block scope. Your house is within your scope, but your neighbour's house is out of yours.

Consider the following code:

{
   let b = 20 ;
   const pi = 3.141;
   console.log (b); //20
   console.log (pi); //3.141
}

console.log (b) ; // ReferenceError : b is not defined at Object .
console.log (pi) ;

Observe the 'console.log' of b and pi within the block, they are accessible, but out of the block, they aren't. JavaScript will throw a reference error, and we'll explore types of errors in the later part of the series, but for now, a reference error simply means that the variable is not in existence.

let in JavaScript

Syntax:

let identifier = value;

let is a keyword introduced in JavaScript in the ES6 version to introduce the concept of block scope. To understand how let acts within the block and outside the block consider the following code

let b = ' welcome to Coding Minutes '
{
    let b = ' Coding Minutes is the best ' ;
    console.log ( b ) ; // Coding Minutes is best
}
     console.log ( b ) ; // welcome to Coding Minutes

var variable allows us to redeclare the variable and the latest declaration shall be considered. That's not the case with let, it refrains us from redeclaring let variables,

let a = 35 ;
let a = 45 ;
console.log(a) ; // SyntaxError: Identifier 'a' has already been declared

const in JavaScript

const is very strict and should be handled with care. const is introduced in the ES6 version as a block-scoped variable

Syntax:

const identifier = value;

Primary points to remember about const are, that const cannot be re-declared or re-assigned. The following piece of code explains that

const b;
b = 23;
console.log(b) // SyntaxError: Missing initializer in const declaration

In the case of var and let we can define the variable and initialise it in the later part of the code. This is called re-assigning. That's not possible in the case of const. const should be declared and initialised simultaneously.

In case of re-declaration, JavaScript will throw a reference error.

It's better to use const when you are sure of a value and you don't want to change it throughout the code. For example const pi=3.141, const g=9.8 etc.

var vs let vs const

In JavaScript, var is flexible, let is stricter while const is the strictest among the lot. Let's examine in detail:

  • var is a function scoped and var does not have any restrictions in the block and out of the block. Its behaviour remains the same.

The same is not the case with let and const, they are block-scoped and act according to their location.

  • var can be re-declared and re-assigned in JavaScript. let can be reassigned but cannot be re-declared. const cannot be re-assigned nor re-declared.
var a;
a = 20
let b;
b = 30
const c;
c = 40
{

    var a = 50;
    let b = 60;
    let b = 80;
    const c = 70;
    const c = 90;
    console.log(a); // 50
    console.log(b); // reference error
    console.log(c); // reference error
}
console.log ( a ); // 50
console.log ( b ); // 30
console.log ( c ); // syntax error
  • var is prone to error, and we may face unexpected errors. let is stable and unexpected errors are comparatively less. const is highly stable and the chances of unexpected errors are very less.

JavaScript constants best practices

Use const, otherwise prefer let as these two are less prone to error. Make sure you give readable names to variables and constants in JavaSript, as while building projects, accessing variables and constants is a real challenge.

The above discussion is just a basic part of how variables are declared and the types of variables in JavaScript. Everything in JavaScript is interconnected, in the later part of the series, when we explore concepts like lexical environment, hoisting, functions etc. we'll observe their behaviour in detail.

In the next article, we will explore different data types in JavaScript in detail.


JavaScript var let const