LightReader

Chapter 1 - JavaScript

What are the possible ways to create objects in JavaScript

You can create objects using object literals {}, the new Object() syntax, Object.create(), constructor functions, or ES6 Classes.

What is a prototype chain

It is the mechanism by which objects inherit features from one another. If a property isn't found on an object, the engine looks at its prototype, and so on, until it reaches null.

What is the Difference Between call, apply, and bind

call invokes a function with arguments as a comma-separated list. apply invokes it with arguments as an array. bind returns a new function with a bound this context without executing it immediately.

What is JSON and its common operations

JSON (JavaScript Object Notation) is a text-based data format. Common operations are JSON.parse() to convert a string to an object and JSON.stringify() to convert an object to a string.

What is the purpose of the array slice method

slice() returns a shallow copy of a portion of an array into a new array object. It does not modify the original array.

What is the purpose of the array splice method

splice() is used to change the contents of an array by removing or replacing existing elements and/or adding new elements in place.

What is the difference between slice and splice

slice is immutable (returns a new array) and extracts a section. splice is mutable (modifies the original array) and adds/removes items.

How do you compare Object and Map

Keys in Objects are strings/symbols, while Maps accept any type. Maps preserve insertion order and have a built-in size property, whereas Objects do not.

What is the difference between == and === operators

== checks for value equality with type coercion (loose equality). === checks for both value and type equality (strict equality).

What are lambda expressions or arrow functions

They are a concise syntax for writing function expressions using =>. They do not have their own this, arguments, or super binding.

What is a first class function

A language has first-class functions if functions can be treated like variables: passed as arguments, returned from other functions, and assigned to variables.

What is a first order function

A function that does not accept another function as an argument and does not return a function as its return value.

What is a higher order function

A function that accepts another function as an argument or returns a function as a result (e.g., map, filter, reduce).

What is a unary function

A function that accepts exactly one argument.

What is the currying function

The process of taking a function with multiple arguments and turning it into a sequence of functions each taking a single argument.

What is a pure function

A function where the return value is determined only by its input values, and it produces no side effects (e.g., no external state mutation).

What are the benefits of pure functions

They are easier to test, debug, and parallelize because they don't depend on external state and don't cause side effects.

What is the purpose of the let keyword

It declares a block-scoped local variable, optionally initializing it to a value. It solves scoping issues common with var.

What is the difference between let and var

var is function-scoped and hoisted. let is block-scoped and is not initialized until the definition is evaluated (Temporal Dead Zone).

What is the reason to choose the name let as a keyword

It is adopted from mathematics and early functional programming languages (like Scheme) indicating "Let x be..." for variable binding.

How do you redeclare variables in a switch block without an error

Wrap the case statements in curly braces {} to create a new block scope for that specific case.

What is the Temporal Dead Zone

The time between entering a scope and the actual declaration of a let or const variable. Accessing the variable during this time throws a ReferenceError.

What is an IIFE (Immediately Invoked Function Expression)

A function that runs as soon as it is defined. It is used to create a private scope and avoid polluting the global namespace.

How do you decode or encode a URL in JavaScript?

Use encodeURIComponent() or encodeURI() to encode, and decodeURIComponent() or decodeURI() to decode.

What is memoization

An optimization technique that caches the result of an expensive function call and returns the cached result when the same inputs occur again.

What is Hoisting

JavaScript's behavior of moving variable and function declarations to the top of their containing scope during the compilation phase.

What are classes in ES6

Syntactic sugar over JavaScript's existing prototype-based inheritance, providing a cleaner and more traditional syntax for creating objects and inheritance.

What are closures

A closure is the combination of a function bundled together with references to its surrounding state (the lexical environment).

What are modules

Small units of independent, reusable code. In JS, modules allow you to export specific variables/functions and import them in other files.

Why do you need modules

To organize code, avoid global namespace pollution, improve maintainability, and enable code reuse.

What is scope in javascript

Scope determines the accessibility (visibility) of variables. JS has Global, Function, and Block scope.

What is a service worker

A script that runs in the background, separate from a web page. It enables features like offline support, push notifications, and background sync.

How do you manipulate DOM using a service worker

You cannot access the DOM directly from a Service Worker. You must communicate with the page via the postMessage interface to trigger DOM changes.

How do you reuse information across service worker restarts

By using the IndexedDB API or the Cache API to persist data, as Service Workers are terminated when not in use.

What is IndexedDB

A low-level API for client-side storage of significant amounts of structured data, including files/blobs.

What is web storage

An API (localStorage and sessionStorage) that allows web applications to store data locally within the user's browser.

What is a post message

A method (window.postMessage) that enables safe cross-origin communication between Window objects (e.g., between a page and an iframe).

What is a Cookie

A small piece of data sent from a website and stored on the user's computer by the user's web browser while browsing.

Why do you need a Cookie

Primarily for session management (logins), personalization (user preferences), and tracking (analyzing user behavior).

What are the options in a cookie

Common options include Expires, Domain, Path, Secure (HTTPS only), and HttpOnly (inaccessible to JS).

How do you delete a cookie

Set the cookie's expiration date to a time in the past using document.cookie.

What are the differences between cookie, local storage and session storage

Cookies are sent to the server and strictly limited in size (4kb). Local/Session storage stays on the client and holds more data (5MB+).

What is the main difference between localStorage and sessionStorage

localStorage persists data even after the browser is closed. sessionStorage data is cleared when the page session ends (tab closes).

How do you access web storage

Via the global objects: window.localStorage or window.sessionStorage.

What are the methods available on session storage

setItem(key, value), getItem(key), removeItem(key), clear(), and key(index).

What is a storage event and its event handler

An event fired on the window object when a storage area changes in the context of another document (e.g., another tab).

Why do you need web storage

To store data on the client side without affecting website performance and without sending data to the server with every request (unlike cookies).

How do you check web storage browser support

Check if typeof(Storage) !== "undefined" in a conditional statement.

How do you check web workers browser support

Check if typeof(Worker) !== "undefined" in a conditional statement.

Give an example of a web worker

A script that processes large data arrays or performs image manipulation in the background without freezing the UI.

What are the restrictions of web workers on DOM

Web workers generally cannot access the DOM (document object), the window object, or parent page properties directly.

What is a promise

An object representing the eventual completion or failure of an asynchronous operation and its resulting value.

Why do you need a promise

To handle asynchronous operations more cleanly than callbacks, avoiding "callback hell" and simplifying error handling.

Explain the three states of promise

Pending (initial state), Fulfilled (operation completed successfully), and Rejected (operation failed).

What is a callback function

A function passed into another function as an argument, which is then invoked inside the outer function to complete some routine.

Why do we need callbacks

To ensure that a function is not executed before a task is completed (essential for asynchronous logic like API calls or timers).

What is a callback hell

A situation where callbacks are nested within other callbacks several levels deep, making code difficult to read and maintain.

What are server-sent events

A standard allowing a web page to get updates from a server automatically via a persistent HTTP connection (uni-directional).

How do you receive server-sent event notifications

By creating an EventSource object and attaching an onmessage event handler to it.

How do you check browser support for server-sent events

Check if typeof(EventSource) !== "undefined".

What are the events available for server sent events

onopen (connection established), onmessage (message received), and onerror (error occurred).

What are the main rules of promise

A promise is immutable once settled (fulfilled or rejected) and can only succeed or fail once.

What is callback in callback

Refers to nesting a callback function inside another callback function, often leading to deep nesting.

What is promise chaining

Executing a sequence of asynchronous tasks one after another by returning a new Promise from a .then() callback.

What is promise.all

A method that takes an iterable of promises and returns a single Promise that resolves when all input promises resolve (or rejects if one rejects).

What is the purpose of the race method in promise

Promise.race() returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects.

What is a strict mode in javascript

A way to opt in to a restricted variant of JavaScript that eliminates some silent errors and prohibits some poor syntax.

Why do you need strict mode

To write safer code, prevent accidental globals, catch silent errors, and prepare for future JS versions.

How do you declare strict mode

Add the string "use strict"; at the beginning of a script or a function.

What is the purpose of double exclamation

The !! operator converts a value to its boolean equivalent (true or false).

What is the purpose of the delete operator

It removes a property from an object. If successful, the property is removed and the expression returns true.

What is typeof operator

An operator that returns a string indicating the type of the unevaluated operand (e.g., "number", "string", "object").

What is undefined property

Refers to a property that has not been assigned a value, or accessing a property that does not exist on an object.

What is null value

A primitive value that represents the intentional absence of any object value.

What is the difference between null and undefined

undefined means a variable has been declared but not defined. null is an assignment value meant to represent "no value".

What is eval

A function that evaluates a string of text as JavaScript code. It is generally discouraged due to security and performance risks.

What is the difference between window and document

window is the global object representing the browser window/tab. document is a property of window representing the loaded DOM content.

How do you access history in javascript

Using the window.history object, which contains the browser's session history (methods: back(), forward(), go()).

How do you detect caps lock key turned on or not

Use the getModifierState("CapsLock") method on a keyboard event or mouse event.

What is isNaN

A function that determines whether a value is "Not-a-Number". Note: The global isNaN coerces values; Number.isNaN does not.

What are the differences between undeclared and undefined variables

Undefined variables are declared but have no value. Undeclared variables do not exist in the scope and accessing them throws a ReferenceError.

What are global variables

Variables declared outside any function or block, or attached to the window object, accessible from anywhere in the code.

What are the problems with global variables

They can lead to naming collisions, are hard to debug, and make code harder to maintain and test.

What is NaN property

It represents a value that is "Not-a-Number", typically the result of an invalid mathematical operation.

What is the purpose of isFinite function

It determines whether a passed value is a finite number (i.e., not Infinity, -Infinity, or NaN).

What is an event flow

The order in which events are received on the page. It consists of three phases: Capturing, Target, and Bubbling.

What is event capturing

The event starts from the window and goes down the DOM tree to the target element.

What is event bubbling

The event starts from the target element and bubbles up the DOM tree to the window.

How do you submit a form using JavaScript

By accessing the form element and calling its submit() method: document.getElementById("myForm").submit().

How do you find operating system details

You can use navigator.platform (deprecated but common) or navigator.userAgent to parse OS details.

What is the difference between document load and DOMContentLoaded events

DOMContentLoaded fires when HTML is parsed and DOM is ready. load fires when HTML and all resources (images, css) are fully loaded.

What is the difference between native, host and user objects

Native: Built-in JS objects (Array, Date). Host: Provided by env (window, document). User: Created by the developer.

What are the tools or techniques used for debugging JavaScript code

Browser DevTools (Console, Sources/Debugger), console.log, debugger statement, and IDE debuggers.

What are the pros and cons of promises over callbacks

Pros: Better readability, chaining, centralized error handling. Cons: Slightly higher complexity than simple callbacks, cannot be cancelled (natively).

What is the difference between an attribute and a property

Attributes are defined in HTML (initial state). Properties are on the DOM object (current state).

What is same-origin policy

A security measure that prevents a script loaded from one origin from interacting with resources from a different origin.

What is the purpose of void 0

It evaluates to undefined. It was historically used to prevent links from navigating (href="void(0)").

Is JavaScript a compiled or interpreted language

Modern JS is JIT (Just-In-Time) compiled. The engine compiles code to bytecode/machine code immediately before execution.

Is JavaScript a case-sensitive language

Yes, identifiers, keywords, and variables are case-sensitive (e.g., myVar is different from MyVar).

Is there any relation between Java and JavaScript

No. They are different languages with different paradigms. The name was a marketing tactic by Netscape.

What are events

Actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond (e.g., clicks, keypresses).

Who created javascript

Brendan Eich created JavaScript in 1995 while working at Netscape.

What is the use of preventDefault method

It stops the default action of an event from happening (e.g., prevents a form from submitting or a link from navigating).

What is the use of stopPropagation method

It prevents the event from bubbling up the DOM tree, stopping parent handlers from being notified of the event.

What are the steps involved in return false usage

In jQuery or inline HTML handlers, return false calls both preventDefault() and stopPropagation().

What is BOM

Browser Object Model. It allows JavaScript to talk to the browser (window, navigator, history, location) outside the DOM.

What is the use of setTimeout

Executes a function or specified piece of code once after the timer expires (specified in milliseconds).

What is the use of setInterval

Repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.

Why is JavaScript treated as Single threaded

It has a single call stack and executes code sequentially. Async tasks are handled via the Event Loop, not parallel threads.

What is an event delegation

Attaching a single event listener to a parent element to manage events for all its children (using bubbling), rather than listeners on every child.

What is ECMAScript

The standard specification that JavaScript implements. It ensures interoperability across browsers.

What is JSON

JavaScript Object Notation. A lightweight data-interchange format that is easy for humans to read/write and machines to parse/generate.

What are the syntax rules of JSON

Data is in name/value pairs, data is separated by commas, curly braces hold objects, and square brackets hold arrays. Keys must be double-quoted.

What is the purpose JSON stringify

To convert a JavaScript object or value to a JSON string.

How do you parse JSON string

Using JSON.parse(), which converts a JSON string back into a JavaScript object.

Why do you need JSON

To transmit data between a server and a web application, as it is language-independent and lightweight.

What are PWAs

Progressive Web Apps. Web apps that use modern web capabilities (Service Workers, Manifests) to deliver an app-like experience (offline, installable).

What is the purpose of clearTimeout method

It cancels a timeout previously established by calling setTimeout().

What is the purpose of clearInterval method

It cancels a timed, repeating action which was previously established by a call to setInterval().

How do you redirect new page in javascript

By assigning a new URL to window.location.href or using window.location.assign().

How do you check whether a string contains a substring

Use string.includes(substring), string.indexOf(substring) !== -1, or Regex.

How do you validate an email in javascript

Typically using a Regular Expression (Regex) to check for the pattern [email protected].

How do you get the current url with javascript

Using window.location.href.

What are the various url properties of location object

href, protocol, host, hostname, port, pathname, search, hash, and origin.

How do get query string values in javascript

Use new URLSearchParams(window.location.search) and then .get('paramName').

How do you check if a key exists in an object

Use the in operator ('key' in obj) or obj.hasOwnProperty('key').

How do you loop through or enumerate javascript object

Use for...in loop, or Object.keys(), Object.values(), or Object.entries() combined with a loop.

How do you test for an empty object

Check if Object.keys(obj).length === 0 and obj.constructor === Object.

What is an arguments object

An array-like object accessible inside functions that contains the values of the arguments passed to that function.

How do you make first letter of the string in an uppercase

str.charAt(0).toUpperCase() + str.slice(1).

What are the pros and cons of for loops

Pros: Fast, break/continue support. Cons: Verbose, manual index handling, prone to off-by-one errors.

How do you display the current date in javascript

new Date() creates a Date object with the current date and time.

How do you compare two date objects

Subtract them (date1 - date2) or compare their timestamps using .getTime().

How do you check if a string starts with another string

Use the string.startsWith(substring) method.

How do you trim a string in javascript

Use string.trim() to remove whitespace from both ends.

How do you add a key value pair in javascript

object.key = value or object['key'] = value.

Is the !-- notation represents a special operator

No. It is processed as ! (not) followed by -- (decrement prefix), which is valid but confusing syntax.

How do you assign default values to variables

Use the logical OR operator (val || default) or ES6 default parameters in functions.

How do you define multiline strings

Use Template Literals (backticks ` `) or append lines with \n and + concatenation.

What is an app shell model

A design pattern for PWAs where the minimal UI structure (HTML/CSS) is cached immediately, and content is loaded dynamically.

Can we define properties for functions

Yes, functions are objects in JavaScript, so you can attach properties to them.

What is the way to find the number of parameters expected by a function

Use the function.length property.

What is a polyfill

Code (usually a function) that implements a feature on web browsers that do not support the feature natively.

What are break and continue statements

break exits the loop entirely. continue skips the current iteration and proceeds to the next one.

What are js labels

Identifiers followed by a colon (label:) used to prefix a loop, allowing break or continue to target that specific loop.

What are the benefits of keeping declarations at the top

Cleaner code, avoids confusion with hoisting, and makes it easier to see local variables.

What are the benefits of initializing variables

Prevents undefined values, clarifies intended data type, and reduces runtime errors.

What are the recommendations to create new object

Use object literals {} for simple objects. Use Classes or Constructor functions for multiple instances.

How do you define JSON arrays

Using square brackets [] inside the JSON structure, e.g., "users": ["A", "B"].

How do you generate random integers

Math.floor(Math.random() * (max - min + 1)) + min.

Can you write a random integers function to print integers within a range

Yes, combine Math.random(), Math.floor(), and arithmetic to scale to the range.

What is tree shaking

A build step (e.g., in Webpack) that removes unused code from the final bundle to reduce file size.

What is the need of tree shaking

To optimize performance by ensuring the browser only downloads the code that is actually used.

Is it recommended to use eval

No. It poses security risks (injection attacks) and is slower because it invokes the JS compiler at runtime.

What is a Regular Expression

A sequence of characters that forms a search pattern, used for text search and replace operations.

What are the string methods that accept Regular expression

match(), replace(), search(), split(), and matchAll().

What are modifiers in regular expression

Flags that change the search behavior: i (case-insensitive), g (global), m (multiline).

What are regular expression patterns

Characters defining the search, e.g., \d (digits), [a-z] (range), ^ (start), $ (end).

What is a RegExp object

A built-in object for matching text with a pattern. Created via literal /pattern/ or new RegExp().

How do you search a string for a pattern

Use str.search(/pattern/) or regex.test(str).

What is the purpose of exec method

It executes a search on a string using a regex and returns an array of results (or null) with detailed match info.

How do you change the style of a HTML element

Access the style property: element.style.color = "red".

What would be the result of 1+2+'3'

"33". First 1+2 becomes 3 (number), then 3 + '3' causes concatenation.

What is a debugger statement

A keyword that stops the execution of JavaScript and calls the available debugging functionality (if open).

What is the purpose of breakpoints in debugging

They allow you to pause code execution at a specific line to inspect variables and call stack.

Can I use reserved words as identifiers

No, reserved words (like if, for, class) cannot be used as variable or function names.

How do you detect a mobile browser

Regex check on navigator.userAgent (e.g., looking for "Mobi" or "Android").

How do you detect a mobile browser without regexp

Check navigator.maxTouchPoints > 0 or screen width, though UserAgent is more reliable for "mobile vs desktop" intent.

How do you get the image width and height using JS

Use imgElement.naturalWidth and imgElement.naturalHeight (for original) or .width/.height (for rendered).

How do you make synchronous HTTP request

Use XMLHttpRequest with the third parameter set to false. (Deprecated and blocks the UI).

How do you make asynchronous HTTP request

Use fetch() API or XMLHttpRequest (default is async).

How do you convert date to another timezone in javascript

Use date.toLocaleString("en-US", {timeZone: "ZoneName"}).

What are the properties used to get size of window

window.innerWidth and window.innerHeight.

What is a conditional operator in javascript

The ternary operator: condition ? exprIfTrue : exprIfFalse.

Can you apply chaining on conditional operator

Yes, cond1 ? val1 : cond2 ? val2 : val3.

What are the ways to execute javascript after a page load

window.== but with special handling for NaN and signed zeros.

How do you copy properties from one object to other

Object.assign(target, source) or using spread syntax {...source}.

What are the applications of the assign method

Cloning objects (shallow), merging objects, or setting default properties.

What is a proxy object

An object that wraps another object to intercept and redefine fundamental operations (like property lookup, assignment).

What is the purpose of the seal method

Object.seal(obj) prevents adding new properties but allows modifying existing ones.

What are the applications of the seal method

To create a fixed-shape object where values can change but the structure cannot.

What are the differences between the freeze and seal methods

Freeze makes properties immutable (read-only). Seal allows existing properties to be changed but prevents addition/deletion.

How do you determine if an object is sealed or not

Use Object.isSealed(obj).

How do you get enumerable key and value pairs

Use Object.entries(obj).

What is the main difference between Object.values and Object.entries method

Object.values returns an array of values. Object.entries returns an array of [key, value] pairs.

How can you get the list of keys of any object

Use Object.keys(obj).

How do you create an object with a prototype

Use Object.create(prototypeObject).

What is a WeakSet

A collection of objects where references are "weak" (don't prevent garbage collection) and values must be objects.

What are the differences between WeakSet and Set

WeakSet only holds objects, is not iterable, and allows garbage collection of its items. Set holds any type and is iterable.

List down the collection of methods available on WeakSet

add(value), delete(value), and has(value).

What is a WeakMap

A Map where keys must be objects and are held weakly.

What are the differences between WeakMap and Map

WeakMap keys must be objects and are not iterable. Map keys can be anything and are iterable.

List down the collection of methods available on WeakMap

set(key, value), get(key), delete(key), has(key).

What is the purpose of uneval

A non-standard Mozilla method to create a string representation of the source code of an object (deprecated).

How do you encode an URL

encodeURI() (for full URL) or encodeURIComponent() (for query parameters).

How do you decode an URL

decodeURI() or decodeURIComponent().

How do you print the contents of web page

Use window.print().

What is the difference between uneval and eval

uneval (deprecated) turns object to code string. eval executes code string.

What is an anonymous function

A function without a name, often used as a callback or in an IIFE.

What is the precedence order between local and global variables

Local variables take precedence over global variables with the same name.

What are javascript accessors

Methods (get and set) used to get or set the value of an object property dynamically.

How do you define property on Object constructor

Use Object.defineProperty(obj, prop, descriptor).

What is the difference between get and defineProperty

get is syntax inside object literals/classes. defineProperty is a method to add getters dynamically or with specific flags.

What are the advantages of Getters and Setters

They allow computed properties, validation on assignment, and encapsulation of internal state.

Can I add getters and setters using defineProperty method

Yes, by providing get and set functions in the descriptor object.

What is the purpose of switch-case

To execute one of many code blocks based on the value of an expression.

What are the conventions to be followed for the usage of switch case

Always include a default case, use break statements, and consider using blocks {} for variable scope.

What are primitive data types

String, Number, BigInt, Boolean, Undefined, Null, Symbol.

What are the different ways to access object properties

Dot notation (obj.prop) and Bracket notation (obj['prop']).

What are the function parameter rules

No data types for parameters, no check on number of args passed (missing are undefined).

What is an error object

A built-in object that provides error details when an exception is thrown (message, name, stack).

When do you get a syntax error

When the JavaScript engine encounters code that violates the language's syntax rules during parsing.

What are the different error names from error object

Error, ReferenceError, SyntaxError, TypeError, URIError, RangeError, EvalError.

What are the various statements in error handling

try, catch, finally, throw.

What are the two types of loops in javascript

Entry controlled (for, while) and Exit controlled (do-while).

What is nodejs

A runtime environment that lets you execute JavaScript on the server side, built on Chrome's V8 engine.

What is the Intl object

A namespace for the ECMAScript Internationalization API (formatting dates, numbers, currencies).

How do you perform language specific date and time formatting

Use new Intl.DateTimeFormat('locale', options).format(date).

What is an Iterator

An object that implements the iterator protocol (has a next() method returning {value, done}).

How does synchronous iteration works

Using loops like for...of which automatically call the next() method of an iterator.

What is the event loop

A mechanism that handles asynchronous callbacks by processing the message queue and executing tasks when the stack is empty.

What is the call stack

A LIFO (Last In, First Out) data structure that records where in the program we are (what function is running).

What is the event queue

A list of messages/callbacks waiting to be processed by the Event Loop once the call stack is empty.

What is a decorator

A design pattern (and proposed JS syntax @decorator) used to modify the behavior of classes or methods.

What are the properties of the Intl object

Collator, DateTimeFormat, NumberFormat, etc.

What is an Unary operator

An operator that performs an operation on a single operand (e.g., typeof, delete, ++, !).

How do you sort elements in an array

Use array.sort(). By default, it sorts strings alphabetically.

What is the purpose of compareFunction while sorting arrays

To define an alternative sort order (e.g., numerical sort), as default sort converts items to strings.

How do you reverse an array

Use array.reverse().

How do you find the min and max values in an array

Math.min(...arr) and Math.max(...arr).

How do you find the min and max values without Math functions

Loop through the array or use reduce to track the lowest/highest value.

What is an empty statement and purpose of it

A semicolon by itself ;. Used when a statement is required by syntax but no action is needed (e.g., in a loop).

How do you get the metadata of a module

Using import.meta (e.g., import.meta.url).

What is the comma operator

Evaluates each of its operands (from left to right) and returns the value of the last operand.

What is the advantage of the comma operator

Allows multiple expressions where only one is expected (e.g., inside a for loop update clause).

What is typescript

A superset of JavaScript that adds static typing. It compiles down to plain JavaScript.

What are the differences between javascript and typescript

TS has static typing, interfaces, and compile-time checks. JS is dynamically typed.

What are the advantages of typescript over javascript

Earlier error detection, better IDE support (IntelliSense), and improved maintainability for large codebases.

What is an object initializer

The syntax for creating objects using curly braces { key: value } (Object Literal).

What is a constructor method

A special method constructor() in a class used for initializing new objects.

What happens if you write constructor more than once in a class

It throws a SyntaxError. A class can only have one constructor.

How do you call the constructor of a parent class

Use super() inside the child class constructor.

How do you get the prototype of an object

Object.getPrototypeOf(obj).

What happens If I pass string type for getPrototype method

In ES6, it coerces the string to a String object and returns String.prototype.

How do you set the prototype of one object to another

Object.setPrototypeOf(obj, newProto) or using Object.create(newProto).

How do you check whether an object can be extended or not

Use Object.isExtensible(obj).

How do you prevent an object from being extend

Use Object.preventExtensions(obj).

What are the different ways to make an object non-extensible

preventExtensions, seal (prevents extension + config), freeze (prevents extension + config + write).

How do you define multiple properties on an object

Object.defineProperties(obj, descriptors).

What is the MEAN stack

A full-stack framework: MongoDB, Express.js, Angular, Node.js.

What is obfuscation in javascript

The process of transforming code into a version that is difficult to understand but works the same, to protect logic.

Why do you need Obfuscation

To protect intellectual property and make reverse engineering difficult.

What is Minification

Removing unnecessary characters (whitespace, comments) and shortening variable names to reduce file size.

What are the advantages of minification

Faster download times, reduced bandwidth usage, and faster script parsing.

What are the differences between obfuscation and Encryption

Obfuscation makes code hard to read but it's still executable. Encryption hides data requiring a key to decode before use.

What are the common tools used for minification

UglifyJS, Terser, Google Closure Compiler.

How do you perform form validation using javascript

Access form values, check against rules (regex, logic), and show error messages if invalid before submission.

How do you perform form validation without javascript

Use HTML5 attributes like required, pattern, min, max, type="email".

What are the DOM methods available for constraint validation

checkValidity(), reportValidity(), setCustomValidity().

What are the available constraint validation DOM properties

validity, validationMessage, willValidate.

What are the validity properties

Properties of the validity object: valueMissing, typeMismatch, patternMismatch, valid, etc.

Give an example usage of the rangeOverflow property

Checks if an input value is higher than the max attribute: input.validity.rangeOverflow.

Are enums available in javascript

Not natively. You can simulate them using Object.freeze({ KEY: 1, KEY2: 2 }) or use TypeScript.

What is an enum

A data type consisting of a set of named values (constants).

How do you list all properties of an object

Object.getOwnPropertyNames(obj) (includes non-enumerable) or Object.keys(obj) (enumerable only).

How do you get property descriptors of an object

Object.getOwnPropertyDescriptor(obj, prop) or Object.getOwnPropertyDescriptors(obj).

What are the attributes provided by a property descriptor

value, writable, enumerable, configurable, get, set.

How do you extend classes

Use the extends keyword: class Child extends Parent {}.

How do I modify the url without reloading the page

Use history.pushState(state, title, url) or history.replaceState().

How do you check whether or not an array includes a particular value

array.includes(value).

How do you compare scalar arrays

Loop through and compare length and values at each index, or JSON.stringify(arr1) === JSON.stringify(arr2) (simple cases).

How to get the value from get parameters

new URLSearchParams(window.location.search).get('key').

How do you print numbers with commas as thousand separators

number.toLocaleString().

What is the difference between java and javascript

Java is strictly typed, compiled, and OOP-centric. JS is dynamic, interpreted, and multi-paradigm.

Does JavaScript support namespaces

Not natively (like C#), but simulated using Objects or Modules to group code.

How do you declare a namespace

var MyApp = MyApp || {}; then add properties MyApp.utils = ....

How do you invoke javascript code in an iframe from the parent page

document.getElementById('iframe').contentWindow.functionName().

How do you get the timezone offset of a date object

date.getTimezoneOffset() returns the difference in minutes between UTC and local time.

How do you load CSS and JS files dynamically

Create or