Javascript
Javascript
Example:
<script>
function changeText() {
document.getElementById("demo").innerText = "You clicked the button!";
}
</script>
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.
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:
Example:
+ 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
let i = 0;
while (i < 3) {
console.log(i);
i++;
}
// Output: 0 1 2
let i = 0;
do {
console.log(i);
i++;
} while (i < 0);
// Output: 0 (runs once even though the condition is false)
The for loop is used to repeat a block of code a known number of times.
Syntax:
Examples:
Examples:
Number("123"); // 123
String(456); // "456"
Boolean(0); // false
A function is a block of code designed to perform a task. It's reusable and can accept inputs
(parameters) and return a result.
Example:
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
Function in JavaScript
Function declaration:
Example:
function add(a, b) {
return a + b;
}
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.
In JavaScript, a function can return a value to the place where it was called using the
return statement.
Example:
function multiply(a, b) {
return a * b;
}
<script>
document.getElementById("myBtn").addEventListener("click", function() {
alert("Button was clicked!");
});
</script>
JavaScript events
JavaScript events are actions that occur in the browser, usually triggered by the user (like
clicks, keypresses, mouse movements, etc.).
Common Events:
Event Triggered When...
Example:
The onclick event runs JavaScript when an element is clicked, usually a button.
Example:
The onmouseover event fires when the mouse pointer enters the element’s area.
Example:
<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.
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:
<script>
function showColor() {
const selectedColor = document.getElementById("colorSelect").value;
alert("You selected: " + selectedColor);
}
</script>
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().
Defined in JavaScript.
Supports multiple handlers and separation of concerns.
document.getElementById("myBtn").addEventListener("click", function() {
alert("Clicked!");
});
Syntax:
element.addEventListener(eventType, callbackFunction, useCapture);
Example:
const btn = document.getElementById("myBtn");
btn.addEventListener("click", function() {
alert("Clicked!");
});
Benefits:
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>
Example:
<button id="myBtn">Click Me</button>
<script>
const button = document.getElementById("myBtn");
function showAlert() {
alert("Button clicked!");
}
// Add listener
button.addEventListener("click", showAlert);
Functions let you encapsulate logic and reuse code multiple times without duplication. They
make code modular, readable, and easier to maintain.
function square(number) {
return number * number;
}
function displayResult(result) {
alert("The square is: " + result);
}
Functions help organize logic into manageable parts, making your code more modular and
testable.
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:
🔹 Global Scope:
🔹 Local Scope:
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.
Number.isNaN(NaN); // true
Number.isNaN("abc"); // false
NaN === NaN; // false (by spec, NaN is not equal to anything, even
itself)
isNaN("abc"); // true, but loosely checks and may return true for non-
numbers
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.
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);
}
Added in JavaScript.
Support multiple handlers for the same event.
Cleaner, more maintainable code.
<script>
const btn = document.getElementById("myBtn");
btn.addEventListener("click", function() {
alert("Button clicked!");
});
</script>
<script>
document.getElementById("myForm").addEventListener("submit",
function(event) {
event.preventDefault(); // prevents form from reloading the page
alert("Form submission prevented.");
});
</script>
Click Example:
element.addEventListener("click", () => {
console.log("Single click");
});
Double Click Example:
element.addEventListener("dblclick", () => {
console.log("Double click detected");
});
Note:
Add and remove elements at the beginning and end of an array in JavaScript
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)
JavaScript uses the sort() method to sort arrays lexicographically by default, meaning
elements are converted to strings and compared by Unicode order.
Examples:
0 == false // true (coercion)
0 === false // false (different types)
do-while Runs at least once, then You need the code to run once
checks condition before checking
Examples:
For loop:
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
Significance of the undefined value in JavaScript and its difference from null
Example:
let a;
console.log(a); // undefined
let b = null;
console.log(b); // null
Use null when:
Syntax:
setTimeout(function, delayInMilliseconds);
Example:
function greet() {
console.log("Hello after 2 seconds");
}
setTimeout(() => {
console.log("This is delayed");
}, 1000);
switch (day) {
case "Monday":
console.log("Start of week");
break;
case "Tuesday":
console.log("Second day");
break;
default:
console.log("Another day");
}
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…
Examples:
Global scope:
Object method:
const person = {
name: "Alice",
greet: function() {
console.log("Hello, " + this.name);
}
};
person.greet(); // "Hello, Alice"
const person = {
name: "Bob",
greet: () => {
console.log("Hi " + this.name); // undefined (uses global `this`)
}
};
person.greet();
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;
}
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)
Reference Types:
let obj1 = { name: "Alice" };
let obj2 = obj1; // copies the reference, both point to same object
obj2.name = "Bob";
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
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");