Unit 4: JavaScript Fundamentals - Subjective Questions
CSE326 — Internet Programming • Practice Questions with Detailed Answers
20 questions
Define JavaScript and explain its role in Internet programming.
JavaScript is a high-level, interpreted programming language primarily used to add dynamic and interactive behavior to web pages.
Its major roles in Internet programming include:
- DOM manipulation: It can modify HTML elements, attributes, and styles.
- Event handling: It responds to user actions such as clicks, keyboard input, and form submission.
- Client-side validation: It validates user input before data is sent to a server.
- Asynchronous communication: It can exchange data with servers using APIs without reloading the entire page.
- Application development: It is used for client-side, server-side, mobile, and desktop applications.
JavaScript is standardized through ECMAScript and is supported by all modern web browsers.
Distinguish between var, let, and const in JavaScript with suitable examples.
var, let, and const are used to declare variables, but they differ in scope and reassignment behavior.
var: Function-scoped, can be redeclared, and can be reassigned.let: Block-scoped, cannot be redeclared in the same scope, but can be reassigned.const: Block-scoped and cannot be redeclared or reassigned after initialization.
Example:
var city = "Delhi";
var city = "Mumbai";
let score = 10;
score = 20;
const pi = 3.14159;A const object or array cannot be reassigned, but its internal properties or elements may still be modified. In modern JavaScript, const is preferred by default and let is used when reassignment is required.
Explain the primitive and non-primitive data types available in JavaScript.
JavaScript data types are broadly divided into primitive and non-primitive types.
Primitive data types:
string: Represents textual data, such as"Hello".number: Represents integers, decimal values,Infinity, andNaN.bigint: Represents integers larger than the safe range ofnumber.boolean: Representstrueorfalse.undefined: Indicates that a variable has been declared but not assigned a value.null: Represents an intentional absence of value.symbol: Represents a unique and immutable identifier.
Non-primitive data type:
object: Stores collections of properties and includes ordinary objects, arrays, functions, and dates.
Primitive values are generally copied by value, whereas objects are handled through references to their locations in memory.
Describe JavaScript operators and explain the major categories of operators with examples.
Operators are symbols or keywords that perform operations on one or more operands.
Major categories include:
- Arithmetic operators:
+,-,*,/,%, and**perform mathematical calculations. - Assignment operators:
=,+=,-=,*=, and/=assign or update values. - Comparison operators:
===,!==,>,<,>=, and<=compare values. - Logical operators:
&&,||, and!combine or reverse Boolean expressions. - Increment and decrement operators:
++and--change a numeric value by one. - Conditional operator:
condition ? value1 : value2selects one of two values. - Type operators:
typeofidentifies a value's type, whileinstanceofchecks an object's prototype chain.
Example:
let x = 8;
let y = 3;
let result = x > y && y !== 0;Here, the comparison expressions produce Boolean values, and && combines them.
Compare the equality operators == and === in JavaScript. Why is strict equality generally preferred?
Both operators compare values, but they follow different conversion rules.
- Loose equality (
==): Converts operands to compatible types before comparison. - Strict equality (
===): Compares both type and value without implicit type conversion.
Examples:
5 == "5"; // true
5 === "5"; // false
false == 0; // true
false === 0; // false
null == undefined; // true
null === undefined; // falseStrict equality is generally preferred because:
- It avoids unexpected type coercion.
- It makes program behavior easier to predict.
- It clearly expresses that both type and value must match.
- It reduces subtle bugs caused by values such as
0,false, and empty strings.
Explain operator precedence, associativity, and type coercion in JavaScript expressions. Evaluate the expressions 2 + 3 * 4, "5" + 2, and "5" - 2.
Operator precedence determines which operator is evaluated first. Associativity determines the evaluation direction when operators have the same precedence. Parentheses can be used to explicitly control the order.
Type coercion is the automatic or explicit conversion of a value from one data type to another.
Evaluation:
-
2 + 3 * 4- Multiplication has higher precedence than addition.
- Result: .
-
"5" + 2- When one operand is a string,
+performs string concatenation. - Result:
"52".
- When one operand is a string,
-
"5" - 2- The subtraction operator converts
"5"to the number5. - Result:
3.
- The subtraction operator converts
Explicit conversions such as Number(value) and String(value) are preferable when the intended type should be clear.
Explain strings in JavaScript and describe any five commonly used string properties or methods.
A string is a sequence of characters used to represent text. Strings may be created using single quotes, double quotes, or backticks. JavaScript strings are immutable, so methods return new strings rather than changing the original string.
Common properties and methods include:
length: Returns the number of UTF-16 code units in a string.toUpperCase(): Returns an uppercase version of the string.toLowerCase(): Returns a lowercase version of the string.includes(value): Checks whether a substring is present.slice(start, end): Extracts part of a string.replace(search, replacement): Replaces the first matching value by default.trim(): Removes whitespace from both ends.
Example:
const text = " JavaScript Basics ";
const result = text.trim().toUpperCase();
// "JAVASCRIPT BASICS"What are template literals? Explain interpolation and multiline strings with an example.
Template literals are strings enclosed in backticks. They support expression interpolation, multiline text, and tagged templates.
Interpolation uses the syntax ${expression} to insert an expression's result into a string.
Example:
const name = "Asha";
const marks = 82;
const message = `${name} obtained ${marks} marks.
Status: ${marks >= 40 ? "Pass" : "Fail"}`;This produces a two-line string containing the values of name, marks, and the conditional expression.
Advantages include:
- Cleaner construction of strings containing variables.
- Direct support for multiline strings.
- Ability to evaluate expressions inside a string.
- Improved readability compared with repeated use of the
+operator.
Explain JavaScript numbers, NaN, Infinity, and commonly used number-related methods.
JavaScript uses the number type for most integer and floating-point values. It follows the IEEE 754 double-precision floating-point format.
Important special values are:
NaN: Means "Not a Number" and represents an invalid numeric result, such asNumber("abc").Infinity: Represents a value greater than the largest finite number and may result from positive division by zero.-Infinity: Represents negative infinity.
Useful methods and functions include:
Number(value): Converts a value to a number.Number.isNaN(value): Reliably checks whether a value isNaN.Number.isFinite(value): Checks whether a value is a finite number.parseInt(value, radix): Parses an integer from a string.parseFloat(value): Parses a floating-point number.toFixed(digits): Returns a formatted string with a fixed number of decimal places.
Floating-point arithmetic may have precision limitations; for example, 0.1 + 0.2 is not represented as exactly 0.3.
Explain Boolean values, truthy values, and falsy values in JavaScript with examples.
A Boolean value is either true or false. Boolean values are commonly produced by comparison and logical expressions.
When a non-Boolean value is used in a condition, JavaScript converts it to a Boolean.
The principal falsy values are:
false0and-00n""or an empty stringnullundefinedNaN
Most other values are truthy, including non-empty strings, nonzero numbers, arrays, and objects.
Example:
const username = "Ravi";
if (username) {
console.log("A username was provided");
}The string is non-empty, so it is converted to true. Notably, empty arrays and empty objects are also truthy.
Describe the if, if...else, and if...else if...else conditional statements in JavaScript.
Conditional statements execute different blocks of code according to whether conditions are true or false.
if: Executes a block only when its condition is truthy.if...else: Selects between two blocks.if...else if...else: Tests multiple conditions in order and executes the first matching block.
Example:
const score = 72;
let grade;
if (score >= 80) {
grade = "A";
} else if (score >= 60) {
grade = "B";
} else if (score >= 40) {
grade = "C";
} else {
grade = "Fail";
}Conditions should be arranged carefully because evaluation stops as soon as a true branch is found. Braces are recommended even for single-statement blocks to improve clarity and prevent errors.
Compare the switch statement and the conditional operator in JavaScript. State appropriate use cases for each.
A switch statement compares one expression against multiple case values using strict comparison. It is suitable when many branches depend on one value.
switch (role) {
case "admin":
access = "full";
break;
case "editor":
access = "limited";
break;
default:
access = "read-only";
}The break statement prevents execution from continuing into the next case. The default branch handles unmatched values.
The conditional operator has the form condition ? valueIfTrue : valueIfFalse. It is an expression and is useful for selecting one of two values.
const status = age >= 18 ? "Adult" : "Minor";Use switch for readable multi-way selection and the conditional operator for concise two-way value selection. Deeply nested conditional operators should generally be avoided because they reduce readability.
Define a JavaScript function. Explain function declarations, function expressions, parameters, arguments, and return values.
A function is a reusable block of code designed to perform a task. It can receive input through parameters and provide output through return.
A function declaration is defined using the function keyword and a name:
function add(a, b) {
return a + b;
}A function expression stores a function value in a variable:
const multiply = function (a, b) {
return a * b;
};- Parameters are names listed in the function definition, such as
aandb. - Arguments are actual values supplied during a call, such as
add(4, 6). - Return value is the result sent back by the
returnstatement.
If execution reaches the end without return, the function returns undefined. Function declarations are hoisted differently from function expressions, so a declaration can generally be called before its position in the source code.
Compare regular functions and arrow functions in JavaScript. Discuss their syntax and behavior of this.
Arrow functions provide a shorter syntax for function expressions.
Regular function:
const square = function (value) {
return value * value;
};Arrow function:
const square = value => value * value;Key differences are:
- Arrow functions can use an implicit return when the body is a single expression.
- Arrow functions do not create their own
this; they capturethisfrom the surrounding lexical scope. - Regular functions receive
thisaccording to how they are called. - Arrow functions do not have their own
argumentsobject. - Arrow functions cannot be used as constructors with
new.
Arrow functions are useful for short callbacks and lexical this. Regular functions are usually more appropriate for object methods that require a dynamically determined this value or for constructor functions.
Explain global scope, function scope, block scope, lexical scope, and variable shadowing in JavaScript.
Scope determines where a variable can be accessed.
- Global scope: A variable declared outside functions and blocks is accessible throughout the script, subject to the module or environment.
- Function scope: A variable declared with
varinside a function is available throughout that function. - Block scope: Variables declared with
letorconstinside{}are limited to that block. - Lexical scope: An inner function can access variables declared in its surrounding source-code scopes.
- Variable shadowing: An inner declaration with the same name temporarily hides an outer variable.
Example:
const value = "global";
function display() {
const value = "function";
if (true) {
let message = value;
console.log(message);
}
}Here, the inner value shadows the global variable, and message cannot be accessed outside the if block.
What is a closure in JavaScript? Explain how it is related to lexical scope with a suitable example.
A closure is formed when a function retains access to variables from its lexical outer scope even after the outer function has completed execution.
Example:
function createCounter() {
let count = 0;
return function () {
count += 1;
return count;
};
}
const counter = createCounter();
counter(); // 1
counter(); // 2The returned inner function continues to access and update count. The variable is not directly accessible from outside createCounter, but it remains alive because the inner function refers to it.
Closures are useful for:
- Preserving state between function calls.
- Creating private data.
- Building function factories.
- Implementing callbacks and event handlers.
Each call to createCounter() creates a separate lexical environment and therefore an independent counter.
Explain how arrays are created, accessed, updated, and traversed in JavaScript.
An array is an ordered collection whose elements are accessed using zero-based numeric indexes. It can contain values of different data types.
const subjects = ["HTML", "CSS", "JavaScript"];Important operations include:
- Access:
subjects[0]returns"HTML". - Update:
subjects[1] = "Web Design"changes the second element. - Length:
subjects.lengthreturns the number of elements. - Append:
subjects.push("Node.js")adds an element at the end. - Traversal: A loop or array method can process every element.
Example traversal:
subjects.forEach(function (subject, index) {
console.log(index, subject);
});Arrays are objects and are mutable. Assigning an array to another variable copies its reference rather than creating an independent array.
Compare the array methods push, pop, shift, unshift, slice, and splice.
These methods add, remove, or extract array elements.
push(value): Adds one or more elements to the end and mutates the array.pop(): Removes and returns the last element.unshift(value): Adds elements to the beginning and mutates the array.shift(): Removes and returns the first element.slice(start, end): Returns a shallow copy of a selected section without modifying the original array. The end index is excluded.splice(start, deleteCount, ...items): Removes, replaces, or inserts elements and modifies the original array.
Example:
const values = [10, 20, 30, 40];
const selected = values.slice(1, 3); // [20, 30]
values.splice(1, 2, 25); // [10, 25, 40]The major distinction is that slice is non-mutating, while splice changes the source array.
Explain the purpose of forEach, map, filter, find, and reduce. Use them to describe a data-processing sequence for an array of numbers.
These higher-order array methods accept callback functions.
forEach: Performs an action for each element and returnsundefined.map: Creates a new array by transforming every element.filter: Creates a new array containing elements that satisfy a condition.find: Returns the first element satisfying a condition, orundefined.reduce: Combines all elements into one accumulated result.
Example:
const numbers = [1, 2, 3, 4, 5, 6];
const evenSquares = numbers
.filter(number => number % 2 === 0)
.map(number => number ** 2);
const total = evenSquares.reduce(
(sum, number) => sum + number,
0
);The sequence first selects [2, 4, 6], transforms it into [4, 16, 36], and then computes . The original array is not modified by these operations.
Describe JavaScript objects and explain object creation, property access, property modification, methods, destructuring, and the spread syntax.
A JavaScript object is a collection of key-value properties. A property value may be any JavaScript value, including a function. A function stored as a property is commonly called a method.
const student = {
name: "Meera",
marks: 85,
introduce() {
return `I am ${this.name}`;
}
};Object manipulation includes:
- Dot access:
student.name - Bracket access:
student["marks"], useful for computed property names - Modification:
student.marks = 90 - Addition:
student.course = "Internet Programming" - Deletion:
delete student.course - Destructuring:
const { name, marks } = student - Spread syntax:
const updated = { ...student, marks: 95 }
Useful static methods include Object.keys(), Object.values(), and Object.entries(). Spread syntax performs a shallow copy, so nested objects remain shared unless they are copied separately.
Define JavaScript and explain its role in Internet programming.
JavaScript is a high-level, interpreted programming language primarily used to add dynamic and interactive behavior to web pages.
Its major roles in Internet programming include:
- DOM manipulation: It can modify HTML elements, attributes, and styles.
- Event handling: It responds to user actions such as clicks, keyboard input, and form submission.
- Client-side validation: It validates user input before data is sent to a server.
- Asynchronous communication: It can exchange data with servers using APIs without reloading the entire page.
- Application development: It is used for client-side, server-side, mobile, and desktop applications.
JavaScript is standardized through ECMAScript and is supported by all modern web browsers.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →