Skip to main content

Understanding Variables and Data Types in JavaScript

Updated 7 min readMarkdown

Hi! In this blog, i am going to discuss about JavaScript basics. This blog is beginner-friendly. If you don't know anything of JavaScript, you can still read this blog. The topics are explained with real life scenarios through which you can relate. Let's start...

What variables are and why they are needed

In below picture what would you prefer in your kitchen ?

Imagine you're preparing food in the kitchen. You have different ingredients such as sugar, salt, clove, chilli powder.

Would you keep all these ingredients scattered across your kitchen? Probably not.

Instead you store each ingredient in separate containers and put a label on it so you can easily identify and access them whenever you need.

Programming works in similar way.

When writing programs, we deal with different types of data such as numbers, string, boolean, etc.. We need a way to store this data so we can retrieve whenever we require.

This is where our variables comes into the picture.

A variable is like a labelled container that stores data. We give it a name so that they are easily accessible.

Example :

let sugar = "Sweet";
let salt = "Salty";

Here:

  • sugar and salt are variable names.
  • "Sweet" and "Salty" are the values stored in those variables.
  • We can use these variables to access their corresponding values.

Think of it this way:

Kitchen Programming
Container Variable
Label on container Variable name
Ingredient inside Value
Taking ingredients out Accessing the value

Variables are not just containers for storing data. They also allow us to reuse and update the value inside them.

How to declare variables using var, let, and const

In JavaScript, you can declare variable using three keywords : var, let, const

And all three of them are used differently based on how we reassign values, redeclare variables, and access them based on the scope.

Let's get to know about each one:

  1. var (used in dinosaurs era)
var age  = 20;
console.log(age); // 20

You can also change its value :

age = 21;
console.log(age) // 21

You can even redeclare same variable:

var age = 25;
var age = 29; 
console.log(age); // 29
  1. let

let was introduced in ES6 (2015) to provide a better way of declaring variables.

let name = "Thor";
console.log(name); // Thor

Unlike var, you can redefine the value but cannot redeclare the variable within same scope.

let thorWeapon = "Mjolnir";
    thorWeapon = "Stormbreaker";

console.log(thorWeapon); // Stormbreaker
// let thorWeapon = "Lightning Thunder" // Error : thorWeapon has already been defined
  1. const

const is used when you don't want to reassign value to variable after its declaration.

const myCountry = "India";
console.log(myCountry); // "India"

You cannot reassign or redeclare const variable.

const myCountry = "India";
myCountry = "USA"; // Error

Also, unlike var and let, const must be initialized when declared.

const myCountry; // Error

Difference between var, let and const

Feature var let const
Reassignment Yes Yes No
Redeclaration in same scope Yes No No
Block scoped No Yes Yes
Function scoped Yes Yes Yes
Must initialized during declaration No No Yes

Tips :

  • Use const by default when you don't have to reassign values.
  • Use let when you know value will be changed.
  • Though var is not deprecated but it is strongly discouraged as it pollutes the global scope.

Primitive data types (string, number, boolean, null, undefined)

Now that we understand what variables are and how to declare them. Let's understand about: Data Types

Data can be of different types. For example, we might store a character's name, their age, or whether they have completed a particular task.

const villain = "Thanos";
let infinityStones = 6;
const hasSnapped = false;

In above code, we can see there are different type of data stored in variables.

  • "Thanos" is a text.
  • 6 is a number.
  • false represents a boolean value (true or false).

Although all three are stored in variables but their values represent different type of data.

JavaScript data types broadly divided into two categories:

  1. Primitive Data Types
  2. Non-Primitive (Reference) Data Types

What are Primitive Data Types?

Primitive data types are the basic types of values in JavaScript. They represent single values rather than collection of values.

JavaScript has 7 Primitive data Types.

Data Description Example
String Represents text "Loki"
Number Represents numbers (integers and decimals) 6, 99.5
Boolean Represents true or false true, false
Undefined A variable declared but not assigned a value. undefined
Null Represents the intentional absence of a value. null
BigInt Represents integer larger than Number type can safely represent 12345678n
Symbol Represents a unique identifier Symbol("id")

Let's understand all data types with examples.

String

const character = "Kelly";
console.log(character);

Number

const hpLevel = 100.00;
console.log(hpLevel) // 100.00

Boolean

const isWinner = true;
console.log(isWinner) // true

Undefined

let score = undefined;
console.log(score) // undefined

let damageTaken;
console.log(damageTaken) // undefined

Null

let temperature = null;
console.log(temperature) // null

BigInt

const hugeNumber = 12345n; // n makes the number -> BigInt
console.log(hugeNumber) // 12345n

Symbol

const adminId = Symbol("admin@Password");
console.log(adminId) // Symbol(admin@Password)

What is scope

Story of scope starts from the variables: let, const and var.

Scope defines the accessibility of variables in different parts of your code. In simple words, it determines where you can access and use a variable.

In JavaScript, scope usually represented with "{ }" (curly braces).

Let's understand with an example:

var runs = 26;
let wickets = 2;
let overs = 12.5;

console.log(runs); // 26
console.log(wickets); // 2
console.log(overs); // 12.5

In above code we can easily predict the output.

The Problem

Imagine you want to calculate score and make a function.

var runs = 26;
let wickets = 2;
let overs = 12.5;

function calculateScore() {
    var runs = 45;
    let wickets = 4;

    console.log(runs);
    console.log(wickets);
}

calculateScore();

console.log(runs);
console.log(wickets);

What do you think will be the output?

You might wonder:

  • We already declared runs and wickets outside the function. So what happen when we declare them again in function?
  • Will the values of original variables change?
  • Can we access the variables declared inside the function from outside of it?

Let's look at the output:

45
4
26
4

Surprised? Don't worry. Let's understand this behavior.

The variables declared inside the function belongs to its own scope. They are separate from the variables declared outside the function.

  • The runs inside the function has its own value (45).
  • The runs outside the function still holds 26.
  • The same applies to wickets.

The idea behind the scope : It determines where a variable can be accessed and keeps variable within their respective boundaries.

Type of Scope

  1. Global Scope
  2. Function Scope
  3. Block Scope

Thanks for reading this blog💌. Hope it provided you useful stuff about JavaScript.

No comments yet. Be the first to comment.