FAQ Portal
Categories
Search
About
Contacts
UK
RU
EN
Home
Technology
Programming
JavaScript
JavaScript
100 questions
What is the difference between var, let, and const?
•
var — function scope, hoisting.
•
let — block scope, cannot be redeclared.
•
const — block scope, cannot be reassigned.
•
const objects can be mutated.
•
Use const by default, let if necessary.
What data types are in JavaScript?
•
Primitives: string, number, boolean, null, undefined, symbol, bigint.
•
Objects: object, array, function.
•
typeof checks the type.
•
null is an object (historical bug).
•
NaN is a number.
What is hoisting?
•
Moving declarations to the top of the scope.
•
var is hoisted with undefined.
•
let/const are hoisted but in the temporal dead zone.
•
Functions are hoisted entirely.
•
Only declarations, not assignments.
How do == and === work?
•
== compares with type coercion.
•
'5' == 5 returns true.
•
=== is strict comparison without coercion.
•
'5' === 5 returns false.
•
Always use ===.
What are truthy and falsy values?
•
Falsy: false, 0, '', null, undefined, NaN.
•
Everything else is truthy.
•
[] and {} are truthy!
•
Used in if conditions.
•
Boolean(value) for explicit conversion.
How do logical operators work?
•
&& — returns the first falsy or the last value.
•
|| — returns the first truthy or the last value.
•
?? — nullish coalescing (null/undefined only).
•
! — negation.
•
Short-circuit evaluation.
What are template literals?
•
Strings in backticks: `text`.
•
Interpolation: `Hello ${name}`.
•
Multiline strings.
•
Tagged templates: tag`text`.
•
Nested expressions: `${a + b}`.
How to declare a function?
•
Function declaration: function name() {}.
•
Function expression: const fn = function() {}.
•
Arrow function: const fn = () => {}.
•
Declaration hoisting, expression not.
•
IIFE: (function() {})().
How do arrow functions work?
•
Short syntax: (x) => x *
2.
•
Without {} — implicit return.
•
Do not have their own this.
•
Do not have arguments.
•
Cannot be used as constructors.
What is scope (visibility scope)?
•
Global scope — accessible everywhere.
•
Function scope — inside a function.
•
Block scope — inside {} (let, const).
•
Lexical scope — determined at writing.
•
Scope chain for variable lookup.
What is closure?
•
A function remembers its lexical environment.
•
Access to external variables after exiting the function.
•
Used for private variables.
•
Function factories.
•
Currying.
How does this work?
•
In an object method — the object itself.
•
In a regular function — window/undefined.
•
In an arrow function — from the outer context.
•
With new — a new object.
•
call/apply/bind — explicit binding.
What are call, apply, bind?
•
call — invocation with this and arguments: fn.call(obj, a, b).
•
apply — arguments as an array: fn.apply(obj, [a, b]).
•
bind — returns a new function with bound this.
•
bind does not invoke the function immediately.
•
Useful for method borrowing.
How to work with arrays?
•
Creation: [], new Array(), Array.from().
•
push/pop — end, shift/unshift — start.
•
slice — copy of a part, splice — modification.
•
concat, spread for merging.
•
includes, indexOf for searching.
Which array methods are for iteration?
•
forEach — no return.
•
map — transformation.
•
filter — filtering.
•
reduce — folding.
•
find/findIndex — searching.
•
some/every — checking.
How does reduce work?
•
arr.reduce((acc, curr) => acc + curr, 0).
•
Second argument — initial value.
•
Returns a single value.
•
Can create an object, array.
•
Powerful but complex to read.
How to work with objects?
•
Creation: {}, new Object().
•
Access: obj.key, obj['key'].
•
Object.keys/values/entries.
•
Spread: {...obj1, ...obj2}.
•
Object.assign for copying.
What is destructuring?
•
Arrays: const [a, b] = [1, 2].
•
Objects: const {name, age} = user.
•
Renaming: const {name: n} = user.
•
Default values: const {x = 0} = obj.
•
Nested: const {a: {b}} = obj.
What are spread and rest?
•
Spread (...) expands.
•
[...arr1, ...arr2] — merging.
•
{...obj, newKey: val}.
•
Rest collects: function f(...args).
•
In destructuring: const [first, ...rest] = arr.
How deeply to copy an object?
•
structuredClone(obj) — modern.
•
JSON.parse(JSON.stringify(obj)).
•
Lodash: _.cloneDeep().
•
Recursive function.
•
Spread — only shallow copy.
What are Map and Set?
•
Map — key of any type.
•
new Map(), set(), get(), has().
•
Set — unique values.
•
add(), has(), delete().
•
WeakMap, WeakSet — weak references.
What is Symbol?
•
Unique primitive type.
•
Symbol('desc') !== Symbol('desc').
•
For unique object keys.
•
Symbol.for() — global registry.
•
Well-known: Symbol.iterator.
How to work with strings?
•
Methods: length, charAt, slice, substring.
•
split, join, trim.
•
toLowerCase, toUpperCase.
•
includes, startsWith, endsWith.
•
replace, replaceAll.
•
padStart, padEnd.
What are regular expressions?
•
/pattern/flags or new RegExp().
•
test() — check.
•
match(), matchAll() — search.
•
replace() — substitution.
•
Flags: g, i, m, s, u.
How to work with numbers?
•
parseInt, parseFloat.
•
Number.isNaN(), Number.isFinite().
•
toFixed(), toPrecision().
•
Math: round, floor, ceil, random.
•
BigInt for large numbers.
What is asynchronous in JS?
•
JavaScript is single-threaded.
•
Async operations do not block.
•
Callbacks, Promises, async/await.
•
Event Loop processes queue.
•
Web APIs perform async tasks.
What is Event Loop?
•
Asynchronous mechanism.
•
Call Stack — code execution.
•
Task Queue — callbacks.
•
Microtask Queue — promises.
•
Microtasks have higher priority.
What are callbacks?
•
Function passed as argument.
•
Called after operation completes.
•
Callback hell — nested callbacks.
•
First argument often error.
•
Replaced by Promises.
What is Promise?
•
Object for async operations.
•
States: pending, fulfilled, rejected.
•
new Promise((resolve, reject) => {}).
•
then(), catch(), finally().
•
Chainable — chains.
How to create a Promise?
•
new Promise((resolve, reject) => { ... }).
•
resolve(value) on success.
•
reject(error) on failure.
•
Promise.resolve(value) — immediately resolved.
•
Promise.reject(error) — immediately rejected.
How to handle Promise errors?
•
.catch(error => {}).
•
Second argument of .then(null, onRejected).
•
catch catches all errors in the chain.
•
Unhandled rejection — unhandledrejection.
•
finally() always executes.
What is Promise.all?
•
Promise.all([p1, p2, p3]).
•
Waits for all promises.
•
Returns an array of results.
•
Rejects on the first error.
•
Parallel execution.
What are Promise.race, allSettled, any?
•
race — first to settle (success or error).
•
allSettled — waits for all, returns statuses.
•
any — first successful.
•
allSettled does not reject.
•
any rejects if all are rejected.
How does async/await work?
•
async function returns a Promise.
•
await pauses execution.
•
Only inside async functions.
•
try/catch for errors.
•
Syntactic sugar over Promises.
How to handle errors in async/await?
•
try { await ... } catch (e) { }.
•
Or .catch() on the call.
•
finally for cleanup.
•
Can be combined.
•
Unhandled — unhandledrejection.
How to run async functions in parallel?
•
await Promise.all([fn1(), fn2()]).
•
Do not await each separately.
•
Results in an array.
•
Promise.allSettled if all results are needed.
•
Destructuring: const [a, b] = await Promise.all([...]).
What are setTimeout and setInterval?
•
setTimeout(fn, ms) — one time.
•
setInterval(fn, ms) — recurring.
•
clearTimeout, clearInterval to cancel.
•
Return timer ID.
•
Minimum delay ~4ms.
What is requestAnimationFrame?
•
For animations, synchronized with the screen.
•
Usually ~60fps.
•
cancelAnimationFrame to cancel.
•
More efficient than setInterval for animations.
•
Pauses in background tabs.
What is fetch API?
•
Modern way of HTTP requests.
•
fetch(url, options).
•
Returns a Promise.
•
response.json(), .text(), .blob().
•
Does not reject on 404, 500.
How to make a POST request with fetch?
•
fetch(url, { method: 'POST', headers: {...}, body: JSON.stringify(data) }).
•
Content-Type: application/json.
•
FormData for files.
•
await response.json().
•
Check response.ok.
How to cancel a fetch request?
•
AbortController.
•
const controller = new AbortController().
•
fetch(url, { signal: controller.signal }).
•
controller.abort() to cancel.
•
Catch AbortError.
What are Web Workers?
•
Running JS in a separate thread.
•
new Worker('worker.js').
•
postMessage for communication.
•
onmessage for receiving.
•
No access to DOM.
What are Service Workers?
•
Proxy between browser and network.
•
Offline functionality.
•
Push notifications.
•
Caching resources.
•
Only work on HTTPS.
What is WebSocket?
•
Two-way communication with server.
•
new WebSocket('ws://...').
•
onopen, onmessage, onclose, onerror.
•
send() for sending.
•
Persistent connection.
What is queueMicrotask?
•
Adds a microtask.
•
Executes after current code.
•
Higher priority than setTimeout.
•
queueMicrotask(() => {}).
•
Like Promise.resolve().then().
What is prototype inheritance?
•
Each object has [[Prototype]].
•
Property lookup through the chain.
•
Object.getPrototypeOf().
•
Object.create() for creation.
•
__proto__ — getter/setter.
How do ES6 classes work?
•
class Name { constructor() {} }.
•
Syntactic sugar over prototypes.
•
extends for inheritance.
•
super() calls parent.
•
Methods in prototype.
What is static in classes?
•
static method() {} — static method.
•
static property = value.
•
Call: ClassName.method().
•
Not accessible via instance.
•
For utility functions.
What are getter and setter?
•
get propertyName() { return this._value; }.
•
set propertyName(val) { this._value = val; }.
•
Called as properties, not methods.
•
For validation, computed properties.
•
Also in object literals.
What are private class fields?
•
#privateField — private property.
•
#privateMethod() {} — private method.
•
Accessible only inside the class.
•
Error when accessed from outside.
•
ES2022+.
How does class inheritance work?
•
class Child extends Parent {}.
•
super() in constructor is mandatory first.
•
super.method() calls the parent method.
•
Overriding methods.
•
instanceof for checking.
What is new.target?
•
Indicates the constructor called with new.
•
undefined if called without new.
•
For abstract classes.
•
In arrow functions — from external context.
•
ES6+.
What is instanceof?
•
obj instanceof Class.
•
Checks the prototype chain.
•
Works with classes and constructor functions.
•
Symbol.hasInstance for customization.
•
typeof for primitives.
What are mixins?
•
Adding methods to a class.
•
Object.assign(Class.prototype, mixin).
•
Or through extends with a function.
•
Composition of behavior.
•
Alternative to multiple inheritance.
What is Object.create()?
•
Creates an object with a specified prototype.
•
Object.create(proto, descriptors).
•
Object.create(null) — without a prototype.
•
For pure inheritance.
•
Descriptors for properties.
What is Object.defineProperty?
•
Defines a property with a descriptor.
•
value, writable, enumerable, configurable.
•
get, set for accessor.
•
Defaults to false for flags.
•
Object.getOwnPropertyDescriptor.
What is Proxy?
•
Wrapper for intercepting operations.
•
new Proxy(target, handler).
•
Traps: get, set, apply, construct.
•
For reactivity, validation.
•
Reflect for calling the original.
What is Reflect?
•
Methods for object operations.
•
Reflect.get, set, has, deleteProperty.
•
Returns boolean instead of throwing.
•
Works with Proxy.
•
More explicit API.
How to make an object immutable?
•
Object.freeze() — complete freeze.
•
Object.seal() — cannot add/remove properties.
•
Object.preventExtensions() — cannot add properties.
•
Check with isFrozen, isSealed.
•
Shallow freeze.
What is Object.entries/keys/values?
•
keys — array of keys.
•
values — array of values.
•
entries — array of [key, value].
•
Only enumerable own properties.
•
Object.fromEntries for reverse.
How to select DOM elements?
•
getElementById — by id.
•
querySelector — CSS selector.
•
querySelectorAll — all matches.
•
getElementsByClassName, getElementsByTagName.
•
querySelector returns the first.
How to change element content?
•
textContent — only text.
•
innerHTML — HTML markup.
•
innerText — visible text.
•
innerHTML is dangerous for XSS.
•
Use textContent for security.
How to work with attributes?
•
getAttribute(), setAttribute().
•
removeAttribute().
•
hasAttribute().
•
dataset for data-* attributes.
•
el.dataset.userId for data-user-id.
How to work with element classes?
•
classList.add(), remove(), toggle().
•
classList.contains() — check.
•
classList.replace(old, new).
•
className — string of all classes.
•
classList — DOMTokenList.
How to change element styles?
•
el.style.color = 'red'.
•
el.style.backgroundColor (camelCase).
•
el.style.cssText = 'color: red;'.
•
getComputedStyle(el) — computed styles.
•
CSS custom properties: setProperty.
How to create and add an element?
•
document.createElement('div').
•
parent.appendChild(el).
•
parent.insertBefore(el, ref).
•
el.append(), prepend().
•
insertAdjacentHTML, insertAdjacentElement.
How to delete an element?
•
el.remove() — modern.
•
parent.removeChild(el).
•
el.replaceWith(newEl).
•
innerHTML = '' — remove content.
•
Removed elements can be reinserted.
What is event bubbling and capturing?
•
Bubbling — event rises from target to parents.
•
Capturing — from window to target.
•
addEventListener(type, fn, true) for capturing.
•
event.stopPropagation() stops it.
•
Default is bubbling.
What is event delegation?
•
One handler on parent.
•
event.target — actual element.
•
event.currentTarget — element with handler.
•
Efficient for dynamic elements.
•
matches() or closest() for filtering.
How to prevent default action?
•
event.preventDefault().
•
Cancels the default behavior.
•
For example, submitting a form, following a link.
•
return false in the old style.
•
event.defaultPrevented — check.
What is DOMContentLoaded and load?
•
DOMContentLoaded — DOM is ready.
•
load — all resources are loaded.
•
DOMContentLoaded is faster.
•
defer scripts after DOMContentLoaded.
•
document.readyState for checking.
How to work with forms in JS?
•
form.elements — collection of elements.
•
input.value — value.
•
form.submit() — programmatic submission.
•
form.reset() — reset.
•
FormData for collecting data.
What is FormData?
•
new FormData(formElement).
•
append(), get(), delete().
•
entries() for iteration.
•
Sending with fetch.
•
For files and form data.
How to work with localStorage?
•
localStorage.setItem(key, value).
•
getItem(key).
•
removeItem(key).
•
clear() — clear everything.
•
Only strings — JSON.stringify/parse.
What is the difference between localStorage and sessionStorage?
•
localStorage — persistent storage.
•
sessionStorage — until the tab is closed.
•
Both ~5-10 MB.
•
Synchronous operations.
•
Same API.
What is a cookie in JavaScript?
•
document.cookie — string.
•
Setting: document.cookie = 'name=value'.
•
expires, max-age, path, domain.
•
HttpOnly not accessible from JS.
•
4 KB limit per cookie.
How to work with the history API?
•
history.pushState(state, title, url).
•
history.replaceState().
•
history.back(), forward(), go().
•
popstate event.
•
For SPA navigation.
What is Intersection Observer?
•
Observing element intersection.
•
new IntersectionObserver(callback, options).
•
observer.observe(element).
•
Lazy loading images.
•
Infinite scrolling.
What is Mutation Observer?
•
Observing DOM changes.
•
new MutationObserver(callback).
•
observer.observe(target, config).
•
childList, attributes, characterData.
•
subtree for nested.
What is Resize Observer?
•
Observing the size of an element.
•
new ResizeObserver(callback).
•
observer.observe(element).
•
entry.contentRect — dimensions.
•
More efficient than window resize.
What are ES modules?
•
export const x = 1; export default fn.
•
import {x} from './module'.
•
import * as M from './module'.
•
Static imports.
•
type='module' in HTML.
What is dynamic import?
•
import('./module').then(module => {}).
•
await import('./module').
•
For code splitting.
•
Lazy loading.
•
Returns a Promise.
How do CommonJS and ES modules differ?
•
CommonJS: require(), module.exports.
•
ES: import/export.
•
CommonJS — synchronous, Node.
•
ES — asynchronous, standard.
•
Node supports both.
What is a bundler?
•
Combines modules into files.
•
Webpack, Vite, Rollup, esbuild.
•
Tree shaking — removing unused code.
•
Code splitting.
•
Minification.
What is tree shaking?
•
Removing unused code.
•
Works with ES modules.
•
Static analysis of imports.
•
sideEffects in package.json.
•
Reduces bundle size.
What are source maps?
•
Link between minified and original code.
•
For debugging in DevTools.
•
.map files.
•
devtool in Webpack.
•
Do not include publicly in production.
What is transpilation?
•
Converting new JS to older versions.
•
Babel — the main transpiler.
•
Support for old browsers.
•
TypeScript also transpiles.
•
Polyfills for new APIs.
What is a polyfill?
•
Code that adds missing functionality.
•
core-js — popular library.
•
For old browsers.
•
Promise, fetch polyfills.
•
@babel/polyfill (deprecated) → core-js.
What are npm and package.json?
•
npm — Node package manager.
•
package.json — project configuration.
•
dependencies, devDependencies.
•
scripts for commands.
•
package-lock.json locks versions.
What are yarn and pnpm?
•
yarn — an alternative to npm from Facebook.
•
pnpm — efficient storage.
•
yarn.lock, pnpm-lock.yaml.
•
Faster and more reliable than npm.
•
Compatible with npm registry.
What are memory leaks?
•
Unreleased memory.
•
Global variables.
•
Forgotten timers and listeners.
•
Closures with DOM elements.
•
Chrome DevTools Memory for analysis.
What is garbage collection?
•
Automatic memory freeing.
•
Mark-and-sweep algorithm.
•
Unreachable objects are removed.
•
WeakMap/WeakSet for weak references.
•
Cannot be called manually.
What are debounce and throttle?
•
debounce — execute after a pause.
•
throttle — no more often than N ms.
•
debounce for search, resize.
•
throttle for scroll, mousemove.
•
lodash.debounce, lodash.throttle.
What is currying?
•
Transforming f(a, b) into f(a)(b).
•
Partial application of arguments.
•
const add = a => b => a + b.
•
Function composition.
•
Functional programming.
What is immutability?
•
Object does not change after creation.
•
New object on changes.
•
{...obj, key: newVal}.
•
Immer for convenience.
•
Important for React, Redux.
What are Web Components?
•
Custom Elements — your own tags.
•
Shadow DOM — style isolation.
•
HTML Templates — templates.
•
customElements.define().
•
Work without frameworks.
What is Canvas API?
•
Drawing 2D graphics.
•
canvas.getContext('2d').
•
fillRect, strokeRect, arc.
•
drawImage for images.
•
Animations with requestAnimationFrame.
What is WebGL?
•
3D graphics in the browser.
•
canvas.getContext('webgl').
•
Shaders in GLSL.
•
Three.js simplifies work.
•
GPU acceleration.
What is Web Audio API?
•
Audio processing in the browser.
•
AudioContext — context.
•
Oscillator, Gain, Filter nodes.
•
Frequency analysis.
•
Spatial sound.
What are the new features of ES2023+?
•
Array.prototype.toSorted, toReversed.
•
Array.prototype.with().
•
Hashbang grammar.
•
Symbols as WeakMap keys.
•
Array.fromAsync().
JavaScript — Programming — Technology — FAQ Портал