Skip to main content

Command Palette

Search for a command to run...

Js Notes

Updated
10 min read

Variables in JavaScript

What is a Variable?

A variable is a named container used to store data in memory. It allows us to save information and use it later in our program.

For example, we can store a person's name, age, or any other value in a variable.

let name = "Abhishek";
let age = 21;

In the example above:

  • name stores a string value.

  • age stores a number.

Declaring Variables in JavaScript

JavaScript provides three keywords to declare variables:

  • let

  • const

  • var

A variable can be:

  • Declared: Creating the variable.

  • Initialized: Assigning a value to the variable.

let city;          // Declaration
city = "Delhi";   // Initialization

let country = "India"; // Declaration + Initialization

Difference Between let, const, and var

Keyword Can Reassign? Can Redeclare? Scope
let Yes No Block Scope
const No No Block Scope
var Yes Yes Function Scope

let

Use let when the value may change later.

let score = 10;
score = 20;

const

Use const when the value should remain constant.

const pi = 3.14;
// pi = 3.1415; // Error

var

var is the older way of declaring variables. It is generally avoided in modern JavaScript because it can lead to unexpected behavior.

var message = "Hello";
var message = "Hi"; // Allowed

In modern JavaScript, prefer let and const.

Rules for Naming Variables

  • Variable names can contain letters, digits, underscores (_), and dollar signs ($).

  • A variable name must begin with a letter, underscore (_), or dollar sign ($).

  • Variable names cannot start with a number.

  • Variable names are case-sensitive.

  • Reserved keywords (like if, for, class) cannot be used as variable names.

Valid Variable Names

let firstName;
let _count;
let $price;
let age2;

Invalid Variable Names

let 2age;      // Starts with a number
let first-name; // Hyphen is not allowed
let class;      // Reserved keyword

Data Types in JavaScript

A data type defines the kind of value a variable can store.

JavaScript has two main categories of data types:

  • Primitive Data Types

  • Non-Primitive (Reference) Data Types

Primitive Data Types

1. String

A sequence of characters enclosed in quotes.

let name = "Abhishek";

2. Number

Represents both integers and decimal numbers.

let age = 21;
let price = 99.99;

3. Boolean

Represents either true or false.

let isLoggedIn = true;

4. Undefined

A variable that has been declared but not assigned a value.

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

5. Null

Represents an intentional absence of value.

let selectedItem = null;

6. BigInt

Used for very large integers.

let bigNumber = 12345678901234567890n;

7. Symbol

Represents a unique value.

let id = Symbol("id");

Non-Primitive Data Types

Object

Used to store multiple values as key-value pairs.

let person = {
  name: "Abhishek",
  age: 21
};

Array

Used to store multiple values in a single variable.

let colors = ["red", "blue", "green"];

Function

A block of reusable code.

function greet() {
  console.log("Hello!");
}

Checking the Data Type

You can use the typeof operator to check the type of a value.

console.log(typeof "Hello");   // string
console.log(typeof 42);        // number
console.log(typeof true);      // boolean

Best Practices

  • Use const by default.

  • Use let when the value needs to change.

  • Avoid using var in modern JavaScript.

  • Choose meaningful and descriptive variable names.

const companyName = "OpenAI";
let totalMarks = 0;

Control Flow Statements in JavaScript

What are Control Flow Statements?

Control flow statements determine the order in which code is executed. They allow a program to make decisions, repeat tasks, and execute different blocks of code based on conditions.

In simple words, control flow statements help us control how our program runs.

Why are They Important?

  • They make programs interactive and dynamic.

  • They allow decision-making based on different situations.

  • They help automate repetitive tasks.

  • They improve code efficiency and reduce duplication.


Decision-Making Statements

if Statement

The if statement executes a block of code only when a specified condition is true.

let age = 18;

if (age >= 18) {
    console.log("You are eligible to vote.");
}

Use Case: When you want to perform an action only if a condition is satisfied.


if...else Statement

The if...else statement executes one block of code if the condition is true and another block if it is false.

let age = 16;

if (age >= 18) {
    console.log("You can vote.");
} else {
    console.log("You cannot vote yet.");
}

Use Case: When there are two possible outcomes.


if...else if...else Ladder

This is used when multiple conditions need to be checked.

let marks = 85;

if (marks >= 90) {
    console.log("Grade A");
} else if (marks >= 75) {
    console.log("Grade B");
} else if (marks >= 50) {
    console.log("Grade C");
} else {
    console.log("Fail");
}

Use Case: When you need to choose one option from many conditions.


Loops in JavaScript

Loops are used to execute a block of code repeatedly until a specified condition becomes false.

They save time and reduce repetitive code.

Basic Components of a Loop

Every loop generally has three parts:

  1. Initialization – Starting point of the loop.

  2. Condition – Determines how long the loop will run.

  3. Updation – Changes the loop variable after each iteration.


for Loop

The for loop is used when the number of iterations is known in advance.

Syntax

for (initialization; condition; updation) {
    // code to execute
}

Example

for (let i = 1; i <= 5; i++) {
    console.log(i);
}

Output: 1 2 3 4 5

How it works:

  • let i = 1 → Initialization

  • i <= 5 → Condition

  • i++ → Updation

Use Case: When you know exactly how many times the loop should run.


while Loop

The while loop executes as long as the condition remains true.

Example

let i = 1;

while (i <= 5) {
    console.log(i);
    i++;
}

Use Case: When the number of iterations is not known beforehand.


do...while Loop

The do...while loop executes the code at least once, even if the condition is false.

Example

let i = 1;

do {
    console.log(i);
    i++;
} while (i <= 5);

Important: The loop body runs first, and then the condition is checked.


Comparison of Loops

  • for loop: Best when the number of iterations is known.

  • while loop: Best when the number of iterations is unknown.

  • do...while loop: Best when the code must execute at least once.


Advantages of Control Flow Statements

  • Enable decision-making in programs.

  • Reduce code repetition.

  • Improve program flexibility.

  • Make code easier to manage and maintain.

  • Allow efficient handling of different scenarios.


Real-Life Examples

  • Checking login credentials using if...else.

  • Assigning grades using if...else if...else.

  • Displaying numbers from 1 to 10 using loops.

  • Processing items in a shopping cart.

  • Repeating tasks such as sending notifications.

Functions in JavaScript

What is a Function?

A function is a reusable block of code that performs a specific task. Instead of writing the same code multiple times, we can write it once inside a function and use it whenever needed.

Functions help make code more organized, reusable, and easier to maintain.

Why Do We Need Functions?

  • They reduce code repetition.

  • They make programs easier to read.

  • They help organize large programs into smaller parts.

  • They make debugging and maintenance simpler.

Basic Structure of a Function

A function generally has three main parts:

  1. Function Keywordfunction

  2. Function Name – the name used to identify the function

  3. Function Body – the block of code that runs when the function is called

function greet() {
    console.log("Hello!");
}

In this example:

  • function is the keyword.

  • greet is the function name.

  • The code inside { } is called the function body.

How to Call a Function

Defining a function only creates it. To execute it, we must call it.

greet();

When called, the output will be:

Hello!

Types of Functions in JavaScript

JavaScript provides several ways to create functions. The three most common are:

  • Function Declaration

  • Function Expression

  • Arrow Function


1. Function Declaration

A function declaration defines a named function using the function keyword.

function add(a, b) {
    return a + b;
}

console.log(add(2, 3));

Features

  • Has a name.

  • Can be called before it is defined (hoisting).

  • Best for general-purpose reusable functions.

Use Case

Use function declarations when you want a standard, reusable function that can be accessed throughout your code.


2. Function Expression

A function expression stores a function inside a variable.

const greetUser = function() {
    console.log("Welcome!");
};

greetUser();

Features

  • Can be anonymous (without a name).

  • Cannot be called before it is defined.

  • Useful when assigning functions to variables or passing them as values.

Use Case

Commonly used in callbacks, event handlers, and situations where functions are treated like values.


3. Arrow Function

Arrow functions provide a shorter and cleaner syntax for writing functions.

const multiply = (a, b) => {
    return a * b;
};

console.log(multiply(4, 5));

For a single expression, it can be written even shorter:

const square = num => num * num;

console.log(square(6));

Features

  • Short and concise syntax.

  • Does not have its own this.

  • Ideal for small functions.

Use Case

Best for callbacks, array methods, and short utility functions.


High-Level Difference Between the Three

Feature Function Declaration Function Expression Arrow Function
Syntax Standard Stored in variable Shortest syntax
Hoisted Yes No No
Own this Yes Yes No
Best For General reusable functions Callbacks and dynamic assignments Short callbacks and modern code

Advantages of Using Functions

  • Promote code reusability.

  • Reduce repetition.

  • Improve readability.

  • Make code modular and organized.

  • Simplify testing and debugging.

  • Easier to maintain and update.

Real-Life Example

Without functions, you would need to write the same code repeatedly.

With functions:

function sayHello(name) {
    console.log(`Hello, ${name}!`);
}

sayHello("Abhishek");
sayHello("Muskan");
sayHello("Rahul");

This saves time and keeps the code clean.

Summary

A function is a reusable block of code that performs a specific task. JavaScript supports multiple ways to create functions, including function declarations, function expressions, and arrow functions. Choosing the right type depends on your use case, but all functions help make your code cleaner, reusable, and easier to manage.