0% found this document useful (0 votes)
3 views32 pages

Javascript

JavaScript is a scripting language used for creating interactive web pages, allowing manipulation of HTML and CSS, handling user input, and server communication. It features various data types, control structures like loops, and functions that enhance code reusability and organization. Additionally, JavaScript supports event handling through event listeners, enabling responsive user interfaces.

Uploaded by

collins kombe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views32 pages

Javascript

JavaScript is a scripting language used for creating interactive web pages, allowing manipulation of HTML and CSS, handling user input, and server communication. It features various data types, control structures like loops, and functions that enhance code reusability and organization. Additionally, JavaScript supports event handling through event listeners, enabling responsive user interfaces.

Uploaded by

collins kombe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

About JavaScript

JavaScript is a scripting language used primarily to create interactive, dynamic behavior


on web pages. It runs in the browser and interacts with HTML and CSS to:

 Respond to user input (e.g., clicks, typing).


 Manipulate the DOM (e.g., show/hide elements, change content).
 Communicate with servers using AJAX/fetch.
 Control animations, validate forms, and much more.

Example:

<button onclick="changeText()">Click Me</button>


<p id="demo">Hello!</p>

<script>
function changeText() {
document.getElementById("demo").innerText = "You clicked the button!";
}
</script>

Differences between var, let, and const in JavaScript.

Keywor Scope Reassignm Redeclarat Hoistin Use When?


d ent ion g

var Functio Yes Yes Yes Legacy code,


n rarely used

let Block Yes No No When the


value
changes

const Block No No No When the


value doesn't
change
(constants,
functions,
arrays)

Examples:

var x = 5;
let y = 10;
const z = 15;

y = 20; // allowed
z = 30; // Error: Assignment to constant variable
Different data types available in JavaScript.

JavaScript has primitive and reference data types.

Primitive Types:

 String: "Hello"
 Number: 42
 Boolean: true, false
 Null: null (intentional "no value")
 Undefined: variable declared but not assigned
 Symbol: unique identifier (ES6+)
 BigInt: large integers (e.g., 123n)

Reference Types:

 Object: { name: "Alice" }


 Array: [1, 2, 3]
 Function: function() {}

Example:

let name = "John"; // string


let age = 30; // number
let isActive = true; // boolean
let data = null; // null
let user; // undefined
let scores = [10, 20]; // array
let person = { name: "A" }; // object

Arithmetic operators in JavaScript.

Operat Description Example (a = 10, b =


or 5)

+ Addition a + b → 15

- Subtraction a - b →5

* Multiplication a * b → 50

/ Division a / b →2

% Modulus a % b →0
(remainder)

++ Increment a++ → 11
-- Decrement b-- →4

Example:

let x = 8;
x = x + 2; // x is now 10
x *= 3; // x is now 30

Difference between a while loop and a do-while loop in JavaScript

Loop Condition Minimum Executions


Type Checked

while Before the loop 0 (if condition is false


initially)

do-while After the loop At least 1 (runs once even if


false)

Example: while loop:

let i = 0;
while (i < 3) {
console.log(i);
i++;
}
// Output: 0 1 2

Example: do-while loop:

let i = 0;
do {
console.log(i);
i++;
} while (i < 0);
// Output: 0 (runs once even though the condition is false)

How the for loop works in JavaScript

The for loop is used to repeat a block of code a known number of times.

Syntax:

for (initialization; condition; increment) {


// code block to execute
}

Example – iterating through an array:

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

for (let i = 0; i < colors.length; i++) {


console.log(colors[i]);
}
// Output: red, green, blue

How JavaScript handle type conversion and type coercion

JavaScript uses type conversion to convert values between types.

Type Coercion (Implicit Conversion):

JavaScript automatically converts types when needed.

Examples:

console.log("5" + 1); // "51" (number coerced to string)


console.log("5" - 1); // 4 (string coerced to number)
console.log(true + 1); // 2 (true → 1)
Type Conversion (Explicit):

You manually convert using functions like Number(), String(), or Boolean().

Examples:

Number("123"); // 123
String(456); // "456"
Boolean(0); // false

Function in JavaScript, and its importance in organizing and structuring code

A function is a block of code designed to perform a task. It's reusable and can accept inputs
(parameters) and return a result.

Why functions are important:

 Avoid code repetition


 Break programs into smaller, manageable parts
 Improve readability and maintainability
 Enable reuse and modular design

Example:

function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
Function in JavaScript

Function declaration:

function functionName(param1, param2) {


// code block
return result;
}

Example:

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

let sum = add(5, 3);


console.log(sum); // 8

Pass parameters to a JavaScript function

You pass parameters in parentheses when calling the function.

Required parameters:
function greet(name) {
console.log("Hello, " + name);
}
greet("Sam"); // Output: Hello, Sam
Optional parameters using default values:
function greet(name = "Guest") {
console.log("Hello, " + name);
}
greet(); // Output: Hello, Guest
greet("John"); // Output: Hello, John

Default values make parameters optional — if no argument is passed, the default is used.

Concept of function return values in JavaScript.

In JavaScript, a function can return a value to the place where it was called using the
return statement.

 Once return is executed, the function stops.


 You can store the returned value in a variable.

Example:

function multiply(a, b) {
return a * b;
}

let result = multiply(4, 5);


console.log(result); // 20

If no return is provided, the function returns undefined by default.


Anonymous function in JavaScript, and its usage in event handling

An anonymous function is a function without a name, typically used inline.

It's often used as a callback, especially in event handling.

Example (anonymous function in an event listener):

<button id="myBtn">Click Me</button>

<script>
document.getElementById("myBtn").addEventListener("click", function() {
alert("Button was clicked!");
});
</script>

 The function is defined and used immediately, without being named.

JavaScript events

JavaScript events are actions that occur in the browser, usually triggered by the user (like
clicks, keypresses, mouse movements, etc.).

You can attach event listeners to elements to respond to these actions.

Common Events:
Event Triggered When...

onclick A user clicks an element

onmouseover Mouse hovers over an element

onchange Input or select element value


changes

Example:

<input onchange="alert('Changed!')" />


<button onclick="alert('Clicked!')">Click</button>

Role of the onclick event in JavaScript

The onclick event runs JavaScript when an element is clicked, usually a button.

Example:

<p id="message">Original Text</p>


<button onclick="changeText()">Click Me</button>
<script>
function changeText() {
document.getElementById("message").innerText = "Text has been
changed!";
}
</script>

 Clicking the button changes the content of the paragraph.

Working of onmouseover event in JavaScript

The onmouseover event fires when the mouse pointer enters the element’s area.

You can use it to create interactive UI, like image swaps.

Example:

<img id="myImage" src="image1.jpg" onmouseover="hoverImage()"


onmouseout="resetImage()" width="200">

<script>
function hoverImage() {
document.getElementById("myImage").src = "image2.jpg";
}

function resetImage() {
document.getElementById("myImage").src = "image1.jpg";
}
</script>

 When the user hovers over the image, it changes to a second image.
 When the mouse leaves, it changes back.

Purpose of the onchange event in JavaScript

The onchange event is triggered when the value of an element changes and the user moves
focus away from it (e.g., clicks elsewhere or presses Enter).

Common with:

 <input> fields (text, number, etc.)


 <select> dropdowns
 <textarea>

Example – Input field:


<input type="text" id="name" onchange="alert('Name changed!')" />
Example – Dropdown menu:
<select id="colorSelect" onchange="showColor()">
<option value="Red">Red</option>
<option value="Blue">Blue</option>
</select>

<script>
function showColor() {
const selectedColor = document.getElementById("colorSelect").value;
alert("You selected: " + selectedColor);
}
</script>

Event listener in JavaScript

An event listener is a function that waits for a specific event to happen and executes code
when it does. It is added with addEventListener().

🔸 Inline Event Handling:

 Added directly in HTML (not recommended for large projects).


 Only one handler per event type.

<button onclick="alert('Clicked!')">Click Me</button>


🔸 Event Listener:

 Defined in JavaScript.
 Supports multiple handlers and separation of concerns.

document.getElementById("myBtn").addEventListener("click", function() {
alert("Clicked!");
});

Syntax of the addEventListener() method in JavaScript

Syntax:
element.addEventListener(eventType, callbackFunction, useCapture);

 eventType: e.g., "click", "mouseover"


 callbackFunction: function to run
 useCapture: optional, false by default (bubbling phase)

Example:
const btn = document.getElementById("myBtn");

btn.addEventListener("click", function() {
alert("Clicked!");
});
Benefits:

 Can attach multiple event types to the same element.


 Keeps JavaScript separate from HTML (cleaner structure).
 Allows removal of listeners (removeEventListener()).
 Helps maintain large codebases.

Usage of addEventListener() to attach multiple events to a single HTML


element
You can call addEventListener() multiple times on the same element with different events
or even the same event.

Example:
<button id="myBtn">Hover or Click Me</button>

<script>
const btn = document.getElementById("myBtn");

btn.addEventListener("click", () => {
console.log("Button clicked");
});

btn.addEventListener("mouseover", () => {
console.log("Mouse over the button");
});
</script>

Benefits of using addEventListener() over directly assigning event handlers


like onclick or onmouseover

Feature onclick / Inline addEventListener()

Multiple handlers per ❌ No (overwrites) ✅ Yes (stacked)


event

HTML/JS separation ❌ Mixed in HTML ✅ Keeps JS in script files

Supports capturing ❌ No ✅ Yes (optional 3rd


phase parameter)

Can be easily removed ❌ Not easily ✅ Yes, using


removeEventListener

Better structure & ❌ Poor for large ✅ Clean and scalable


maintainability projects

Remove an event listener in JavaScript

To remove an event listener, use removeEventListener() with the same function


reference that was used in addEventListener().

Important: Anonymous functions can't be removed — use named functions.

Example:
<button id="myBtn">Click Me</button>

<script>
const button = document.getElementById("myBtn");

function showAlert() {
alert("Button clicked!");
}

// Add listener
button.addEventListener("click", showAlert);

// Remove listener after 5 seconds


setTimeout(() => {
button.removeEventListener("click", showAlert);
console.log("Event listener removed");
}, 5000);
</script>

JavaScript functions support code reusability and modularity

Functions let you encapsulate logic and reuse code multiple times without duplication. They
make code modular, readable, and easier to maintain.

Example: Breaking down a complex task


function getInput() {
return prompt("Enter a number:");
}

function square(number) {
return number * number;
}

function displayResult(result) {
alert("The square is: " + result);
}

// Using the functions together


let num = parseFloat(getInput());
let result = square(num);
displayResult(result);

Functions help organize logic into manageable parts, making your code more modular and
testable.

Handle errors in JavaScript using try-catch.

JavaScript uses try-catch blocks to handle exceptions (errors) during execution.

Syntax:
try {
// Code that might throw an error
} catch (error) {
// Code to handle the error
} finally {
// Optional: code that runs no matter what
}
Example:
try {
let result = 10 / 0;
console.log("Result:", result);

// Simulating an error
let name = undefined;
console.log(name.length); // Error!
} catch (err) {
console.log("An error occurred:", err.message);
} finally {
console.log("Done processing.");
}

Use it when:

 Handling API responses


 Managing user input
 Preventing application crashes

How JavaScript handles variable scope (global vs. local).

Scope determines where variables can be accessed in your code.

🔹 Global Scope:

 Declared outside any function or block.


 Accessible from anywhere in the script.

🔹 Local Scope:

 Declared inside a function or block (let, const).


 Accessible only inside that function or block.

Example:
let globalVar = "I'm global";

function example() {
let localVar = "I'm local";
console.log(globalVar); // ✅ Accessible
console.log(localVar); // ✅ Accessible
}

example();
console.log(globalVar); // ✅ Accessible
console.log(localVar); // ❌ Error: not defined

Best Practice: Use let and const inside blocks to avoid accidental global variables.

JavaScript handle NaN (Not-a-Number)

NaN stands for Not-a-Number. It is returned when a mathematical operation fails or an


invalid number conversion happens.
Examples of NaN:
parseInt("abc"); // NaN
Math.sqrt(-1); // NaN
0 / 0; // NaN
Checking for NaN:

 Use Number.isNaN() (accurate):

Number.isNaN(NaN); // true
Number.isNaN("abc"); // false

 Avoid using just == or ===:

NaN === NaN; // false (by spec, NaN is not equal to anything, even
itself)

 Another safe check:

isNaN("abc"); // true, but loosely checks and may return true for non-
numbers

Prefer Number.isNaN() for strict checking.

Purpose of the eval() function in JavaScript

Purpose:

The eval() function executes a string of JavaScript code as if it were part of the program.

Example:

let x = 10;
let result = eval("x + 5"); // 15
Why it's dangerous and should be avoided:

 Security risk: Can run malicious code (e.g., from user input).
 Performance: Slower, because it disables some JavaScript optimizations.
 Debugging: Code becomes harder to read and maintain.

Avoid it unless absolutely necessary. Use safe alternatives:

 JSON.parse() for parsing JSON.


 Function() constructor for limited dynamic evaluation (careful!).

Working of default parameters in JavaScript functions.

JavaScript allows you to assign default values to function parameters if no value (or
undefined) is passed.

Example:
function greet(name = "Guest") {
console.log("Hello, " + name);
}

greet(); // Hello, Guest


greet("Alice"); // Hello, Alice
Benefits:

 Cleaner code (no need for if (param === undefined) checks)


 Improves readability and reduces bugs

Event listeners in JavaScript

Event Listeners (addEventListener)

 Added in JavaScript.
 Support multiple handlers for the same event.
 Cleaner, more maintainable code.

Inline Event Handlers

 Written directly in HTML.


 Only one handler allowed per event type.
 Harder to maintain in large applications.

Example – using addEventListener()


<button id="myBtn">Click Me</button>

<script>
const btn = document.getElementById("myBtn");
btn.addEventListener("click", function() {
alert("Button clicked!");
});
</script>

preventDefault() method work in JavaScript

preventDefault() is used to stop the default action of an event.

Common Use Cases:

 Preventing form submission


 Blocking a link from navigating
 Disabling default key actions

Example – prevent form submission:


<form id="myForm">
<input type="text" placeholder="Type something">
<button type="submit">Submit</button>
</form>

<script>
document.getElementById("myForm").addEventListener("submit",
function(event) {
event.preventDefault(); // prevents form from reloading the page
alert("Form submission prevented.");
});
</script>

Difference between click and dblclick events in JavaScript

Event Triggered When... Use Case Example

click Single mouse click Button clicks, links,


selections

dblclick Double mouse click Edit mode, special


(quickly) interactions

Click Example:
element.addEventListener("click", () => {
console.log("Single click");
});
Double Click Example:
element.addEventListener("dblclick", () => {
console.log("Double click detected");
});
Note:

 A dblclick will also trigger a click first.


 Handle them carefully if both are used on the same element.

Add and remove elements at the beginning and end of an array in JavaScript

JavaScript arrays provide the following methods:

Operation Method Description

Add to end push() Adds element to


end

Remove from pop() Removes last


end element

Add to unshift() Adds element to


beginning start

Remove from shift() Removes first


start element
Example:
let fruits = ["apple", "banana"];

fruits.push("orange"); // ["apple", "banana", "orange"]


fruits.pop(); // ["apple", "banana"]

fruits.unshift("mango"); // ["mango", "apple", "banana"]


fruits.shift(); // ["apple", "banana"]

Find the index of an element in an array using indexOf()

The indexOf() method returns the first index of the specified element in the array, or -1 if
not found.

Syntax:
array.indexOf(element, startIndex);
Example:
let numbers = [10, 20, 30, 40];

console.log(numbers.indexOf(30)); // 2
console.log(numbers.indexOf(50)); // -1 (not found)

It's case-sensitive for strings and uses strict equality (===).

Sort an array of numbers or strings in JavaScript

JavaScript uses the sort() method to sort arrays lexicographically by default, meaning
elements are converted to strings and compared by Unicode order.

Sorting strings (default):


let fruits = ["banana", "apple", "cherry"];
fruits.sort(); // ["apple", "banana", "cherry"] Sorting numbers (requires
compare function):
let numbers = [40, 100, 1, 5];
numbers.sort(); // Incorrect: [1, 100, 40, 5] (as strings)

numbers.sort((a, b) => a - b); // Correct: [1, 5, 40, 100]


Descending sort:
numbers.sort((a, b) => b - a); // [100, 40, 5, 1]

Difference between == and === in JavaScript

Operat Description Example


or

== Loose equality (performs type "5" == 5 → true


coercion)

=== Strict equality (no type coercion) "5" === 5 → false


Why use ===?

 Avoids unexpected bugs due to automatic type conversion.


 Safer and more predictable.

Examples:
0 == false // true (coercion)
0 === false // false (different types)

"123" == 123 // true


"123" === 123 // false

Different types of loops in JavaScript (for, while, do-while).

Loop Description Use When...


Type

for Repeats a block known You know the start/end


number of times conditions

while Repeats while condition is You don't know how many


true times

do-while Runs at least once, then You need the code to run once
checks condition before checking

Examples:

 For loop:

for (let i = 0; i < 5; i++) {


console.log(i);
}

 While loop:

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

 Do-while loop:

let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
Differences between break and continue in loops in JavaScript

Keywor Description
d

break Exits the loop entirely when a condition is met

continue Skips the current iteration and moves to the next


loop cycle

Example using break:


for (let i = 1; i <= 5; i++) {
if (i === 3) break;
console.log(i); // Output: 1, 2
}
Example using continue:
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
console.log(i); // Output: 1, 2, 4, 5
}

Significance of the undefined value in JavaScript and its difference from null

Value Meaning When it Appears

undefined A variable declared but not Automatically assigned by


assigned JS

null An intentional empty value Manually assigned by


developer

Example:
let a;
console.log(a); // undefined

let b = null;
console.log(b); // null
Use null when:

 You want to explicitly clear or reset a variable.

setTimeout() method in JavaScript, and how is it used

The setTimeout() method delays the execution of a function by a specified number of


milliseconds.

Syntax:
setTimeout(function, delayInMilliseconds);
Example:
function greet() {
console.log("Hello after 2 seconds");
}

setTimeout(greet, 2000); // Runs greet() after 2 seconds

You can also use an anonymous function:

setTimeout(() => {
console.log("This is delayed");
}, 1000);

Working of if, else, and switch statements in JavaScript.

if-else statements evaluate conditions:


let age = 18;

if (age < 18) {


console.log("Minor");
} else {
console.log("Adult");
}
switch statement checks multiple exact values:
let day = "Tuesday";

switch (day) {
case "Monday":
console.log("Start of week");
break;
case "Tuesday":
console.log("Second day");
break;
default:
console.log("Another day");
}

 break prevents "fall-through" to the next case.


 default runs if no match is found.

Role of the this keyword in JavaScript

The this keyword refers to the object that is currently executing the function. Its value
depends on the context in which the function is called.

Context Examples:
Context this refers to…

Global scope (non- Global object (window)


strict)

Method in object The object itself


Inside event listener The DOM element that
triggered it

Arrow functions this from surrounding scope

Examples:

 Global scope:

console.log(this); // window (in browser)

 Object method:

const person = {
name: "Alice",
greet: function() {
console.log("Hello, " + this.name);
}
};
person.greet(); // "Hello, Alice"

 Arrow function (inherits this):

const person = {
name: "Bob",
greet: () => {
console.log("Hi " + this.name); // undefined (uses global `this`)
}
};
person.greet();

JavaScript, variable scope determines where a variable can be accessed or modified.


Understanding scope is crucial for writing clean, bug-free code.
1. What Is Scope?
Scope refers to the context in which variables are declared and accessible.
JavaScript has:
 Global scope
 Local (function or block) scope
 Lexical scope (scope defined at declaration time, not runtime)
2. Global Scope
 A variable declared outside any function or block is in the global scope.
 Accessible from anywhere in the code.
var globalVar = "I'm global";

function printVar() {
console.log(globalVar); // Accessible
}
printVar(); // Output: I'm global
Lifespan:
Exists for the entire lifetime of the page (in browsers).
3. Local Scope (Function Scope)
 Variables declared inside a function using var, let, or const are local to that
function.
 Not accessible outside the function.
function testScope() {
let localVar = "I'm local";
console.log(localVar); // Accessible here
}
testScope();
// console.log(localVar); // ❌ Error: localVar is not defined
Lifespan:
Exists only while the function is running.
4. Block Scope (let and const)
 Introduced in ES6.
 let and const are block-scoped — they exist only inside {} blocks.
{
let x = 10;
const y = 20;
console.log(x, y); // 10 20
}
// console.log(x, y); // ❌ Error
var is function-scoped, not block-scoped.
5. Variable Declarations: var vs let vs const
Feature var let / const
Scope Function Block
Redeclaratio Allowed Not allowed (same scope)
n
Hoisting Yes (undefined) Yes (but not initialized)
Use in loops Shared Block-unique
6. Scope and Accessibility
Accessible:
A variable is accessible only in the scope in which it is defined and its inner (nested)
scopes.
javascript
CopyEdit
function outer() {
let outerVar = "outer";

function inner() {
console.log(outerVar); // Accessible
}
inner();
}
Not Accessible:
From outside a function/block, you cannot access inner-scope variables.
function outer() {
let innerVar = "hidden";
}
// console.log(innerVar); // Error
7. Lexical Scope (a.k.a Static Scope)
 JavaScript uses lexical scoping, which means the scope of a variable is determined at
the time of writing, not at runtime.
function outer() {
let x = 10;

function inner() {
console.log(x); // x is accessible due to lexical scope
}

return inner;
}

const innerFn = outer();


innerFn(); // Output: 10
8. Why Scope Matters
 Avoid name conflicts and unintended overwrites
 Helps encapsulate logic
 Important for closures, modularity, and memory management
PROCESS OF TYPE COERCION IN JAVASCRIPT
Type coercion in JavaScript is the process of converting one data type to another
automatically when required during operations like comparisons, arithmetic, or logical
expressions.
1. What is Type Coercion?
Type coercion can be:
 Implicit: done automatically by JavaScript.
 Explicit: done manually using functions like Number(), String(), etc.
2. Implicit Type Coercion
JavaScript tries to "guess" the right type during operations.
Examples:
console.log("5" + 2); // "52" → string (number converted to string)
console.log("5" - 2); // 3 → number (string converted to number)
console.log(true + 1); // 2 → true becomes 1
console.log(null + 1); // 1 → null becomes 0
console.log(undefined + 1); // NaN → undefined becomes NaN

3. Comparison and Type Coercion


Loose Equality (==) vs Strict Equality (===)
Comparison Resu Explanation
lt
5 == "5" true "5" is coerced to number
null == undefined true Special case
0 == false true false is coerced to 0
[] == "" true Both become empty string ""
[] == 0 true [] → "" → 0
{} == {} false Objects are compared by
reference
Strict Equality (===) avoids coercion:
5 === "5" // false
null === undefined // false
🔹 4. Truthy and Falsy Values
In JavaScript, the following are considered falsy:
 false
 0
 "" (empty string)
 null
 undefined
 NaN
Everything else is truthy, even:
 "0" (string with zero)
 [] (empty array)
 {} (empty object)
if ("0") console.log("Truthy!"); // Will print
if (0) console.log("Falsy!"); // Won't print
5. Common Pitfalls
Pitfall 1: Loose comparison confusion
console.log(false == "0"); // true
console.log(false == undefined); // false
Pitfall 2: == with arrays/objects
console.log([] == 0); // true
console.log([] == false); // true
Pitfall 3: Unexpected truthy/falsy values
if (" ") {
console.log("This runs"); // Space is truthy
}

Role of the this keyword in JavaScript functions


The this keyword in JavaScript refers to the execution context — i.e., the object on which
a function is called. However, its value is dynamic and depends on how the function is
invoked, not where it is defined.

1. this in JavaScript – Summary Table


Invocation Type Value of this
Global context Global object (window in browsers)
Function (non- Global object
strict)
Function (strict undefined
mode)
Method of an That object
object
Constructor The new instance created
function
Event handler (DOM) The HTML element triggering the
event
Arrow function Lexically inherited from enclosing
scope

2. this in Different Contexts – Explained


a) Global Context
console.log(this); // In browser: window
In the global scope, this refers to the global object (e.g., window in browsers).
b) Regular Function
function show() {
console.log(this);
}
show(); // window (or undefined in strict mode)
In a non-strict regular function, this refers to the global object.
In strict mode, it is undefined.
c) As a Method of an Object
const person = {
name: "Alice",
greet: function() {
console.log(this.name);
}
};
person.greet(); // "Alice"
Here, this refers to the object that calls the method (person).
d) Inside a Constructor Function
function Person(name) {
this.name = name;
}
const p = new Person("Bob");
console.log(p.name); // "Bob"
this refers to the newly created object.
e) Inside an Event Handler
document.getElementById("btn").addEventListener("click", function() {
console.log(this); // The button element
});
this refers to the DOM element that triggered the event.
f) With Arrow Functions
const person = {
name: "Eve",
greet: () => {
console.log(this.name);
}
};
person.greet(); // undefined
Arrow functions do not bind their own this.
Instead, this is inherited from the surrounding (lexical) scope.
g) Manual Binding with call(), apply(), bind()
function greet() {
console.log(this.name);
}
const user = { name: "Tom" };
greet.call(user); // "Tom"
You can explicitly set the value of this using call(), apply(), or bind().
Common Pitfalls
1. Losing this in Callbacks:
const person = {
name: "Zoe",
sayHi() {
setTimeout(function() {
console.log(this.name); // ❌ undefined (refers to window)
}, 1000);
}
};
Fix using arrow function:
setTimeout(() => {
console.log(this.name); // ✅ refers to `person`
}, 1000);
JavaScript supports both synchronous and asynchronous programming, and understanding
how they work with the event loop is key to writing efficient, non-blocking code.
1. Synchronous vs Asynchronous Programming in
JavaScript
Aspect Synchronous Asynchronous
Executio One statement at a time, Non-blocking, tasks run
n blocking concurrently
Code Sequential Tasks can be deferred or
flow delayed
Use Simple calculations, Network requests, timers, I/O
cases immediate tasks operations

2How Synchronous Code Works


 Runs line by line, blocking further execution until the current statement finishes.
 Example:
console.log("Start");
console.log("Middle");
console.log("End");
Output:
Start
Middle
End
3. How Asynchronous Code Works with the Event Loop
JavaScript has a single-threaded runtime but can handle async operations via the event loop:
Components:
 Call Stack: Executes synchronous code.
 Web APIs (browser environment): Handle async operations like timers, HTTP
requests.
 Callback Queue (Task Queue): Holds callbacks ready to be executed.
 Event Loop: Monitors the call stack and callback queue, moves callbacks to stack
when empty.
4. Execution Flow with Async Code
 When an async operation (e.g., setTimeout) is called, the callback is registered with
Web APIs.
 After the specified time, the callback is moved to the callback queue.
 The event loop waits until the call stack is empty, then pushes the callback onto the
stack for execution.
5. Example: setTimeout() and setInterval()
console.log("Start");

setTimeout(() => {
console.log("Timeout callback (after 2 seconds)");
}, 2000);

setInterval(() => {
console.log("Interval callback (every 1 second)");
}, 1000);

console.log("End");
Expected Output:
Start
End
Interval callback (every 1 second)
Interval callback (every 1 second)
Timeout callback (after 2 seconds)
Interval callback (every 1 second)
...
 The "Start" and "End" logs run immediately (synchronously).
 The setInterval callback runs every 1 second asynchronously.
 The setTimeout callback runs once after 2 seconds asynchronously.
1. What is NaN?
 NaN stands for Not-a-Number.
 It is a special numeric value that represents the result of an invalid or undefined
mathematical operation.
 Although its name suggests "not a number," NaN is actually of the type number.
Examples producing NaN:
console.log(0 / 0); // NaN (undefined division)
console.log(Math.sqrt(-1)); // NaN (invalid square root)
console.log(parseInt("abc")); // NaN (cannot parse to number)
console.log("hello" - 5); // NaN (invalid subtraction)
2. Purpose of NaN
 To indicate errors in numeric computations without throwing exceptions.
 Acts as a sentinel value signaling that the result is not a valid number.
 Prevents program crashes while indicating a computational problem.
3. How to Check if a Value is NaN
Important: NaN is not equal to itself!
console.log(NaN === NaN); // false
Methods to correctly check for NaN:
 Using Number.isNaN() (recommended)
Number.isNaN(NaN); // true
Number.isNaN("hello"); // false
Number.isNaN(undefined); // false
 Using global isNaN()
isNaN(NaN); // true
isNaN("hello"); // true (coerces to number first!)
Warning: The global isNaN() converts the argument to a number before checking, so it can
give unexpected results for non-numeric inputs.
4. Common Mistakes When Working with NaN
Mistake 1: Using equality operators to test for NaN
let val = NaN;
console.log(val === NaN); // false - won't work!
Mistake 2: Using global isNaN() without knowing coercion
console.log(isNaN("abc")); // true (because "abc" coerces to NaN)
console.log(isNaN("123")); // false (string "123" coerces to number 123)
This can lead to confusion when trying to detect numeric invalidity.
Mistake 3: Assuming NaN behaves like other values
 NaN is contagious in arithmetic:
console.log(5 + NaN); // NaN
console.log(NaN * 10); // NaN
 Once a calculation produces NaN, it propagates through subsequent operations.
1. What is eval()?
 eval() is a built-in JavaScript function that takes a string as input and executes it
as JavaScript code.
 It can evaluate expressions, execute statements, and return results dynamically at
runtime.
Example:
const code = "2 + 3 * 4";
const result = eval(code);
console.log(result); // 14
2. How eval() Works
 Takes a string argument.
 Parses the string as JavaScript code.
 Executes the code in the current scope.
 Returns the result of the executed code (if any).
eval("var x = 10;");
console.log(x); // 10 (x is now defined in the current scope)
3. Why is eval() Generally Discouraged?
Major Reasons:
1. Security Risks
 Running dynamically generated code can open doors for code injection attacks.
 If user input reaches eval(), malicious code can execute with full privileges.
let userInput = "alert('Hacked!')";
eval(userInput); // Dangerous if userInput is uncontrolled
2. Performance Issues
 eval() forces the JavaScript engine to recompile the code at runtime, which is
slower than normal code execution.
 Optimizations by JS engines cannot be applied well.
3. Debugging Difficulty
 Code executed via eval() is hard to debug and maintain.
 Tools like linters and static analyzers struggle with dynamic code strings.
4. Scope Confusion
 Can unintentionally create or overwrite variables in the current scope, making code
harder to predict.
4. Safer Alternatives to eval()
1. Using Functions
For evaluating expressions, use functions or Function constructor (although Function
constructor also has some risks):
const expr = "2 + 3 * 4";
const func = new Function(`return ${expr};`);
console.log(func()); // 14
More controlled than eval() since it runs in its own scope.
2. JSON Parsing
For data, use JSON.parse() instead of eval():
const jsonString = '{"name":"Alice", "age":25}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // Alice
Avoids running arbitrary code; only parses JSON.
detailed explanation about JavaScript arrays and common array methods like push(), pop(),
shift(), and unshift():
1. How JavaScript Arrays Work
 JavaScript arrays are dynamic, ordered collections that can store elements of any
type.
 They are zero-indexed, meaning the first element is at index 0.
 Arrays can grow or shrink automatically.
 Internally, they behave like objects with integer keys, but optimized for sequential
data.
2. Common Array Methods and Their Effects
Method Description Effect on Array
push() Adds one or more Increases array length, adds
elements to the end elements at the back
pop() Removes the last Decreases array length by 1,
element returns removed element
shift() Removes the first Decreases array length by 1, shifts
element remaining elements left
unshift() Adds one or more Increases array length, shifts
elements to the front existing elements right

3. Examples
a) push()
Adds elements to the end of the array.
let fruits = ["apple", "banana"];
fruits.push("orange");
console.log(fruits); // ["apple", "banana", "orange"]
b) pop()
Removes the last element and returns it.
let fruits = ["apple", "banana", "orange"];
let last = fruits.pop();
console.log(last); // "orange"
console.log(fruits); // ["apple", "banana"]
c) shift()
Removes the first element and returns it.
let fruits = ["apple", "banana", "orange"];
let first = fruits.shift();
console.log(first); // "apple"
console.log(fruits); // ["banana", "orange"]
d) unshift()
Adds elements to the front of the array.
let fruits = ["banana", "orange"];
fruits.unshift("apple");
console.log(fruits); // ["apple", "banana", "orange"]
1. Primitive vs Reference Data Types
Aspect Primitive Types Reference Types
Examples Number, String, Boolean, Object, Array, Function
null, undefined, Symbol,
BigInt
Stored in Stored directly on
the Stored on the heap, with
Memory stack variable holding a
reference (pointer)
Value Copies the actual value Copies the reference
assignment (memory address)
Mutability Immutable Mutable (can change
internal properties)
Equality Compared by value Compared by reference
comparison (same object?)
Passed to Passed by value Passed by reference
functions (actually the reference is
passed by value)

2. How They Are Stored in Memory


 Primitive values are stored in the call stack directly, which means variables hold the
actual value.
 Objects and arrays are stored in the heap (larger memory area), and variables hold a
reference (pointer) to the location in the heap.

3. Behavior When Assigned or Passed


Primitives:
let a = 10;
let b = a; // copies the value 10
b = 20;
console.log(a); // 10 (unchanged)
console.log(b); // 20
 Changing b does not affect a because the value is copied.

Reference Types:
let obj1 = { name: "Alice" };
let obj2 = obj1; // copies the reference, both point to same object
obj2.name = "Bob";

console.log(obj1.name); // "Bob" (changed)


console.log(obj2.name); // "Bob"
 Changing the property via obj2 affects obj1 because both reference the same object
in memory.

4. Passing to Functions
Primitives (passed by value):
function changeNum(num) {
num = 100;
}
let x = 50;
changeNum(x);
console.log(x); // 50 (unchanged)
Reference types (reference passed by value):
function changeObj(o) {
o.name = "Charlie";
}
let person = { name: "Alice" };
changeObj(person);
console.log(person.name); // "Charlie" (modified)
Note: The reference itself is passed by value, but it points to the same object, so
modifications affect the original object.
1. What is undefined?
 undefined is a primitive value automatically assigned to variables that have been
declared but not initialized.
 It also represents the absence of a defined value in various situations.
Common scenarios where undefined appears:
 Variable declared but not assigned:
let x;
console.log(x); // undefined
 Accessing a non-existent object property:
const obj = {a: 1};
console.log(obj.b); // undefined
 Function with no return statement returns undefined:
function foo() {}
console.log(foo()); // undefined

2. What is null?
 null is an explicitly assigned value that represents "no value" or "empty".
 It's a way for programmers to indicate that a variable intentionally has no object or
value.
Example:
let y = null;
console.log(y); // null

3. Differences Between undefined and null


Aspect undefined null
Type undefined (type: "undefined") (type: "object") —
object
a known JavaScript quirk
Value Automatically assigned by JS Must be explicitly
assignment assigned
Meaning Value is missing or not yet set Explicitly "no value" or
"empty"
Usage Uninitialized variables, missing Intentional absence of an
properties, missing return object/value
values
Equality (==) undefined == null is true null == undefined is true
Strict undefined === null is false null === undefined is
equality false
(===)

4. When to Encounter Each


 Use undefined to detect if a variable/property is missing or uninitialized.
 Use null to explicitly indicate "no value" or "empty".
5. Handling undefined and null Effectively
Checking for both:
if (value == null) {
// This checks for both null and undefined because == does type coercion
}
Avoid using == loosely—prefer strict checks:
if (value === undefined) {
// Only undefined
}

if (value === null) {


// Only null
}
Default values with nullish coalescing (??):
let input;
let result = input ?? "default"; // uses "default" if input is null or
undefined
Avoid confusing null and undefined:
 Don’t assign undefined manually — use null for empty values.
 Always initialize variables properly to avoid unexpected undefined.
6. Example Usage:
function getUser(id) {
if (id <= 0) return null; // no user found (explicit no value)
return { id, name: "Alice" };
}

let user = getUser(-1);

if (user === null) {


console.log("User not found");
} else if (user === undefined) {
console.log("User data missing");
}
1. What is the typeof Operator?
 typeof is a unary operator in JavaScript that returns a string indicating the type of
the operand.
 It helps you determine the data type of a variable or expression at runtime.
2. Basic Usage
typeof 42; // "number"
typeof "hello"; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" (this is a known JavaScript quirk)
typeof Symbol(); // "symbol"
typeof BigInt(123); // "bigint"
3. Identifying Objects, Functions, and Arrays
 Objects:
typeof {name: "Alice"}; // "object"
 Functions:
function greet() {}
console.log(typeof greet); // "function"
 Arrays:
typeof [1, 2, 3]; // "object" (arrays are technically objects)
Because arrays return "object" from typeof, to detect arrays, use:
Array.isArray([1, 2, 3]); // true
Array.isArray({}); // false
4. Examples in Context
let x;

x = 10;
console.log(typeof x); // "number"

x = "hello";
console.log(typeof x); // "string"

x = true;
console.log(typeof x); // "boolean"
x = null;
console.log(typeof x); // "object" <-- this is a JavaScript quirk!

x = undefined;
console.log(typeof x); // "undefined"

x = function() {};
console.log(typeof x); // "function"

x = [1, 2, 3];
console.log(typeof x); // "object"
console.log(Array.isArray(x)); // true
1. How addEventListener() Improves Event Handling
Inline Event Handlers (onclick, onmouseover, etc.)
 Assigned directly to HTML elements or DOM properties.
 Can only have one event handler per event type — assigning a new handler
overwrites the previous one.
 Limited control over event phases (capturing vs bubbling).
 Harder to separate JavaScript logic from HTML (mixes structure with behavior).
 Example:
<button onclick="alert('Clicked!')">Click Me</button>
Or in JavaScript:
element.onclick = function() {
console.log("Clicked!");
};
Assigning element.onclick again will replace the previous handler.
addEventListener() Method
 Allows attaching multiple event handlers to the same event type on an element —
handlers are added, not overwritten.
 Supports event capturing and bubbling phases via a third parameter.
 Keeps JavaScript separate from HTML, promoting cleaner code.
 Enables more flexible and powerful event management.
2. Example: Handling Multiple Events with addEventListener()
Suppose you want to handle both click and mouseover events on a button:
<button id="myButton">Hover or Click Me</button>

<script>
const btn = document.getElementById("myButton");

// Handle click event


btn.addEventListener("click", () => {
console.log("Button clicked!");
});

// Handle mouseover event


btn.addEventListener("mouseover", () => {
console.log("Mouse is over the button!");
});

// Another click handler (adds on top of the first)


btn.addEventListener("click", () => {
console.log("Another click handler!");
});
</script>
Behavior:
 When you click the button, both click handlers run (order of registration).
 When you hover over the button, the mouseover handler runs.
 Multiple handlers coexist without overwriting.
1. What is an Anonymous Function?
 An anonymous function is a function without a name.
 It is often defined inline, usually as part of an expression or passed directly as an
argument (callback).
 Cannot be referenced by name later (unless assigned to a variable).
Example of an anonymous function:
function() {
console.log("Hello, I'm anonymous!");
}
2. Difference Between Named and Anonymous Functions
Feature Named Function Anonymous Function
Has a name? Yes No
Can be called Yes, by name Only if assigned to a
later variable
Useful for Reusable functions, Callbacks, inline use,
recursion closures
Debugging Easier to identify in stack Harder to identify without a
traces name

3. Named Function Example:


function greet() {
console.log("Hello!");
}
greet(); // Output: Hello!
4. Anonymous Function Example:
Assigned to a variable:
const greet = function() {
console.log("Hello!");
};
greet(); // Output: Hello!
As a callback (common usage):
setTimeout(function() {
console.log("Executed after 1 second");
}, 1000);
Or in event listeners:
button.addEventListener("click", function() {
console.log("Button clicked!");
});
5. Why Use Anonymous Functions?
 They make code concise and inline.
 Useful for callbacks, event handlers, and places where the function is used only once.
 Often replaced nowadays with arrow functions for shorter syntax.

You might also like