DEV Community

Cover image for Understanding Variables and Data Types in JavaScript
SATYA SOOTAR
SATYA SOOTAR

Posted on

Understanding Variables and Data Types in JavaScript

So imagine this, you are going to work, and you carry a backpack. That backpack contains laptop, ID card and pen.

Just like that in Javascript the variables are like the backpack that stores some information which can be used to execute programs.

In technical term we can say "Variables are the name of the memory space where we store information".

In Javascript variables are of 3 keywords:-

  • let
  • const
  • var

let keyword

In simple terms, the let keyword in JavaScript is used to create a container for a value that can be changed later.

Example:

let name = "Satya"
console.log(name) // Satya
name = "Omm"
console.log(name) // Omm
Enter fullscreen mode Exit fullscreen mode

The most important part is that the let variable is only accessible inside the braces and is hidden from the rest of the program, which helps prevent mistakes (bugs) in your code unless it is declared in a global scope. That is why it is called block-scope.

In JavaScript, scope is the mechanism that determines the accessibility (visibility) of variables, functions, and objects in a particular part of the code.

Example:

let globalName = "satya";
function getName(){
  let localName = "omm";
  console.log(globalName);  // satya
  console.log(localName);   // omm
}
getName()
console.log(globalName);  // satya
console.log(localName);   // ReferenceError: localName is not defined

// OUTPUT
// satya
// omm
// satya
// ReferenceError: localName is not defined
Enter fullscreen mode Exit fullscreen mode

const keyword

In simple terms, the const keyword is used to create a permanent container whose value cannot be changed.

const name = "satya";
console.log(name); // satya
name = "omm";
console.log(name); // TypeError: Assignment to constant variable.

// OUTPUT
// satya
// TypeError: Assignment to constant variable.
Enter fullscreen mode Exit fullscreen mode

The important part is that this is also block-scoped, just like the let keyword.

Example:

const globalName = "satya";
function getName(){
  const localName = "omm";
  console.log(globalName);  // satya
  console.log(localName);   // omm
}
getName()
console.log(globalName);  // satya
console.log(localName);   // ReferenceError: localName is not defined

// OUTPUT
// satya
// omm
// satya
// ReferenceError: localName is not defined
Enter fullscreen mode Exit fullscreen mode

var keyword

It was the original way to create variables in JavaScript. Usually it is preferred to use let and const over var due to its confusing behaviour.

If it is declared within a function then it is block-scoped and when it is declared globally then it becomes a global variable.

Example 1: You can change the value of the variable.

var name = "satya"
console.log(name); // satya
name = "omm"
console.log(name) // omm
Enter fullscreen mode Exit fullscreen mode

Example 2:

var globalName = "satya";
function getName(){
  var localName = "omm";
  console.log(globalName);  // satya
  console.log(localName);   // omm
}
getName()
console.log(globalName);  // satya
console.log(localName);   // ReferenceError: localName is not defined
Enter fullscreen mode Exit fullscreen mode

So then what is the difference?
Unlike let and const, variables declared with var inside a block (like an if or for loop) are accessible outside that block.

if (true) {
    var blockVar = "I am not block scoped";
}
console.log(blockVar); // I am not block scoped
Enter fullscreen mode Exit fullscreen mode

Variables declared with var are hoisted to the top of their scope, meaning the declaration part is moved to the top, but not the initialization. This can result in undefined behavior if not understood properly.

console.log(hoistedVar); // undefined
var hoistedVar = "Hoisted!";
Enter fullscreen mode Exit fullscreen mode
Feature var let const
Can reassign Yes Yes No
Block scoped No Yes Yes
Function scoped Yes Yes Yes
Recommended No Yes Yes

Datatypes

Now that you know the different ways to create a variable. It's time to store items in it.

Datatypes are nothing but just what type of data that can be stored in a variable. In Javascript there are 8 datatypes. Among which 7 are primitive datatypes and 1 is non primitive datatypes.

Primitive DataTypes

A primitive data type is a basic, built-in data type provided by a programming language that represents a single and simple value.

There are 7 types of Primitive Datatypes:

1. String

This represents the textual data that is written within Double Quotes or Single Quotes. You can also say that it is the collection of characters.

Example:

let name = "satya"  // satya is a string.
let rollNum = "987" // 987 is a string as it is written within Double quotes.

console.log(typeof name)    // string
console.log(typeof rollNum) // string
Enter fullscreen mode Exit fullscreen mode

You can check the type of each data by using typeof <variablename>

2. Number

Represents both integer and floating-point numbers, including special values like Infinity and NaN (Not-a-number).

Example:

let roll = 43      // This is an integer value
let price = 10.78  // This is a floating point

console.log(typeof roll)   // number
console.log(typeof price)  // number
Enter fullscreen mode Exit fullscreen mode

3. BigInt

It is a special datatype in JavaScript used to store very large integers that the normal number type cannot safely handle.

It allows you to perform operations on whole numbers larger than the maximum safe integer for the number type, which is 2⁵³ - 1.

Example:

let bigNum = 233254355435n // By appending n to the number you can declare BigInt.
let Num = 233254355435 

console.log(typeof bigNum) // bigint
console.log(typeof Num)    // number
Enter fullscreen mode Exit fullscreen mode

4. Boolean

It represents only two possible values: true or false.

Example:

let isNumber = false;
let isAvailable = true;
console.log(typeof isNumber)    // boolean
console.log(typeof isAvailable) // boolean
Enter fullscreen mode Exit fullscreen mode

5. Undefined

A variable that has been declared but not assigned a value is automatically assigned the value undefined.

Imagine like this: you declared a variable but forgot to assign a value to it, so JavaScript will automatically assign undefined to it.

let value;
console.log(value)        // undefined
console.log(typeof value) // undefined
Enter fullscreen mode Exit fullscreen mode

The type of undefined is undefined.

6. Null

A special value that represents the intentional absence of any object value. It must be explicitly assigned.

Imagine like this: you declared a variable but do not want to store any value right now, so you assigned it null. That means the variable does not store anything, and you are the one who decided not to store the value — not JavaScript.

Example:

let data = null;
console.log(typeof null);    // object
console.log(data === null);  // true
Enter fullscreen mode Exit fullscreen mode

If you check the typeof null you will get the result object. It is a quirky behavior of JavaScript. In this case you explicitly check the value of the variable using the Triple Equal-to operator (===) which returns a boolean value (true/false).

7. Symbol

Introduced in ES6, it is a unique and immutable primitive value often used as a property key to prevent naming conflicts in objects.

Example:

let value = Symbol('hello');
console.log(typeof value) // symbol
Enter fullscreen mode Exit fullscreen mode

Non-primitive Datatypes

Non-primitive data types are reference types that store collections of data or more complex structures.

It is of 3 types:

  1. Object
  2. Array
  3. Function

Technically, Arrays and Functions are special types of Objects.

1. Object

An Object stores values in key-value pairs.

Example:

let employee = {
    name: "Satya",
    role: "Full-Stack developer",
    id: 123,
    isOnline: true,
    address: {
        planet: "Earth",
        continent: "Asia"
    }
}

console.log(typeof employee)          // object
console.log(employee.name)            // Satya
console.log(employee.address.planet)  // Earth
Enter fullscreen mode Exit fullscreen mode

2. Array

An object used for storing ordered collections of values, accessed by a numerical index.

Example:

let arr = ["satya", "susant", "susan", "john"] 
console.log(typeof arr) // object
console.log(arr)        // [ 'satya', 'susant', 'susan', 'john' ]
console.log(arr[2])     // susan
Enter fullscreen mode Exit fullscreen mode

3. Function

A callable object that executes a block of code and can be assigned to variables.

Example:

function greet(name){
    console.log(`Hello ${name}`)
}

greet("satya")  // Hello satya
Enter fullscreen mode Exit fullscreen mode

We will discuss more about functions in a later stage.

Scope in JavaScript

In the above section I have mentioned about Function scope and Block scope. What are these? Let me explain.

"The Scope defines the accessibility or visibility of variables and functions in different parts of your code."

It is generally of 3 types:

  1. Global Scope
  2. Local Scope
  3. Block Scope

1. Global Scope

A variable that is declared outside any function or block {}. Anyone can access the variable.

2. Local Scope or Function Scope

A variable or function that is declared inside a function can only be accessed inside that function. It cannot be accessed outside of that function.

3. Block Scope

A variable that is declared inside curly braces {} (for, while, if) is block-scoped. It cannot be accessed outside of that scope.

Example:

let globalVar = "I am global";

function example() {
  let functionVar = "I am inside function";

  if (true) {
    let blockVar = "I am inside block";
    console.log(globalVar);    // I am global
    console.log(functionVar);  // I am inside function
    console.log(blockVar);     // I am inside block
  }

  console.log(globalVar);    // I am global
  console.log(functionVar);  // I am inside function
  console.log(blockVar);     // ReferenceError: blockVar is not defined
}

example();

// OUTPUT
// I am global
// I am inside function
// I am inside block
// I am global
// I am inside function
// ReferenceError: blockVar is not defined
Enter fullscreen mode Exit fullscreen mode

Scope visualization


Conclusion

In this blog, we covered the foundational building blocks of JavaScript - variables and datatypes.

We explored the three ways to declare variables: var, let, and const. While var is the old way and comes with quirky behaviors like hoisting and lack of block scope, let and const are the modern, preferred approaches. Use const when the value shouldn't change, and let when it should.

We also looked at the 8 datatypes in JavaScript - 7 primitive types (String, Number, BigInt, Boolean, Undefined, Null, and Symbol) and 1 non-primitive type (Object, which also covers Arrays and Functions). Understanding datatypes helps you write cleaner, bug-free code and gives you a better sense of how JavaScript handles data under the hood.

Finally, we touched on scope - Global, Local, and Block - which controls where in your code a variable can be read or modified.

These concepts are the backbone of JavaScript. Once you're comfortable with them, everything else - functions, loops, objects, and beyond will start to make a lot more sense. Stay tuned for the next part!


Hope you liked this blog. If there's any mistake or something I can improve, do tell me. You can find me on LinkedIn and X, I post more stuff there.

Top comments (0)