1. What is JavaScript and where is it used ?

JavaScript is a high-level, interpreted, dynamic programming language primarily used to make web pages interactive.

It is one of the core technologies of the web, alongside:

  • HTML → Structure

  • CSS → Styling

  • JavaScript → Behavior / Interactivity

JavaScript runs inside the browser using engines like V8 (Chrome) and can also run outside the browser using Node.js.

Why is JavaScript Needed?

Without JavaScript, websites would be static.

JavaScript allows:

  • Dynamic content updates

  • Form validation

  • Interactive UI elements

  • API calls without reloading the page

  • Real-time updates

Example:

  • Button click actions

  • Showing/hiding elements

  • Updating data without refreshing the page

Key Features of JavaScript

  1. Interpreted Language

    • Runs line by line (no separate compilation required).

  2. Dynamically Typed

    • Variable types are decided at runtime

  3. Prototype-Based

    • Uses prototypes instead of classical inheritance.

  4. First-Class Functions

    • Functions can be stored in variables, passed as arguments, returned from other functions.

  5. Event-Driven

    • Executes code based on events (click, submit, hover).

  6. Asynchronous & Non-Blocking

    • Uses callbacks, Promises, async/await.

    • Handles tasks like API calls efficiently.

  7. Cross-Platform

    • Works in browsers, servers, mobile apps, desktop apps.

2. Who created JavaScript and why ?

JavaScript was created by Brendan Eich in 1995.

He developed it while working at Netscape Communications Corporation.

 Important Fact:

  • Initially named Mocha

  • Later renamed to LiveScript

  • Finally renamed to JavaScript (for marketing reasons to associate with Java, which was popular at that time).

Main Purpose:

To add interactivity to websites.

At that time (1995), websites were completely static — built only with HTML.

Users could not:

  • Validate forms instantly

  • Respond to button clicks dynamically

  • Update content without reloading

Netscape wanted a scripting language that:

  • Runs directly in the browser

  • Is easy for developers to learn

  • Makes web pages interactive

So Brendan Eich built JavaScript.

What Problem Did It Solve?

Before JavaScript:

  • Every user action required server communication

  • Page reload was required for validation

  • User experience was slow

After JavaScript:

  • Client-side validation

  • Faster UI updates

  • Dynamic content without reload

  • Better user experience

3. Is JavaScript case-sensitive ?

Yes, JavaScript is a case-sensitive language.

This means:

  • Variable names

  • Function names

  • Keywords

  • Object properties

are treated differently based on uppercase and lowercase letters.

4. Is JavaScript compiled or interpreted ?
JavaScript is both interpreted and compiled (Just-In-Time compiled) in modern engines.

Traditional Understanding

Originally, JavaScript was considered an interpreted language because:

  • It runs line by line

  • No separate compilation step like C or C++

  • Code runs directly inside the browser

What Happens in Modern JavaScript Engines?

Modern engines like:

  • Chrome → V8

  • Firefox → SpiderMonkey

  • Edge → Chakra

use Just-In-Time (JIT) compilation.

How It Works:

  1. JavaScript code is parsed.

  2. Converted into bytecode.

  3. Frequently used code is compiled into machine code.

  4. Optimizations are applied at runtime.

Why Is JIT Used?

To improve performance.

Without JIT:

  • Slower execution

  • Less optimization

With JIT:

  • Faster performance

  • Dynamic optimization

  • Better memory usage

5. What is ECMAScript ?

ECMAScript is the standard specification on which JavaScript is based.

It defines:

  • Syntax

  • Rules

  • Features

  • Core functionalities

JavaScript is an implementation of the ECMAScript standard.

Why is ECMAScript Needed?

Before standardization:

  • Different browsers implemented JavaScript differently.

  • Code worked in one browser but failed in another.

To solve this inconsistency:

  • In 1997, JavaScript was standardized by ECMA International.

  • The standard was named ECMAScript.

This ensured:

  • Cross-browser compatibility

  • Consistent behavior

  • Structured evolution of the language

6. What is ES6 and why is it important ?

ES6 (ECMAScript 2015) is the 6th version of the ECMAScript standard, which defines how JavaScript should work.

It was released in 2015 and introduced major improvements to the language.

Why ES6 Is Important

ES6 modernized JavaScript by:

  • Making code cleaner and shorter

  • Improving readability

  • Introducing better scoping

  • Supporting modular programming

  • Enabling modern frameworks like React, Angular, and Vue

It is considered one of the biggest updates in JavaScript history.

Major Features Introduced in ES6

  1. let and const (block scope)

  2. Arrow functions

  3. Template literals

  4. Destructuring

  5. Default parameters

  6. Rest and spread operators

  7. Classes

  8. Modules (import/export)

  9. Promises

7. What are data types in JavaScript ?

Data types in JavaScript define the type of value a variable can hold.

Since JavaScript is a dynamically typed language, you don’t need to declare the type explicitly. The type is determined at runtime

Types of Data in JavaScript

JavaScript has two main categories:

  1.  Primitive Data Types

  2.  Non-Primitive (Reference) Data Types

Types of Primitive Data

  1. Number

  2. String

  3. Boolean

  4. Undefined

  5. Null

  6. BigInt

  7. Symbol

8. What are primitive and non-primitive data types ?

Primitive Data Types

Primitive data types are basic data types that store a single value directly in memory.

They are:

  • Immutable (cannot be changed)

  • Stored by value

Types of Primitive Data

JavaScript has 7 primitive types:

  1. Number

  2. String

  3. Boolean

  4. Undefined

  5. Null

  6. BigInt

  7. Symbol

Non-Primitive Data Types (Reference Types)

Definition

Non-primitive data types are complex data types that store collections of values.

They are:

  • Mutable

  • Stored by reference

Examples

  • Object

  • Array

  • Function

  • Date

  • Map

  • Set

9. What is a variable and how do you declare it ?

A variable is a container used to store data values in a program.

It allows us to:

  • Store information

  • Reuse values

  • Update data during execution

Why Are Variables Needed?

Without variables:

  • We cannot store user input

  • Cannot perform calculations

  • Cannot manipulate data

  • Cannot build dynamic applications

Variables are fundamental to programming.

 How to Declare a Variable in JavaScript?

In JavaScript, we declare variables using:

  1. var

  2. let

  3. const

10. What is the difference between var, let, and const ?

Features of var

  • Function-scoped

  • Can be redeclared

  • Can be updated

  • Hoisted (initialized as undefined)

Features of let

  • Block-scoped

  • Cannot be redeclared in same scope

  • Can be updated

  • Hoisted but not initialized (Temporal Dead Zone)

Features of const

  • Block-scoped

  • Cannot be redeclared

  • Cannot be reassigned

  • Must be initialized during declaration

Featurevarletconst
ScopeFunctionBlockBlock
RedeclareYesNoNo
ReassignYesYesNo
HoistedYesYesYes
TDZNoYesYes

11. What is scope in JavaScript ?
Scope determines where a variable is accessible in a program. If a variable is inside a scope, it can only be accessed within that scope.

Why Scope is Important?

  • Prevents variable conflicts

  • Protects data

  • Helps in memory management

  • Avoids accidental overwriting

Scope is one of the most important core concepts in JavaScript interviews.

Types of Scope in JavaScript

JavaScript has mainly:

  1. Global Scope - A variable declared outside any function or block.

  2. Function Scope - Variables declared using var inside a function are accessible only inside that function.

  3. Block Scope - Variables declared using let and const inside {} are accessible only inside that block

  4. Lexical Scope - Inner functions can access variables from their outer functions.

12. What is hoisting ?
Hoisting is JavaScript's default behavior of moving variable and function declarations to the top of their scope during the compilation phase.

why Hoisting Exists?

Before executing the code, JavaScript:

  1. Scans the code

  2. Allocates memory for variables and functions

  3. Then executes line by line

This pre-processing phase causes hoisting.

TypeHoisted?Initialized?
varYesYes (undefined)
letYesNo (TDZ)
constYesNo (TDZ)
Function DeclarationYesYes
Function ExpressionPartiallyNo
13. What is the Temporal Dead Zone ?

The Temporal Dead Zone (TDZ) is the time period between:

  • When a variable is hoisted

  • And when it is initialized

During this period, accessing the variable results in a ReferenceError.

TDZ applies to:

  • let

  • const

Why Does TDZ Exist?

TDZ was introduced in ES6 to:

  • Prevent accidental access before initialization

  • Avoid bugs caused by var hoisting

  • Encourage better coding practices


14. What is undefined ?
undefined is a primitive data type in JavaScript that represents A variable that has been declared but has not been assigned a value.

15. What is null ?
null is a primitive value in JavaScript that represents An intentional absence of any object value.

Why Do We Use null?

We use null when:

  • We want to reset a variable

  • We want to indicate “empty value”

  • We expect a value later

  • We intentionally clear data

16. Difference between null, undefined, and undeclared ?
Featureundefinednullundeclared
Declared? Yes Yes No
Assigned? No Yes No
Who assigns?JavaScriptDeveloperNobody
Type"undefined""object"Error
Accessing itGives undefinedGives nullReferenceError

17. What are truthy and falsy values ?

In JavaScript, truthy and falsy values determine how values behave in a boolean context (like inside if conditions).

When JavaScript evaluates a condition, it implicitly converts values to true or false.

Falsy Values

Falsy values are values that convert to false in a boolean context.

false
0
-0
0n // BigInt zero
"" // Empty string
null
undefined
NaN

Truthy Values

Any value that is not falsy is truthy.

true
1
-1
"hello"
"0"
[]
{}
function() {}

18. What is NaN and when does it occur ?
NaN stands for Not A Number
It is a special value in JavaScript that represents an invalid or undefined mathematical result.

 When Does NaN Occur?

NaN occurs when:

1. Performing Invalid Mathematical Operations

2. Converting Non-Numeric Strings to Number

3. Invalid Math Operations

19. What is typeof operator ?

typeof is a unary operator in JavaScript used to determine the data type of a variable or value.

It returns a string indicating the type.

Basic Syntax

Why typeof is Important?

  • Type checking

  • Debugging

  • Conditional logic

  • Validation

Common Return Values

Valuetypeof Result
Number"number"
String"string"
Boolean"boolean"
Undefined"undefined"
Null"object"
Object"object"
Array"object"
Function"function"
Symbol"symbol"
BigInt"bigint"
20. What is type coercion ?

Type coercion is the automatic or explicit conversion of one data type into another in JavaScript.

JavaScript is a dynamically typed language, so it automatically converts types when needed.

Types of Type Coercion

There are two types:

  1. Implicit Coercion (Automatic)

  2. Explicit Coercion (Manual Conversion)

Implicit Type Coercion

JavaScript automatically converts data types during operations.

Example 1: String + Number


  • + operator converts number to string.

  • String concatenation happens.

 Example 2: String - Number


  • - forces numeric conversion.

  • "5" becomes number 5.

Explicit Type Coercion

Manually converting types using functions.

Convert to Number

Convert to String

21. Implicit vs explicit type conversion ?

Type conversion (Type Coercion) means converting a value from one data type to another.

There are two types:

  1. Implicit Type Conversion (Automatic)

  2. Explicit Type Conversion (Manual)

Implicit Type Conversion (Automatic)

Definition

Implicit conversion happens automatically when JavaScript converts data types during operations.

Example 1: String + Number

  • + operator converts number to string.

  • String concatenation happens.

Example 2: String - Number


  • - operator forces numeric conversion.

  • "5" becomes number 5.

Example 3: Loose Equality (==)


  • "5" is converted to number 5.

Characteristics of Implicit Conversion

 Happens automatically
 Can cause unexpected bugs
 Common with ==, +, -, *, /
 Based on internal JavaScript rules

Explicit Type Conversion (Manual)

Definition

Explicit conversion is when the developer manually converts one data type to another using built-in functions.

Convert to Number

Convert to String

Convert to Boolean

Characteristics of Explicit Conversion

 Done intentionally
 More predictable
 Reduces bugs
 Preferred in production code

Comparison Table (Important for Interview)

FeatureImplicitExplicit
Done ByJavaScriptDeveloper
ControlNoYes
RiskHigher (unexpected behavior)Lower
Example"5" + 2Number("5")

22. Difference between == and === ?

Definition

  • == → Loose equality operator

  • === → Strict equality operator

The main difference is type coercion.

== (Loose Equality)

  • Compares values after performing implicit type conversion

  • If data types are different, JavaScript converts one type to another before comparison

  • Can produce unexpected results

=== (Strict Equality)

  • Compares both value and data type

  • Does NOT perform type coercion

  • Safer and more predictable

23. What is a conditional (ternary) operator ?

The conditional (ternary) operator is a shorthand way of writing an if...else statement.

It is called “ternary” because it takes three operands.

Syntax

How It Works

  • If the condition is true → first expression executes

  • If the condition is false → second expression executes

When to Use It

  • Simple conditions

  • Assigning values based on condition

  • Short, readable expressions

24. What are break and continue statements ?
Both break and continue are used inside loops (and switch) to control flow.

1. break Statement

Definition

The break statement is used to exit a loop or switch statement immediately.

When break executes:

  • The loop stops completely

  • Control moves to the next statement after the loop

Example (Loop)

Output:

1
2

The loop stops when i === 3.

2. continue Statement

Definition

The continue statement is used to skip the current iteration of a loop and move to the next iteration.

It does NOT stop the loop entirely.

Example

Output:

1
2
4
5

When i === 3, that iteration is skipped.

Key Difference

  • break → Stops the loop completely

  • continue → Skips current iteration, continues loop

25. What are functions in JavaScript ?

A function in JavaScript is a reusable block of code designed to perform a specific task.

Functions help in:

  • Organizing code

  • Avoiding repetition

  • Improving readability

  • Making code modular

Why Functions Are Needed

  • To execute code multiple times

  • To break complex logic into smaller parts

  • To improve maintainability

  • To follow DRY principle (Don’t Repeat Yourself)

Basic Syntax

Types of Functions in JavaScript

  1. Function Declaration
  2. Function Expression

  3. Arrow Function

  4. Anonymous Function

  5. Immediately Invoked Function Expression (IIFE)

26. Function declaration vs function expression ?

Function Declaration

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

Syntax

Characteristics

  • Has a function name

  • Fully hoisted (both declaration and definition)

  • Can be called before it appears in code

Example (Hoisting)

Function Expression

                    A function expression is when a function is assigned to a variable.

Syntax

Characteristics

  • Can be named or anonymous

  • Not fully hoisted

  • Cannot be called before definition

  • Treated like a variable

Example (No Hoisting)

Only the variable is hoisted (if var), not the function body.

27. What is an anonymous function ?

An anonymous function is a function without a name.

It is usually used:

  • As a function expression

  • As a callback

  • Inside other functions

  • In IIFE (Immediately Invoked Function Expressions)

Why Anonymous Functions Are Used

  • When the function does not need to be reused

  • When passing functions as arguments (callbacks)

  • To avoid polluting the global scope

  • In functional programming patterns

28. What are arrow functions ?

Arrow functions are a shorter syntax for writing functions, introduced in ES6 (2015).

They use the => (arrow) syntax.

Basic Syntax

Key Features

  • Shorter and cleaner syntax

  • Do NOT have their own this

  • Do NOT have their own arguments object

  • Cannot be used as constructors

  • Not hoisted like function declarations

When to Use Arrow Functions

  • Short functions

  • Callbacks

  • Functional programming

  • When you need lexical this

Avoid when:

  • You need your own this

  • You need a constructor

29. What is a first-class function ?

A first-class function means:

Functions in JavaScript are treated like any other value.

This means functions can:

  • Be assigned to variables

  • Be passed as arguments to other functions

  • Be returned from other functions

  • Be stored inside objects or arrays

JavaScript is called a first-class function language because it supports all of these.

Why This Is Important

First-class functions enable:

  • Callbacks

  • Higher-order functions

  • Closures

  • Functional programming patterns

30. What is a unary function ?

A unary function is a function that takes exactly one argument (one parameter).

“Unary” means “one”.

Syntax Example

Why Unary Functions Are Important

Unary functions are common in:

  • Functional programming

  • Array methods like map, filter

  • Mathematical operations

  • Higher-order functions

31. What is the arguments object ?

The arguments object is a special array-like object available inside regular (non-arrow) functions.

It contains all the arguments passed to the function, regardless of the number of parameters defined.

Characteristics

  • Available only inside regular functions

  • Not available in arrow functions

  • Array-like (has length and index), but not a real array

  • Does not support array methods directly (like map, filter)

32. What are default parameters ?
Default parameters allow you to assign a default value to a function parameter if no argument (or undefined) is passed.

Syntax

Important Behavior

Default value is used only when:

  • Argument is not passed

  • Argument is explicitly undefined

Why Default Parameters Are Useful

  • Prevents undefined errors

  • Makes functions safer

  • Reduces need for manual checks

  • Cleaner than old method

33. What are template literals ?

Template literals are a way to create strings using backticks ( ) instead of single or double quotes.

They were introduced in ES6 and allow:

  • String interpolation

  • Multi-line strings

  • Embedded expressions

Syntax

Why Template Literals Are Important

  • Cleaner and more readable

  • Avoid messy string concatenation

  • Useful in dynamic UI rendering

  • Common in React and Node.js

34. How to write multi-line strings using template literals ?
Template literals allow you to write multi-line strings using backticks ( ) without needing special characters like \n.

Syntax

Use backticks instead of single (') or double (") quotes.

Output:

This is line one
This is line two
This is line three

35. What is destructuring assignment ?
Destructuring assignment is a syntax that allows you to extract values from arrays or properties from objects and assign them to variables in a concise way.

Array Destructuring

Extract values from an array based on position.

Destructuring

Extract properties from objects based on property names.

36. What are enhanced object literals ?

Enhanced object literals are features introduced in ES6 that make it easier and cleaner to create objects.

They provide shorthand syntax and additional capabilities when defining objects.

1. Property Shorthand

If the variable name and property name are the same, you can omit the value repetition.

Before ES6:

ES6 Enhanced Syntax:

Method Shorthand

You can define methods without using the function keyword.

Before ES6:

ES6 Enhanced Syntax:

37. What is an array and how do you create one ?

An array is a special type of object used to store multiple values in a single variable.

  • It stores elements in an ordered list

  • Elements are accessed using index (starting from 0)

  • It can store different data types

Why Arrays Are Needed

  • To store collections of data

  • To iterate over multiple values

  • To manage lists like users, products, numbers, etc.

Important Characteristics

  • Arrays are zero-indexed

  • They are dynamic (can grow or shrink)

  • They are reference types

  • typeof array returns "object"

38. What are common array methods (map, filter, reduce) ?
These are higher-order array methods introduced in ES5.
They do not modify the original array (non-mutating) and return a new value.

1. map()

Definition

map() creates a new array by applying a function to each element of the original array.

Use Case

  • Transforming data

  • Modifying each element

Example

Each element is transformed.

2. filter()

Definition

filter() creates a new array containing only elements that satisfy a condition.

Use Case

  • Removing unwanted items

  • Selecting specific values

Example

Only elements matching the condition are kept.

3. reduce()

Definition

reduce() reduces the array to a single value by applying a function to each element.

Use Case

  • Sum of numbers

  • Counting values

  • Flattening arrays

  • Complex transformations

Syntax

Example (Sum of Numbers)


acc = accumulator
num = current value

Key Differences

  • map() → Transforms every element

  • filter() → Selects some elements

  • reduce() → Produces a single value

39. What is an object and how do you access properties ?

An object is a non-primitive data type used to store data in key–value pairs.

  • Keys are called properties

  • Values can be any data type (string, number, array, function, etc.)

  • Objects are reference types

How to Create an Object

Using Object Literal 

40. Dot notation vs bracket notation ?

Both are used to access object properties.

1. Dot Notation

Syntax

Example

Characteristics

  • Property name must be a valid identifier

  • Cannot start with a number

  • Cannot contain spaces

  • Cleaner and more readable

  • Most commonly used

 Bracket Notation

Syntax

Example

Key Differences

  • Dot notation → simple, static property access

  • Bracket notation → dynamic or special property access

  • Dot notation cannot use variables directly

  • Bracket notation can use variables

41. What are loops and types of loops ?

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

They help:

  • Avoid code repetition

  • Iterate over arrays and objects

  • Perform repetitive tasks efficiently

Types of Loops in JavaScript

  1. for loop

  2. while loop

  3. do...while loop

  4. for...of loop

  5. for...in loop

Key Differences

  • for → fixed iterations

  • while → condition-based

  • do...while → runs at least once

  • for...of → values of iterable

  • for...in → keys of object

42. for vs while vs do-while ?

All three are looping statements used to execute code repeatedly, but they differ in structure and condition checking.

for Loop

Used when the number of iterations is known in advance.

Syntax

Example

Characteristics

  • Initialization, condition, and update in one line

  • Condition checked before execution

  • Best for counter-based loops

2. while Loop

Executes code as long as the condition is true.

Syntax

Example

Characteristics

  • Condition checked before execution

  • Initialization and update written separately

  • Best when number of iterations is unknown

3. do...while Loop

Similar to while, but executes the block at least once.

Syntax

Example

Characteristics

  • Condition checked after execution

  • Runs at least one time, even if condition is false

43. What are events in JavaScript ?

Events are actions or occurrences that happen in the browser, which JavaScript can detect and respond to. They allow interaction between the user and the webpage.

Examples of Events

  • Mouse click

  • Key press

  • Form submission

  • Page load

  • Mouse hover

  • Input change

Common Event Types

  • click

  • submit

  • change

  • mouseover

  • keydown

  • load

How Events Work

JavaScript listens for an event and executes a function when the event occurs.

This function is called an event handler.

Ways to Attach Events

  1. Inline in HTML (not recommended)

  2. Using element properties (element.onclick)

  3. Using addEventListener() (recommended)

44. What is an event listener ?

An event listener is a function that waits for a specific event to occur on an element and executes a callback function when that event happens.

It allows JavaScript to respond to user interactions.

Syntax

Example

When the button is clicked, the function runs.

Parameters of addEventListener

  1. Event type (e.g., "click", "keydown")

  2. Callback function (what should run)

  3. Optional options object (like capture, once, etc.)

Why Use addEventListener Instead of onclick?

  • Can attach multiple listeners to the same element

  • Provides more control (capture, bubbling)

  • Cleaner and more flexible

45. What is DOM ?

DOM stands for Document Object Model.

It is a programming interface provided by the browser that represents an HTML document as a tree-like structure of objects.

JavaScript uses the DOM to access and manipulate HTML elements dynamically.

How DOM Works

When a webpage loads:

  1. The browser parses the HTML

  2. It creates a tree structure (DOM Tree)

  3. Each HTML element becomes an object (node)

  4. JavaScript can access and modify these nodes

46. What is BOM ?

BOM stands for Browser Object Model.

It provides objects that allow JavaScript to interact with the browser itself (not just the webpage content).

While the DOM represents the HTML document, the BOM represents the browser environment.

What Does BOM Allow You To Do?

  • Access browser window

  • Control browser navigation

  • Get browser information

  • Show alerts and dialogs

  • Work with URLs

Main BOM Object

The main object in BOM is window.

Everything in the browser runs inside the window object.

Common BOM Objects

  1. window

  2. navigator

  3. location

  4. history

  5. screen

47. What is console.log and why is it used ?

console.log() is a built-in JavaScript method used to print output to the browser's console.

It is mainly used for debugging and testing code.

Syntax

Example

Why It Is Used

  • Debugging code

  • Checking variable values

  • Tracking execution flow

  • Testing logic

  • Inspecting objects and arrays

48. What is setTimeout ?

setTimeout() is a built-in browser function that executes a function after a specified delay (in milliseconds).

It is used for scheduling code to run later.

Example

After 2000 milliseconds (2 seconds), the function runs.

Using Arrow Function

Important Points

  • The delay is in milliseconds (1000 ms = 1 second)

  • It executes only once

  • It is asynchronous (non-blocking)

  • Returns a timeout ID

49. What is setInterval ?

setInterval() is a built-in browser function that repeatedly executes a function at specified time intervals (in milliseconds).

Unlike setTimeout(), it runs continuously until stopped.

Syntax

Example

This prints the message every 2 seconds continuously.

Using Arrow Function

50. How to redirect a page using JavaScript ?

Page redirection means navigating the browser to another URL using JavaScript.

It is done using the location object (part of the BOM).

1. Using window.location.href 


  • Redirects to the given URL

  • Keeps the current page in browser history

  • User can click Back button

2. Using window.location.assign()


  • Similar to href

  • Adds entry to browser history

3. Using window.location.replace()


  • Redirects without saving current page in history

  • User cannot go back to previous page

4. Redirect After Delay

Redirects after 3 seconds.

51. What is JSON ?

JSON stands for JavaScript Object Notation.

It is a lightweight data format used for storing and exchanging data between a client and a server.

JSON is language-independent but derived from JavaScript object syntax.

Why JSON Is Used

  • Sending data between frontend and backend

  • API communication

  • Storing structured data

  • Easy to read and write

JSON Structure

JSON stores data in key–value pairs.

Important Rules of JSON

  • Keys must be in double quotes

  • Strings must use double quotes

  • No functions allowed

  • No comments allowed

52. Why do we need JSON ?

JSON is needed as a standard format to exchange data between systems, especially between frontend and backend.

It provides a lightweight and structured way to send and receive data.

Data Exchange Between Client and Server

1. Language Independent
2. Easy to Convert
3. Lightweight Compared to XML
4. Used in Modern Applications

53. JSON syntax rules ?
JSON (JavaScript Object Notation) follows strict formatting rules.
  1. Data Must Be in Key–Value Pairs
  2.  Keys Must Be in Double Quotes
  3.  Strings Must Use Double Quotes
  4.  Data Must Be One of the Valid Types
  5.  No Functions Allowed
  6. No Comments Allowed
  7.  No Trailing Commas

54. What is JSON.stringify ?

JSON.stringify() is a built-in JavaScript method that converts a JavaScript object into a JSON string.

It is mainly used to send data to a server or store data in formats like localStorage.

Syntax


  • value → The object to convert

  • replacer (optional) → Filters properties

  • space (optional) → Adds formatting/indentation

Basic Example

Why It Is Needed

  • Sending data in APIs

  • Storing objects in localStorage

  • Converting objects into transferable format

  • Logging structured data

55. How to parse JSON ?

To parse JSON means converting a JSON string into a JavaScript object.

This is done using JSON.parse().

Syntax

It takes a valid JSON string and returns a JavaScript object.

Basic Example

Now obj is a normal JavaScript object.

Why Parsing Is Needed

When data comes from:

  • APIs

  • Servers

  • localStorage

  • External files

It usually arrives as a JSON string.
We must parse it to work with it as a JavaScript object.

56. What is a cookie ?

A cookie is a small piece of data stored in the user's browser by a website.

It is used to store information about the user and send it back to the server with every HTTP request.

Why Cookies Are Used

  • User authentication (login sessions)

  • Storing user preferences

  • Tracking user activity

  • Maintaining session information

How Cookies Work

  1. Server sends a cookie to the browser

  2. Browser stores it

  3. Browser sends it back to the server with future requests

This helps the server recognize the user.

Creating a Cookie 

Reading Cookies

This returns all cookies as a single string.

Important Cookie Attributes

  • expires → Expiry date

  • max-age → Time in seconds

  • path → URL path

  • domain → Domain name

  • secure → Only sent over HTTPS

  • HttpOnly → Not accessible via JavaScript (security feature)

57. Why do we need cookies ?

Cookies are needed to store small pieces of user-specific data in the browser and maintain state between HTTP requests.

Since HTTP is stateless, cookies help websites remember users.

1. Maintaining User Sessions

When a user logs in:

  • Server creates a session

  • Sends a session ID as a cookie

  • Browser sends it back with every request

This keeps the user logged in.

2. Authentication

Cookies store authentication tokens or session IDs.

Without cookies:

  • Users would need to log in on every page request.

3. Remembering User Preferences

Cookies can store:

  • Language settings

  • Theme (dark/light mode)

  • Region selection

Example:
A website remembers your preferred language.

4. Tracking and Analytics

Used for:

  • Tracking user behavior

  • Analytics

  • Advertising personalization

5. Shopping Cart Data

E-commerce sites use cookies to:

  • Store cart items

  • Remember selections

  • Maintain checkout state

58. Cookie options (expiry, path, secure) ?

When setting a cookie, we can define additional attributes to control its behavior.

1. Expiry (expires / max-age)

Purpose

Defines how long the cookie should exist.

expires

Sets a specific expiration date.

After that date, the cookie is automatically deleted.

max-age

Sets expiry in seconds.

This cookie will expire in 1 hour (3600 seconds).

If no expiry is set:

  • It becomes a session cookie

  • Deleted when browser closes

2. Path

Purpose

Defines the URL path where the cookie is accessible.

  • path=/ → Cookie accessible across entire website

  • path=/admin → Cookie accessible only under /admin route

This restricts cookie availability.

3. Secure

Purpose

Ensures the cookie is sent only over HTTPS connections.

  • Cookie will NOT be sent over HTTP

  • Improves security

59. How to delete a cookie ?

To delete a cookie, you set its expiration date to a past date.

When the browser sees an expired cookie, it removes it.

Method 1: Using expires 

Since the date is in the past, the cookie gets deleted.

Method 2: Using max-age

Setting max-age=0 immediately deletes the cookie.

60. What is web storage ?

Web Storage is a browser feature that allows storing data in the browser as key–value pairs.

It is used to store data on the client side without sending it to the server on every request.

Types of Web Storage

  1. localStorage

  2. sessionStorage

1. localStorage

  • Stores data with no expiration time

  • Data remains even after browser is closed

  • Shared across tabs of same origin

Example:

2. sessionStorage

  • Stores data only for the session

  • Data is cleared when tab is closed

  • Not shared between tabs

Example:

Important Characteristics

  • Stores only strings

  • To store objects, use JSON.stringify()

  • To retrieve objects, use JSON.parse()