DEV Community

Cover image for Understanding Variables and Data Types in JavaScript
Abhishek sahni
Abhishek sahni

Posted on • Originally published at jsoperators.hashnode.dev

Understanding Variables and Data Types in JavaScript

In this blog we are going to learn basic fundamentals of programming. We are exploring variables and datatypes in javascript.

First we try to understand variables. So what are variables.

Variables : Variables are containers that stores and manage some data.

There are three ways to declare a variable in javaScript. let , var and const .

syntax to declare a variable :

let variableName = value;
Enter fullscreen mode Exit fullscreen mode
var variableName = value;
Enter fullscreen mode Exit fullscreen mode
const variableName = value;
Enter fullscreen mode Exit fullscreen mode

You can use let ,var and const according to your use case.

What is scope : Scope defines where a variable can be access in program.

Global Scope : A variable declared outside any function can be access anywhere in the program.

Function Scope : A variable declared inside a function cannot be accessed outside that function.

Block Scope : Block scope was introduced in ES6.

Variables declared with let and const can only be accessed inside the block {} where they are declared.

Example : A variable declared with let or const inside an if-else statement is accessible only within that block.

But variables declared with var ignore block scope boundaries and are scoped to the nearest function.

Basic difference between var, let, and const :

var : var is function-scoped.

It can be re-declared and re-assigned (updated).

var x = 10;
var x = 20; // re-declaration allowed

x = 30;     // re-assignment allowed

console.log(x); // 30
Enter fullscreen mode Exit fullscreen mode

let : let is block-scoped.

It can be re-assigned (updated), but cannot be re-declared in the same scope.

let y = 10;

// let y = 20; ❌ Error (cannot re-declare in same scope)

y = 30; // re-assignment allowed

console.log(y); // 30
Enter fullscreen mode Exit fullscreen mode

const : const is also block-scoped.

It cannot be re-declared and cannot be re-assigned.

const z = 10;

// const z = 20; ❌ Error (cannot re-declare)
// z = 30;       ❌ Error (cannot re-assign)

console.log(z); // 10
Enter fullscreen mode Exit fullscreen mode

Naming Rules (Identifiers) to declare a variable :

Variable names must follow these strict rules to be valid:

  • variable names must begin with letter , underscore (_)  or dollar ($). Subsequent characters can also include digits.

  • variables name are case sensitive in javaScript means variable name age and Age are two different variables.

  • you cannot use reserved words like if-else , for loop and function.

Now you understand variables let's dive the datatypes :

Data types : From the name itself, you can understand that a data type means the type of data.

JavaScript is a dynamically typed language.

It means that data types are determined at runtime, not before the execution of the program. unlike many other language we don't need to declare data type first.

Lets take an example :

const data = 12
Enter fullscreen mode Exit fullscreen mode

12 is a data it can be age of any person. But what is the type of 12. It is number.

Here, 12 is a piece of data. It can represent the age of a person.

But what is the type of 12? It is a number.

So, "number" is the data type of 12.

Data types are categorised into two types.

  1. Primitive Data Types

  2. Non-Primitive Data Types

Data types are categorised according to how it stores in memory and how we can access it.

Primitive Data Types : There are seven primitive data types.

  1. Number : The Number data type is used to represent both integer and floating-point values.

    Unlike many other languages, JavaScript does not have separate data types like int, float, or double.

    const age = 21;       // integer
    const price = 99.99;  // floating-point
    
    console.log(typeof age);   // "number"
    console.log(typeof price); // "number"
    
  2. String : A String is used to represent a collection of characters (text data).

    Immutability:

    Once a string is created, it cannot be changed. Methods like toUpperCase() return a new string instead of modifying the original one.

    const name = "john";
    
    const upperName = name.toUpperCase();
    
    console.log(name);       // "john" (original remains same)
    console.log(upperName);  // "JOHN" (new string)
    
  3. Boolean : The Boolean data type represents only two values: true or false.


    These values are case-sensitive and must be written in lowercase.


    TRUE or FALSE are not considered valid Boolean values.

const isLoggedIn = true;
const hasPermission = false;

console.log(typeof isLoggedIn);   // "boolean"
console.log(typeof hasPermission); // "boolean"
Enter fullscreen mode Exit fullscreen mode
  1. null : null is used to represent an intentional absence of value (empty).

    It does not mean 0; it means that no value is assigned.

    let user = null;
    
    console.log(user);        // null
    console.log(typeof user); // "object" (this is a known JavaScript quirk)
    
  2. Undefined : From the name itself , you can understand it represent the value is not defined. When a variable is declared but not assigned any value. It is undefined.

    let name;
    
    console.log(name);        // undefined
    console.log(typeof name); // "undefined"
    
  3. BigInt : BigInt is used to represent very large integers that are beyond the limit of the normal Number type.

    In JavaScript, the Number type can safely store integers only up to:

    2^53 - 1

    For values larger than this, we use BigInt.

    const bigNumber = 1234567890123456789012345678901234567890n;
    
    console.log(bigNumber);        // very large number
    console.log(typeof bigNumber); // "bigint"
    
  4. Symbol : symbol is used to represent unique value.

    It is immutable once created It cannot be changed. It always return a unique value even if the description is same.

    Non-Enumerable: When used as a key in an object, Symbols do not show up in standard loops like for...in or methods like Object.keys().

    const sym1 = Symbol("id");
    const sym2 = Symbol("id");
    
    console.log(sym1 === sym2); // false (always unique)
    

Non-Primitive Data Types : There are two types of non-primitive data types.

Arrays and Objects are non-primitive. They are mutable because they share the reference in the memory. if we change in non-primitive data type it will affect original data.

Arrays : Arrays are collection of multiple data in contiguous order in a single variable.

const numbers = [1 , 2 , 3 , 4]

console.log(numbers);

// output : [1 , 2 , 3 , 4]
Enter fullscreen mode Exit fullscreen mode

Arrays are dynamically sized can grow and shrink its length automatically when you add or remove a value from array.

Array can store multiple datatypes.

const multipleData = [1 , 2 , "email", true};
Enter fullscreen mode Exit fullscreen mode

But in javaScript array is actually a type of object.

When you check its type using typeof, it returns "object".

const numbers = [1, 2, 3];

console.log(typeof numbers); // "object"
Enter fullscreen mode Exit fullscreen mode

So how to check it is an array :

Since typeof() is not reliable for array you can use Array.isArray()

const arr = [1, 2, 3];

console.log(Array.isArray(arr)); // true
Enter fullscreen mode Exit fullscreen mode

If return value is true it is an array otherwise it is not an array.

Objects : An Object in JavaScript is used to store data in the form of key–value pairs.

Each key (also called a property) is associated with a value, which can be of any data type.

const user = {
  name: "john",
  age: 21,
  isStudent: true
};

console.log(user.name); // "john"
console.log(user.age);  // 21
Enter fullscreen mode Exit fullscreen mode
  • Values can be of any type (number, string, array, function, etc.)

  • You can access values using dot notation or bracket notation

Bracket notation Example :

const user = {
  name: "john",
  age: 21
};

console.log(user["name"]); // "john"
Enter fullscreen mode Exit fullscreen mode

Summary : In this blog, we explored the fundamentals of JavaScript, starting with variables and their scope. We also understood the concept of dynamic typing and how JavaScript determines data types at runtime.

Further, we discussed variables using var, let, and const, along with their differences in scope, re-declaration, and re-assignment. The concept of scope—global, function, and block scope—was explained with simple examples to build a strong foundation.

We also explore primitive and non-primitive data types.

By the end of this blog, you should have a clear understanding of how JavaScript handles data and variables, which is essential for writing clean and error-free code.

Top comments (0)