Unit2 - Subjective Questions
INT219 • Practice Questions with Detailed Answers
Differentiate between Primitive and Non-Primitive (Reference) data types in JavaScript with examples.
Primitive Data Types:
These are immutable data types that store a single value directly in the variable location.
- Storage: Stored on the Stack.
- Immutability: The value cannot be changed once created (though the variable can be reassigned).
- Examples:
String,Number,Boolean,Undefined,Null,Symbol, andBigInt.
Non-Primitive (Reference) Data Types:
These are mutable data types that store a reference (address) to the value in memory.
- Storage: Stored on the Heap, while the pointer is stored on the Stack.
- Mutability: The content can be modified without changing the reference.
- Examples:
Object,Array,Function.
Key Difference Example:
javascript
// Primitive
let a = 10;
let b = a;
a = 20;
// b remains 10
// Reference
let x = { val: 10 };
let y = x;
x.val = 20;
// y.val becomes 20 because y references the same object as x
Compare var, let, and const keywords in terms of scope, hoisting, and re-assignment.
The differences are summarized below:
| Feature | var |
let |
const |
|---|---|---|---|
| Scope | Function Scope. It ignores block scope (e.g., inside if-statements or loops). | Block Scope. Restricted to the {} block where it is defined. |
Block Scope. Restricted to the {} block where it is defined. |
| Hoisting | Hoisted to the top of the function/global scope. Initialized with undefined. |
Hoisted but remains in the Temporal Dead Zone (TDZ). Accessing before declaration throws a ReferenceError. |
Hoisted but remains in the TDZ. Throws ReferenceError if accessed before declaration. |
| Re-assignment | Can be reassigned and redeclared. | Can be reassigned but NOT redeclared in the same scope. | Cannot be reassigned. Must be initialized during declaration. |
Note regarding Const Objects: While the variable identifier cannot be reassigned, the properties of a const object or array can be mutated.
Explain the difference between the Equality Operator (==) and the Strict Equality Operator (===) with respect to type coercion.
Equality Operator (==):
- It compares two values for equality after converting both values to a common type (Type Coercion).
- It checks only the value, not the data type.
- Example:
5 == "5"evaluates totruebecause the string "5" is converted to a number before comparison.
Strict Equality Operator (===):
- It compares both the value and the data type.
- No type coercion is performed.
- Example:
5 === "5"evaluates tofalsebecause one is a Number and the other is a String.
Best Practice: It is generally recommended to use === to avoid unexpected bugs caused by implicit type conversion.
What is Hoisting in JavaScript? Describe how it affects variable and function declarations differently.
Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their containing scope (global or function) during the compile phase, before the code is executed.
1. Function Hoisting:
- Function Declarations are fully hoisted. You can call the function before it is defined in the code.
- Example:
sayHello()works even iffunction sayHello() {...}is written later.
2. Variable Hoisting (var):
- Variables declared with
varare hoisted but initialized withundefined. Accessing them before assignment returnsundefined.
3. Variable Hoisting (let and const):
- These are hoisted to the top of the block but are not initialized. They enter a Temporal Dead Zone. Accessing them before the line of declaration results in a
ReferenceError.
4. Function Expressions:
- If a function is assigned to a variable (e.g.,
var myFunc = function() {}), only the variable declaration is hoisted, not the function definition.myFunc()cannot be called before the assignment line.
Explain the concept of Arrow Functions. How do they differ from traditional functions regarding the this keyword?
Arrow Functions provide a concise syntax to write functions in JavaScript, introduced in ES6.
Syntax:
javascript
const add = (a, b) => a + b;
Key Differences regarding this:
-
Traditional Functions: The value of
thisdepends on how the function is called (dynamic binding). If called as a method of an object,thisrefers to that object. If called independently,thisrefers to the global object (orundefinedin strict mode). -
Arrow Functions: They do not have their own
thiscontext. They inheritthisfrom the parent scope (Lexical Scoping) at the time they are defined.
Implication: Arrow functions are excellent for callbacks (like inside setTimeout or array methods) where you want to preserve the context of the outer function, but they are poor choices for object methods where you need this to refer to the object itself.
Describe the Short-Circuit evaluation behavior of the Logical AND (&&) and Logical OR (||) operators.
Short-circuit evaluation means that the second operand of a logical expression is evaluated only if the first operand does not determine the final result.
1. Logical AND (&&):
- Syntax:
A && B - If
Ais falsy, the expression immediately returnsA(false) without evaluatingB. - If
Ais truthy, it evaluates and returnsB. - Usage: Often used for conditional execution (e.g.,
isLoggedIn && showDashboard()).
2. Logical OR (||):
- Syntax:
A || B - If
Ais truthy, the expression immediately returnsAwithout evaluatingB. - If
Ais falsy, it evaluates and returnsB. - Usage: Often used for setting default values (e.g.,
let name = inputName || "Guest").
Mathematical Logic:
Given propositions and :
- is true only if both are true.
- is true if at least one is true.
Discuss the Array Higher-Order Methods: map(), filter(), and reduce(). Provide syntax and use cases for each.
These methods operate on arrays and take a callback function as an argument.
1. map()
- Function: Creates a new array by applying a function to every element in the calling array.
- Syntax:
array.map((element, index) => { ... }) - Use Case: Converting an array of Celsius temperatures to Fahrenheit.
2. filter()
- Function: Creates a new array with all elements that pass the test implemented by the provided function (return
true). - Syntax:
array.filter((element) => { return condition; }) - Use Case: Extracting only even numbers from a list of integers.
3. reduce()
- Function: Executes a reducer function on each element of the array, resulting in a single output value.
- Syntax:
array.reduce((accumulator, currentValue) => { ... }, initialValue) - Use Case: Summing all numbers in an array or flattening a nested array.
Example:
javascript
const nums = [1, 2, 3, 4];
const sum = nums.reduce((acc, curr) => acc + curr, 0); // Result: 10
Explain Destructuring Assignment for Arrays and Objects with examples.
Destructuring Assignment is a syntax that allows unpacking values from arrays or properties from objects into distinct variables.
1. Array Destructuring:
-
Unpacks values based on position (index).
-
Example:
javascript
const colors = ['red', 'green', 'blue'];
const [first, second] = colors;
// first = 'red', second = 'green' -
You can skip elements using commas:
const [first, , third] = colors;
2. Object Destructuring:
-
Unpacks values based on property names (keys).
-
Example:
javascript
const user = { id: 1, name: 'Alice', role: 'Admin' };
const { name, role } = user;
// name = 'Alice', role = 'Admin' -
Renaming Variables: You can assign to a new variable name:
javascript
const { name: userName } = user;
// userName = 'Alice'
Benefits: makes code cleaner and easier to read when extracting data from complex structures.
What is the DOM (Document Object Model)? Differentiate between the window object and the document object.
DOM (Document Object Model):
The DOM is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects (a tree structure).
Differences:
| Feature | window Object |
document Object |
|---|---|---|
| Definition | Represents the browser window containing the DOM. It is the global object in the browser. | Represents the actual HTML page loaded inside the window. |
| Hierarchy | It is the root of the hierarchy. document is a property of window. |
It is a child of the window object (window.document). |
| Functionality | Controls browser-level features: alert(), setTimeout(), history, location. |
Controls page content: getElementById(), querySelector(), createElement(). |
| Scope | Global variables defined with var become properties of window. |
Variables do not attach to document. |
Explain the concept of Event Propagation in the DOM. Describe Bubbling and Capturing.
Event Propagation determines how an event travels through the DOM tree to arrive at its target and what happens afterward.
Phases:
-
Capturing Phase (Trickling):
- The event starts from the
window(root) and travels down the DOM tree to the target element. - Handlers aimed at the capturing phase are executed here (enabled by setting
{capture: true}inaddEventListener).
- The event starts from the
-
Target Phase:
- The event reaches the target element itself.
-
Bubbling Phase:
- The event bubbles up from the target element back to the
window(root). - This is the default behavior for most event handlers.
- The event bubbles up from the target element back to the
Diagrammatic Logic:
If we have div > p > button and click the button:
- Capturing:
divpbutton - Bubbling:
buttonpdiv
Stopping Propagation: usage of event.stopPropagation() prevents the event from moving further in the flow.
How do you access HTML elements using JavaScript? Compare getElementById, getElementsByClassName, and querySelector.
JavaScript provides several methods on the document object to select elements.
1. document.getElementById('id'):
- Selects a single element with the specified unique
idattribute. - Returns: A DOM object (Element) or
null. - Speed: Generally the fastest method.
2. document.getElementsByClassName('class'):
- Selects all elements having the specified class name.
- Returns: A live
HTMLCollection(array-like object). - Note: You must use an index (e.g.,
[0]) or loop to access specific elements.
3. document.querySelector('selector'):
- Selects the first element that matches a specific CSS selector (e.g.,
.myClass,#myId,div > p). - Returns: A single Element or
null. - Flexibility: Extremely flexible as it accepts any valid CSS selector string.
4. document.querySelectorAll('selector'):
- Similar to
querySelectorbut selects all matching elements. - Returns: A static
NodeList.
Explain the Spread Operator (...) and the Rest Parameter (...) in JavaScript with examples.
Both use the same syntax (...) but serve different purposes depending on the context.
1. Spread Operator:
-
Context: Function calls, Array literals, Object literals.
-
Function: Expands (spreads) an iterable (like an array or string) into individual elements.
-
Example (Array):
javascript
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4] -
Example (Object):
javascript
const obj1 = { x: 1 };
const obj2 = { ...obj1, y: 2 }; // { x: 1, y: 2 }
2. Rest Parameter:
- Context: Function definitions.
- Function: Collects multiple elements and condenses them into a single array element.
- Example:
javascript
function sum(...numbers) {
return numbers.reduce((a, b) => a + b);
}
sum(1, 2, 3, 4); // numbers becomes [1, 2, 3, 4]
Describe the Control Flow statements: switch vs if-else if. When should you use one over the other?
If-Else If:
- Evaluates boolean expressions.
- Can handle complex conditions, ranges (e.g.,
x > 10 && x < 20), and different variable checks in each block. - Execution: Checks conditions sequentially until one is true.
Switch Statement:
- Evaluates an expression once and compares the result against a list of
casevalues using strict equality (===). - Syntax: Uses
case,break, anddefault. - Fall-through: If
breakis omitted, execution continues to the next case.
Comparison & Usage:
- Readability:
switchis generally cleaner and faster to read when comparing a single variable against many known discrete values (e.g., Redux reducers, menu options). - Flexibility:
if-elseis necessary for ranges, boolean logic, or checking multiple different variables. - Performance:
switchcan be slightly faster for a large number of fixed conditions due to jump-table optimizations in compilers.
What are Closures in JavaScript? Explain with a code example showing how a function retains access to its lexical scope.
Definition:
A Closure is a feature where an inner function has access to the outer (enclosing) function's variables—a scope chain.
The closure has three scope chains:
- Access to its own scope.
- Access to the outer function's variables.
- Access to the global variables.
Crucially, the inner function remembers the environment in which it was created, even after the outer function has finished executing.
Example:
javascript
function makeCounter() {
let count = 0; // Local variable to makeCounter
return function() {
count++; // Inner function accesses outer variable
return count;
};
}
const counterA = makeCounter();
console.log(counterA()); // Output: 1
console.log(counterA()); // Output: 2
Explanation: Even though makeCounter has finished execution, counterA (the inner function) retains a reference to the count variable due to the closure.
Distinguish between the Looping structures: for, for...in, and for...of.
1. Standard for loop:
- Uses a counter/index.
- Best for when you need precise control over the index or need to modify the array while looping.
- Syntax:
for (let i = 0; i < arr.length; i++) { ... }
2. for...in loop:
- Iterates over the enumerable properties (keys) of an object.
- If used on an array, it iterates over the indices (strings "0", "1", etc.), not the values.
- Also iterates over inherited properties (unless filtered).
- Use case: Iterating over Object keys.
3. for...of loop (Introduced in ES6):
- Iterates over the values of an iterable object (Arrays, Strings, Maps, Sets).
- Does not work on plain Objects (unless they implement an iterator).
- Use case: Iterating over Array elements cleanly.
Summary: Use for...in for Objects (Keys), for...of for Arrays (Values).
What is the role of the event object in Event Handling? Explain event.preventDefault() and event.target.
The Event Object:
When an event occurs, the browser creates an event object and passes it as an argument to the event handler function. It contains details about the event (mouse coordinates, key pressed, element clicked, etc.).
1. event.target:
- This property returns the HTML element that triggered the event.
- Difference from
this:thisusually refers to the element the listener is attached to, whiletargetis the actual element clicked (relevant during bubbling).
2. event.preventDefault():
-
This method prevents the browser's default behavior associated with the event.
-
Example 1 (Forms): Prevents the form from submitting and reloading the page when a "Submit" button is clicked.
javascript
form.addEventListener('submit', function(e) {
e.preventDefault();
// Handle submission via AJAX instead
}); -
Example 2 (Links): Prevents a link (
<a>) from navigating to the URL.
Explain the concept of String Interpolation using Template Literals. How is it different from standard string concatenation?
Template Literals:
Introduced in ES6, template literals are string literals allowing embedded expressions. They are enclosed by the backtick (`) character instead of double or single quotes.
String Interpolation:
It allows embedding variables and expressions directly into the string using the ${expression} syntax.
Comparison:
-
Concatenation (Old way):
- Uses the
+operator. - Cumbersome for multiline strings or complex sentences.
- Example:
var msg = "Hello " + name + ", you contain " + (a + b) + " items.";
- Uses the
-
Interpolation (New way):
- Uses backticks and placeholders.
- Supports multiline strings natively.
- Example:
javascript
const msg =Hello {a + b} items.;
Advantages: Improved readability, maintainability, and ease of formatting HTML strings.
Define Type Coercion in JavaScript. Give examples of implicit coercion that can lead to unexpected results.
Type Coercion is the automatic or implicit conversion of values from one data type to another (e.g., strings to numbers). It happens when operators or functions are applied to types they don't expect.
Examples of Implicit Coercion:
-
String Concatenation wins over Addition:
- Expression:
'5' + 3 - Result:
"53"(String) - Reason: The
+operator prefers string concatenation if one operand is a string.
- Expression:
-
Subtraction converts to Number:
- Expression:
'5' - 3 - Result:
2(Number) - Reason:
-,*,/operators convert strings to numbers.
- Expression:
-
Boolean Coercion:
- Expression:
1 + true - Result:
2(Number) - Reason:
trueis coerced to1(andfalseto0).
- Expression:
-
Equality check:
- Expression:
[] == 0 - Result:
true - Reason: Empty array converts to empty string
"", which converts to0.
- Expression:
Explain the interaction methods: alert, prompt, and confirm. What data types do they return?
These are methods of the window object used to interact with the user via modal dialogs.
1. alert(message)
- Function: Displays a modal with a message and an "OK" button.
- Usage: To display information or warnings.
- Return Value:
undefined. It pauses script execution until closed.
2. prompt(message, default)
- Function: Displays a modal with a text input field, "OK", and "Cancel".
- Usage: To get input from the user.
- Return Value:
- If user clicks OK: Returns the text entered (as a String).
- If user clicks Cancel: Returns
null.
3. confirm(message)
- Function: Displays a modal with a question, "OK", and "Cancel" buttons.
- Usage: To verify a user action (e.g., "Are you sure you want to delete?").
- Return Value:
trueif user clicks OK.falseif user clicks Cancel.
Describe how to manipulate the DOM by creating and appending new elements. Provide a step-by-step code example.
DOM manipulation involves creating new nodes and attaching them to the existing DOM tree.
Steps:
- Create: Use
document.createElement(tagName)to create a new element node. - Content: Set text or attributes using
.textContent,.innerHTML, or.setAttribute(). - Select Parent: Find the existing element where you want to add the new element.
- Append: Use
.appendChild()or.append()to add the new element to the parent.
Example Code:
javascript
// 1. Create a new <li> element
const newItem = document.createElement('li');
// 2. Add content to the element
newItem.textContent = 'Fresh Milk';
newItem.setAttribute('class', 'grocery-item');
// 3. Select the parent <ul> element
const list = document.getElementById('grocery-list');
// 4. Append the new item to the list
list.appendChild(newItem);
This adds a new bullet point saying "Fresh Milk" to the element with ID grocery-list.