Unit 5: Interactive Web Development - Subjective Questions
CSE326 — Internet Programming • Practice Questions with Detailed Answers
20 questions
Explain loops and iterative programming in JavaScript. Describe the syntax, execution flow, and suitable use cases of for, while, and do...while loops.
Loops allow a program to execute a block of statements repeatedly while a condition remains true or while iterating over a collection.
- A
forloop is suitable when the number of iterations is known or controlled by a counter. It contains initialization, a condition, and an update expression. - A
whileloop is useful when the number of iterations is not known in advance. The condition is checked before every iteration. - A
do...whileloop executes its body at least once because the condition is evaluated after the body. - The
breakstatement terminates a loop immediately. - The
continuestatement skips the remainder of the current iteration and proceeds to the next iteration. - Care must be taken to update loop-control variables; otherwise, an infinite loop may occur.
Loops reduce code duplication and are commonly used for processing arrays, generating dynamic content, and validating repeated input.
Describe higher-order functions in JavaScript. Explain how map(), filter(), and reduce() operate, with suitable examples.
A higher-order function is a function that accepts another function as an argument, returns a function, or does both. JavaScript supports this feature because functions are first-class objects.
map()applies a callback to every array element and returns a new array of the same length.filter()applies a condition to every element and returns a new array containing only the elements that satisfy the condition.reduce()combines array elements into a single result, such as a sum, object, or string.
Example:
const doubled = numbers.map(n => n * 2);
const adults = people.filter(person => person.age >= 18);
const total = numbers.reduce((sum, n) => sum + n, 0);
These methods encourage concise, reusable, and declarative programming. They generally do not modify the original array unless the callback explicitly changes referenced objects.
What is a callback function? Explain synchronous and asynchronous callbacks and discuss their use in interactive web applications.
A callback function is a function passed to another function so that it can be invoked later or after a particular operation is completed.
- A synchronous callback runs immediately during the execution of the calling function. Array methods such as
forEach()andmap()commonly use synchronous callbacks. - An asynchronous callback runs later, after an event, timer, network request, or other operation completes. Examples include callbacks used with
setTimeout(), event listeners, and older asynchronous APIs. - Callbacks allow code to respond to user actions without blocking the browser interface.
- They are essential for handling button clicks, loading server data, processing files, and responding to media events.
- Excessive nesting of callbacks can create difficult-to-read code known as callback hell. Promises and
async/awaitprovide more manageable alternatives for many asynchronous tasks.
A callback should receive clearly defined arguments and should handle success and failure conditions appropriately.
Explain the fundamentals of the Document Object Model (DOM). How does the browser represent an HTML document, and how can JavaScript interact with that representation?
The Document Object Model, or DOM, is a programming interface that represents an HTML document as a hierarchical tree of objects.
- The
documentobject represents the complete web page. - Elements such as
<html>,<body>, headings, forms, and buttons are represented as element nodes. - Text inside elements is represented by text nodes.
- Parent-child and sibling relationships allow JavaScript to navigate the document tree.
- JavaScript can read, create, update, move, and remove nodes.
- DOM properties and methods allow scripts to change text, attributes, styles, classes, and event behavior.
For example, JavaScript can access a heading, change its textContent, add a CSS class, and insert a new paragraph. DOM updates change the rendered page without requiring a complete page reload.
Compare common DOM selection methods and explain how DOM elements can be manipulated safely and efficiently.
Common DOM selection methods include:
getElementById()selects one element by its uniqueid.getElementsByClassName()returns a live collection of elements with a specified class.getElementsByTagName()returns a live collection based on the tag name.querySelector()returns the first element matching a CSS selector.querySelectorAll()returns a static collection of all matching elements.
DOM manipulation can be performed using:
textContentfor inserting plain text safely.setAttribute()and direct properties for changing attributes.classList.add(),remove(), andtoggle()for managing CSS classes.createElement()andappend()for generating nodes.remove()for deleting nodes.
textContent should be preferred for untrusted text because assigning untrusted data to innerHTML can introduce cross-site scripting vulnerabilities. Repeated DOM updates should be minimized or grouped for better performance.
Describe event handling in JavaScript. Explain event listeners, event objects, event propagation, and event delegation.
Event handling allows a web page to respond to actions such as clicks, keyboard input, form submission, pointer movement, and page loading.
- An event listener is registered with
addEventListener(), which associates an event type with a handler function. - The event object provides information such as the event target, key pressed, pointer position, and modifier keys.
- Event propagation usually occurs in capturing, target, and bubbling phases.
preventDefault()stops the browser's default action, such as submitting a form or following a link.stopPropagation()prevents the event from continuing through the propagation path.- Event delegation attaches one handler to a common ancestor and uses
event.targetorclosest()to identify the actual control.
Event delegation is useful for lists or dynamically generated elements because it reduces the number of listeners and handles elements added after the initial page load.
Explain how dynamic content is generated and updated using JavaScript. Describe a suitable process for creating a list from an array of data.
Dynamic content generation means creating or modifying page content at runtime based on data, user actions, or application state.
A typical process is:
- Store or receive data in an array or object.
- Select the container where the content will be displayed.
- Create elements with
document.createElement(). - Assign text, attributes, and classes to the new elements.
- Add event listeners when necessary.
- Append the elements to a document fragment or container.
- Replace or update the existing content when the data changes.
A DocumentFragment can be used to assemble multiple elements before inserting them into the document, reducing repeated layout work. For untrusted data, use textContent rather than unsafe HTML insertion. A clear rendering function should keep data processing separate from DOM updates and make refresh operations predictable.
Explain important JavaScript accessibility practices for interactive web pages. Include keyboard access, semantic HTML, focus management, and accessible status messages.
Accessibility ensures that users with different abilities can operate and understand a web application.
- Use semantic elements such as
button,nav,main,label, andforminstead of generic elements whenever possible. - Ensure every form control has an associated visible label.
- Make all interactive controls reachable and operable with the keyboard.
- Preserve a logical focus order and provide a visible focus indicator.
- Use buttons for actions and links for navigation rather than simulating them with noninteractive elements.
- Manage focus after dialogs, dynamic updates, and route changes so users know where they are.
- Use appropriate ARIA attributes only when native HTML semantics are insufficient.
- Provide meaningful alternative text for informative images.
- Announce important dynamic status messages using suitable live-region techniques.
- Ensure sufficient color contrast and do not communicate information through color alone.
Accessibility should be considered during design, implementation, and testing with keyboard and assistive technologies.
Describe client-side form validation in JavaScript. Explain the difference between constraint validation and custom validation, and discuss why server-side validation is still necessary.
Form validation checks whether user-provided values satisfy required rules before processing or submission.
- HTML constraint validation uses attributes such as
required,type,minlength,maxlength,min,max, andpattern. - JavaScript can inspect validity through properties such as
checkValidity()andvalidity. - Custom validation is used for rules that HTML cannot express easily, such as matching two passwords or checking relationships between fields.
setCustomValidity()can assign a custom error message, while clearing the message allows the form to become valid.- Validation messages should identify the specific problem and explain how to correct it.
- Errors should be associated with their controls and should be communicated to keyboard and assistive-technology users.
Client-side validation improves usability but cannot be trusted for security because users can bypass it. The server must validate and sanitize all submitted data independently.
What are regular expressions? Explain their structure and describe how they can be used for form validation in JavaScript.
A regular expression is a pattern used to search, match, or replace text. JavaScript represents regular expressions using literal notation such as /pattern/flags or the RegExp constructor.
Important components include:
- Literal characters that must match exactly.
- Character classes such as
[A-Z]or\dfor digits. - Quantifiers such as
*,+,?, and{n,m}. - Anchors such as
^for the beginning and$for the end. - Groups and alternation using parentheses and the
|operator. - Flags such as
ifor case-insensitive matching andgfor global matching.
Methods such as test(), match(), and replace() support regular-expression operations. For validation, anchors should generally be used so that the complete input is checked. Patterns should remain readable, should not be unnecessarily complex, and should not be treated as a substitute for server-side validation.
Explain date and time handling in JavaScript. Discuss the Date object, timestamps, formatting, time zones, and common problems in date calculations.
JavaScript uses the Date object to represent a specific point in time. Internally, a date is generally stored as the number of milliseconds elapsed since the Unix epoch.
new Date()creates an object for the current date and time.- A date can be created from a timestamp or a standardized date string.
- Methods beginning with
getusually use local time, while methods beginning withgetUTCuse Coordinated Universal Time. Date.now()returns the current timestamp in milliseconds.- Methods such as
toISOString()provide a consistent machine-readable format. - Formatting for users should account for locale, time zone, and cultural conventions.
- Date arithmetic can be affected by daylight-saving transitions, leap years, month lengths, and ambiguous input formats.
For reliable applications, store times in a consistent format such as ISO 8601 or UTC, validate incoming values, and format them for the user's locale only at the presentation layer.
Describe audio and video events in HTML5. Explain how JavaScript can control media and respond to playback state changes.
HTML5 <audio> and <video> elements expose media controls and events through the DOM.
playandplayingindicate that playback has started or is actively progressing.pauseindicates that playback has been paused.timeupdateoccurs as the current playback position changes.loadedmetadataindicates that duration and other metadata are available.canplayindicates that enough data is available to begin playback.endedindicates that playback has reached the end.volumechange,seeking,seeked,waiting, anderrorprovide additional state information.
JavaScript can use methods such as play(), pause(), and load(), and properties such as currentTime, duration, volume, and muted. Because browsers may block unsolicited media playback, applications should usually start playback in response to a user gesture and should provide accessible controls and captions where appropriate.
Compare local storage and session storage in the Web Storage API. Explain their methods, limitations, and appropriate use cases.
localStorage and sessionStorage provide key-value storage in the browser.
localStoragepersists data across browser restarts until the application or user removes it.sessionStorageusually persists data only for the lifetime of a particular browser tab or window.- Both APIs provide
setItem(),getItem(),removeItem(), andclear()methods. - Keys and values are stored as strings, so objects and arrays must be converted using
JSON.stringify()and restored usingJSON.parse(). - Storage is synchronous and has limited capacity, so it is not suitable for large datasets or intensive operations.
- Data should be checked for absence and invalid JSON when it is read.
- Sensitive information such as passwords, long-lived authentication secrets, and confidential personal data should not be stored in Web Storage because scripts running on the page may access it.
Use localStorage for non-sensitive preferences and sessionStorage for temporary state associated with a browsing session.
Explain the Fetch API and JSON processing. Describe the complete flow for retrieving data, checking errors, converting the response, and updating the DOM.
The Fetch API provides a promise-based interface for making HTTP requests.
A typical data retrieval flow is:
- Call
fetch()with a URL and optional request configuration. - Wait for the returned promise to resolve to a
Responseobject. - Check
response.okbecause HTTP errors do not automatically reject the fetch promise. - Throw or handle an error when the status is unsuccessful.
- Call
response.json()to asynchronously parse a JSON response. - Validate that the resulting data has the expected structure.
- Render the data into the DOM using safe DOM methods.
- Catch network, parsing, and application-level errors and show an appropriate user-facing state.
async/await can make the sequence easier to read. Applications should also handle loading states, cancellation where appropriate, malformed data, timeouts, and cross-origin restrictions.
Distinguish between JSON and JavaScript objects. Explain JSON serialization and parsing, including common errors and safe processing practices.
A JavaScript object is an in-memory language value, whereas JSON is a text-based data interchange format.
- JSON property names must use double quotes.
- JSON supports strings, numbers, booleans, arrays, objects, and
null. - JSON does not directly support functions,
undefined, comments, or many special JavaScript object types. JSON.stringify()converts a JavaScript value into JSON text.JSON.parse()converts valid JSON text into a JavaScript value.- Invalid syntax causes
JSON.parse()to throw aSyntaxError. - Data received from an external source should be treated as untrusted and validated before use.
- Avoid inserting received strings directly through
innerHTML; usetextContentor carefully constructed DOM nodes.
Serialization is commonly used for API communication and Web Storage, while parsing is needed before application code can access fields in received JSON.
Explain the Geolocation API. Describe how to request the user's location, handle success and failure, and address privacy and usability concerns.
The Geolocation API allows a website to request the device's geographic position, subject to user permission.
navigator.geolocation.getCurrentPosition()requests one location reading.watchPosition()monitors changes over time and returns an identifier that can be passed toclearWatch().- A success callback receives a position object containing coordinates, such as latitude, longitude, accuracy, and sometimes altitude or heading.
- An error callback handles permission denial, unavailable position data, and timeouts.
- Options can specify
enableHighAccuracy,timeout, andmaximumAge. - The page should explain why location is needed before requesting permission.
- Location data should be collected only when necessary, handled securely, and not retained longer than required.
- The interface should provide a useful fallback when permission is denied or location services are unavailable.
Geolocation generally requires a secure context such as HTTPS and is controlled by browser permission policies.
Describe the HTML Drag and Drop API. Explain the roles of dragstart, dragover, and drop events in implementing a draggable interface.
The HTML Drag and Drop API enables users to move or copy items between draggable sources and drop targets.
- The source element must generally have
draggable="true". dragstartfires when dragging begins. The handler can identify the dragged item and store data withdataTransfer.setData().dragoverfires while the pointer is over a potential target. The handler must usually callpreventDefault()to indicate that dropping is allowed.dropfires when the item is released over an accepted target. The handler reads the stored data usingdataTransfer.getData()and updates the interface.dragendcan remove temporary styling and clean up state.dragenteranddragleavecan provide visual feedback when a target is entered or left.
A robust implementation should validate dropped data, prevent accidental actions, and provide a keyboard-accessible alternative because native drag interactions can be difficult for some users and touch devices.
Design a client-side interactive registration form that uses DOM manipulation, event handling, regular expressions, and custom validation. Explain the validation and accessibility workflow.
A suitable design can follow this workflow:
- Use semantic form controls with visible
labelelements and appropriate input types. - Add event listeners for
submit,input, and possiblyblurevents. - Prevent submission with
event.preventDefault()when validation fails. - Use built-in constraints such as
required,type, andminlengthwhere applicable. - Use regular expressions for structured values such as a username or postal code, while keeping the patterns understandable.
- Compare related fields, such as password and confirmation, with custom validation.
- Set field-specific messages using
setCustomValidity()or accessible error elements. - Associate error text with controls using suitable attributes and ensure errors are announced when necessary.
- Move focus to the first invalid control after a failed submission.
- Display a clear success state only after all checks pass.
- Repeat validation on the server because client-side checks can be bypassed.
The form should not rely on color alone and should remain usable with keyboard navigation and assistive technology.
Explain how to build a dynamic data dashboard using Fetch API, JSON, higher-order functions, DOM manipulation, and Web Storage.
A dynamic dashboard can be organized into the following stages:
- Use
fetch()to request JSON data from a server. - Check the response status and handle loading, network, and parsing errors.
- Parse the response with
response.json()and validate the expected fields. - Use higher-order functions such as
filter(),map(), andreduce()to select records, transform values, and calculate summaries. - Render results by creating DOM elements or updating existing elements with
textContentand safe attributes. - Attach delegated event listeners to support filtering, sorting, or selecting records.
- Save non-sensitive user preferences, such as the selected view or filter, in
localStorage. - Restore saved preferences when the page loads and handle missing or malformed storage values.
- Update the interface when the data or user settings change.
Separating data retrieval, transformation, storage, and rendering makes the dashboard easier to test and maintain.
Compare synchronous and asynchronous operations in interactive web development. Explain how loops, callbacks, promises, and async/await affect browser responsiveness.
Synchronous operations execute in sequence and block subsequent JavaScript execution until they finish. Asynchronous operations allow the browser to continue handling user input and rendering while waiting for a timer, network request, or other external operation.
- A large synchronous loop can block the main thread and make the interface unresponsive.
- A callback can run after an asynchronous operation completes.
- A promise represents a future result and supports success and failure processing.
async/awaitprovides readable syntax for consuming promises, but the awaited operation remains asynchronous.- Independent asynchronous tasks can sometimes be started together and coordinated with
Promise.all(). - Long computations may need to be divided into smaller tasks or moved to a Web Worker.
- Errors must be handled with rejection handlers or
try...catcharound awaited operations.
Good interactive code keeps expensive work from blocking the main thread and gives users visible loading, progress, or error states.
Explain loops and iterative programming in JavaScript. Describe the syntax, execution flow, and suitable use cases of for, while, and do...while loops.
Loops allow a program to execute a block of statements repeatedly while a condition remains true or while iterating over a collection.
- A
forloop is suitable when the number of iterations is known or controlled by a counter. It contains initialization, a condition, and an update expression. - A
whileloop is useful when the number of iterations is not known in advance. The condition is checked before every iteration. - A
do...whileloop executes its body at least once because the condition is evaluated after the body. - The
breakstatement terminates a loop immediately. - The
continuestatement skips the remainder of the current iteration and proceeds to the next iteration. - Care must be taken to update loop-control variables; otherwise, an infinite loop may occur.
Loops reduce code duplication and are commonly used for processing arrays, generating dynamic content, and validating repeated input.
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 →