- What are the different data types in JavaScript?
JavaScript has seven primitive data types: String, Number, Boolean, Undefined, Null, Symbol, and BigInt. It also includes objects, which can be collections of data and more complex entities.
1let name = "John"; // String2let age = 30; // Number3let isStudent = true; // Boolean4let address; // Undefined5let empty = null; // Null6let uniqueId = Symbol("id"); // Symbol7let bigIntNumber = BigInt(1234567890123456789012345678901234567890); // BigInt8let person = { name: "Jane", age: 25 }; // Object
- What is the difference between
undefined
andnull
?
undefined
means a variable has been declared but not assigned a value, whereas null
is an assignment value that represents the intentional absence of any object value.
1let x;2console.log(x); //3let y = null;4console.log(y); // null
- What are JavaScript functions?
Functions are blocks of code designed to perform particular tasks. They are executed when they are called (invoked).
1function greet(name) {2return `Hello, ${name}!`;3}4console.log(greet("Vasyl")); // Hello, Vasyl!
- Explain the difference between
let
,const
, andvar
.
var
is function-scoped or globally-scoped and can be re-declared and updated. let
is block-scoped and can be updated but not re-declared. const
is block-scoped and cannot be updated or re-declared.
1var a = 1;2var a = 2; // No error34let b = 1;5// let b = 2; // Error: Identifier 'b' has already been declared67const c = 1;8// c = 2; // Error: Assignment to constant variable.
- What is a closure in JavaScript?
A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope. Closures allow functions to access variables from an enclosing scope.
1function outer() {2let counter = 0;3return function inner() {4counter++;5return counter;6};7}8const increment = outer();9console.log(increment()); // 110console.log(increment()); // 2
- What is an Immediately Invoked Function Expression (IIFE)?
An IIFE is a function that runs as soon as it is defined. It is used to avoid polluting the global namespace and to create a new scope.
1(function() {2console.log("IIFE executed!");3})();
- What is hoisting in JavaScript?
Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope. This means that variables and function declarations can be used before they are declared.
1console.log(x); //2var x = 5;34greet();5function greet() {6console.log("Hello!");7}
- What are arrow functions?
Arrow functions are a concise syntax for writing function expressions. They do not have their own this
, arguments
, super
, or new.target
.
1const add = (a, b) => a + b;2console.log(add(2, 3)); // 5
- What is the difference between
==
and===
?
==
checks for equality with type coercion, meaning it converts the operands to the same type before comparing. ===
checks for strict equality without type coercion, meaning the values and types must be the same.
1console.log(1 == '1'); // true2console.log(1 === '1'); // false
- What is the purpose of the
this
keyword?
this
refers to the object that is executing the current function. Its value depends on how the function is called.
1const person = {2name: 'Vasyl',3greet: function() {4console.log(`Hello, my name is ${this.name}`);5}6};7person.greet(); // Hello, my name is Vasyl
- What is an event loop in JavaScript?
The event loop is a mechanism that allows JavaScript to perform non-blocking operations by offloading operations to the system kernel whenever possible.
1console.log('Start');2setTimeout(() => {3console.log('Timeout');4}, 0);5console.log('End');6// Output: Start, End, Timeout
- What are Promises?
Promises are objects representing the eventual completion or failure of an asynchronous operation. They provide a way to handle asynchronous operations in a more readable manner.
1const promise = new Promise((resolve, reject) => {2setTimeout(() => {3resolve('Done!');4}, 1000);5});67promise.then(result => {8console.log(result); // Done!9});
- Explain
async
andawait
.
async
functions return a promise and allow the use of await
within them. await
pauses the execution of an async
function and waits for the promise to resolve or reject.
1async function fetchData() {2let response = await fetch('https://api.example.com/data');3let data = await response.json();4console.log(data);5}6fetchData();
- What is the DOM?
The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content.
1document.getElementById('myElement').textContent = 'Hello, World!';
- What is event delegation?
Event delegation is a technique of using a single event listener to manage all events of a particular type within a container. It takes advantage of event bubbling to handle events efficiently.
1document.getElementById('parent').addEventListener('click', function(event) {2if (event.target && event.target.matches('button.class-name')) {3console.log('Button clicked');4}5});
- What is the difference between
map
,filter
, andreduce
?
map
creates a new array with the results of calling a function on every element in the calling array. filter
creates a new array with all elements that pass the test implemented by the provided function. reduce
applies a function against an accumulator and each element in the array to reduce it to a single value.
1const numbers = [1, 2, 3, 4, 5];23const doubled = numbers.map(n => n * 2);4console.log(doubled); // [2, 4, 6, 8, 10]56const even = numbers.filter(n => n % 2 === 0);7console.log(even); // [2, 4]89const sum = numbers.reduce((acc, n) => acc + n, 0);10console.log(sum); // 15
- What are higher-order functions?
Higher-order functions are functions that take other functions as arguments or return functions as their result. They are a key feature of functional programming.
1function applyOperation(a, b, operation) {2return operation(a, b);3}45function add(x, y) {6return x + y;7}89console.log(applyOperation(5, 3, add)); // 8
- What is a callback function?
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some action.
1function fetchData(callback) {2setTimeout(() => {3const data = { name: 'John' };4callback(data);5}, 1000);6}78fetchData(data => {9console.log(data); // { name: 'John' }10});
- What are modules in JavaScript?
Modules are reusable pieces of code that can be imported and exported to organize and structure your code. They help to keep code clean, maintainable, and scoped properly.
1// module.js2export const greet = name => `Hello, ${name}!`;34// main.js5import { greet } from './module.js';6console.log(greet('Vasyl')); // Hello, Vasyl!
- What is the purpose of
use strict
?
use strict
is a directive that helps catch common coding errors and "unsafe" actions such as defining global variables. It enforces stricter parsing and error handling in your code.
1'use strict';2x = 3.14; // Error: x is not defined
- What is the spread operator?
The spread operator (...
) allows an iterable to expand in places where multiple arguments or elements are expected. It is used for copying arrays, merging arrays, and spreading elements.
1const arr1 = [1, 2, 3];2const arr2 = [...arr1, 4, 5];3console.log(arr2); // [1, 2, 3, 4, 5]45const obj1 = { a: 1, b: 2 };6const obj2 = { ...obj1, c: 3 };7console.log(obj2); // { a: 1, b: 2, c: 3 }
- What are template literals?
Template literals are string literals allowing embedded expressions. They can be multi-line and use interpolation using ${}
syntax.
1const name = 'Vasyl';2const message = `Hello, ${name}!`;3console.log(message); // Hello, Vasyl!
- What is destructuring in JavaScript?
Destructuring is a syntax for extracting values from arrays or properties from objects into distinct variables.
1const [a, b] = [1, 2];2console.log(a, b); // 1 234const { name, age } = { name: 'Vasyl', age: 25 };5console.log(name, age); // Vasyl 25
- What is the difference between
for...of
andfor...in
?
for...of
iterates over iterable objects (like arrays, strings, etc.) and returns the values. for...in
iterates over the enumerable properties of an object and returns the keys.
1const arr = [1, 2, 3];2for (const value of arr) {3console.log(value); // 1, 2, 34}56const obj = { a: 1, b: 2 };7for (const key in obj) {8console.log(key); // a, b9}
- What are generators in JavaScript?
Generators are functions that can be paused and resumed, producing a sequence of results using the function*
syntax and yield
keyword.
1function* generateSequence() {2yield 1;3yield 2;4yield 3;5}67const generator = generateSequence();8console.log(generator.next().value); // 19console.log(generator.next().value); // 210console.log(generator.next().value); // 3
- What is the difference between synchronous and asynchronous code?
Synchronous code is executed line by line, with each operation waiting for the previous one to complete. Asynchronous code allows multiple operations to occur simultaneously, using callbacks, promises, or async/await.
1console.log('Start');2setTimeout(() => {3console.log('Timeout');4}, 0);5console.log('End');6// Output: Start, End, Timeout
- What are JavaScript prototypes?
Prototypes are a mechanism by which JavaScript objects inherit features from one another. Every JavaScript object has a prototype, which is another object that the original object inherits properties and methods from.
1function Person(name) {2this.name = name;3}45Person.prototype.greet = function() {6return `Hello, my name is ${this.name}`;7};89const person = new Person('Vasyl');10console.log(person.greet()); // Hello, my name is Vasyl
- What is event bubbling and capturing?
Event bubbling is when an event starts from the target element and propagates up to the root. Event capturing (or trickling) is the reverse, where the event starts from the root and propagates down to the target element.
1document.getElementById('child').addEventListener('click', () => {2console.log('Child clicked');3});45document.getElementById('parent').addEventListener('click', () => {6console.log('Parent clicked');7});8// If you click on the child element, "Child clicked" and then "Parent clicked" will be logged.
- What is a promise chain?
A promise chain is a series of promises where each promise is executed after the previous one completes, using then()
for chaining.
1fetch('https://api.example.com/data')2.then(response => response.json())3.then(data => {4console.log(data);5return fetch('https://api.example.com/other-data');6})7.then(response => response.json())8.then(otherData => {9console.log(otherData);10})11.catch(error => {12console.error('Error:', error);13});
- What are JavaScript classes?
Classes are a template for creating objects and are a syntactical sugar over JavaScript's existing prototype-based inheritance. They provide a cleaner and more intuitive way to create objects and manage inheritance.
1class Person {2constructor(name) {3this.name = name;4}56greet() {7return `Hello, my name is ${this.name}`;8}9}1011const person = new Person('Vasyl');12console.log(person.greet()); // Hello, my name is Vasyl
- What is the
super
keyword?
The super
keyword is used to call the constructor or methods of a parent class. It allows access to the parent class's properties and methods.
1class Animal {2constructor(name) {3this.name = name;4}56speak() {7return `${this.name} makes a sound.`;8}9}1011class Dog extends Animal {12constructor(name) {13super(name);14}1516speak() {17return `${this.name} barks.`;18}19}2021const dog = new Dog('Rex');22console.log(dog.speak()); // Rex barks.
- What are JavaScript Promises?
Promises represent the eventual completion or failure of an asynchronous operation. They are used to handle asynchronous operations more effectively, avoiding callback hell.
1const promise = new Promise((resolve, reject) => {2setTimeout(() => {3resolve('Success!');4}, 1000);5});67promise.then(result => {8console.log(result); // Success!9}).catch(error => {10console.error(error);11});
- What is an async function?
An async
function is a function declared with the async
keyword that enables the use of the await
keyword within it to pause execution until a promise is resolved.
1async function fetchData() {2try {3let response = await fetch('https://api.example.com/data');4let data = await response.json();5console.log(data);6} catch (error) {7console.error('Error:', error);8}9}1011fetchData();
- What is the
new
keyword?
The new
keyword is used to create an instance of a constructor function or a class. It sets up the prototype chain and initializes the new object.
1function Person(name) {2this.name = name;3}45const person = new Person('Vasyl');6console.log(person.name); // Vasyl
- What is the difference between
call
andapply
?
Both call
and apply
invoke a function with a specified this
value, but call
takes arguments separately while apply
takes arguments as an array.
1function greet(greeting, punctuation) {2console.log(`${greeting}, my name is ${this.name}${punctuation}`);3}45const person = { name: 'Vasyl' };67greet.call(person, 'Hello', '!'); // Hello, my name is Vasyl!8greet.apply(person, ['Hi', '.']); // Hi, my name is Vasyl.
- What is the
bind
method?
The bind
method creates a new function that, when called, has its this
value set to the provided value, with a given sequence of arguments.
1const person = {2name: 'Vasyl',3greet() {4console.log(`Hello, my name is ${this.name}`);5}6};78const greet = person.greet.bind(person);9greet(); // Hello, my name is Vasyl
- What is the
this
keyword in JavaScript?
this
refers to the object that is executing the current function. Its value is determined by how the function is called.
1const person = {2name: 'Vasyl',3greet() {4console.log(`Hello, my name is ${this.name}`);5}6};78person.greet(); // Hello, my name is Vasyl910const greet = person.greet;11greet(); // , since `this` refers to the global object (or undefined in strict mode)
- What is the difference between
==
and===
?
==
compares values for equality with type coercion, whereas ===
compares values for equality without type coercion.
1console.log(1 == '1'); // true2console.log(1 === '1'); // false
- What is an arrow function in JavaScript?
An arrow function is a shorter syntax for writing function expressions. They do not have their own this
, arguments
, super
, or new.target
.
1const add = (a, b) => a + b;2console.log(add(2, 2)); // 4
- What is the
fetch
API?
The fetch
API is a modern interface for making HTTP requests, replacing older technologies like XMLHttpRequest. It returns a promise that resolves to the response of the request.
1fetch('https://api.example.com/data')2.then(response => response.json())3.then(data => console.log(data))4.catch(error => console.error('Error:', error));
- What is the
typeof
operator?
The typeof
operator returns a string indicating the type of the operand. It is used to determine the type of a variable or value.
1console.log(typeof 'hello'); // string2console.log(typeof 42); // number3console.log(typeof true); // boolean4console.log(typeof ); // undefined5console.log(typeof { a: 1 }); // object6console.log(typeof null); // object (this is a known bug in JavaScript)7console.log(typeof function() {}); // function
- What are JavaScript events?
Events are actions or occurrences that happen in the browser, which can be detected and handled using JavaScript. Examples include clicking a button, loading a page, and submitting a form.
1document.getElementById('myButton').addEventListener('click', () => {2console.log('Button clicked');3});
- What is the
Date
object in JavaScript?
The Date
object is used for working with dates and times in JavaScript. It provides methods to get and set the year, month, day, hour, minute, second, and millisecond.
1const now = new Date();2console.log(now); // Current date and time34const specificDate = new Date('2024-07-02');5console.log(specificDate); // July 2, 2024
- What is the
setTimeout
function?
setTimeout
is a function that sets a timer to execute a function or code snippet after a specified delay in milliseconds.
1setTimeout(() => {2console.log('This message is delayed by 2 seconds');3}, 2000);
- What is the
setInterval
function?
setInterval
is a function that repeatedly calls a function or code snippet with a fixed time delay between each call, specified in milliseconds.
1const intervalId = setInterval(() => {2console.log('This message repeats every 2 seconds');3}, 2000);45// To stop the interval6clearInterval(intervalId);
- What is a promise in JavaScript?
A promise is an object representing the eventual completion or failure of an asynchronous operation. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason.
1const promise = new Promise((resolve, reject) => {2setTimeout(() => {3resolve('Success!');4}, 1000);5});67promise.then(result => {8console.log(result); // Success!9}).catch(error => {10console.error(error);11});
- What is the
async/await
syntax?
async/await
is syntactic sugar built on top of promises, allowing you to write asynchronous code in a synchronous-looking manner. An async
function returns a promise, and await
pauses the execution of the function until the promise is resolved.
1async function fetchData() {2try {3const response = await fetch('https://api.example.com/data');4const data = await response.json();5console.log(data);6} catch (error) {7console.error('Error:', error);8}9}1011fetchData();
- What are JavaScript cookies?
Cookies are small pieces of data stored on the user's computer by the web browser. They are used to remember information about the user between page requests.
1// Setting a cookie2document.cookie = 'username=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT';34// Getting a cookie5const cookies = document.cookie.split('; ');6const usernameCookie = cookies.find(cookie => cookie.startsWith('username='));7const username = usernameCookie.split('=')[1];8console.log(username); // John
- What is the scope?
Scope determines the visibility and accessibility of variables and functions during runtime. Understanding scope is crucial for managing variable lifetimes, avoiding naming conflicts, and writing maintainable code. There are two main types of scope in JavaScript: global scope and local scope.
Global Scope
Variables declared outside of any function or block have global scope. They can be accessed from anywhere within the script, including inside functions and blocks.
1// Global scope2let message = "Hello, world!";34function greet() {5console.log(message); // Accessible within the function6}78greet(); // Outputs: Hello, world!9console.log(message); // Outputs: Hello, world!
In this example, message
is declared outside any function, making it globally scoped. Both the greet
function and the console.log
statement outside the function can access and modify message
.
Local Scope
Variables declared within a function or block have local scope. They are only accessible within that specific function or block.
1function greet() {2// Local scope3let name = "Vasyl";4console.log(`Hello, ${name}!`);5}67greet(); // Outputs: Hello, Vasyl!8console.log(name); // Throws ReferenceError: name is not defined
In this example, name
is declared inside the greet
function, making it locally scoped. It cannot be accessed outside of the function.
Block Scope (ES6+)
Introduced in ECMAScript 6 (ES6), block scope refers to the visibility of variables within any block delimited by curly braces { }
, such as if
, for
, while
, and switch
statements.
1function calculate() {2let result = 0;34if (true) {5// Block scope6let x = 10;7result = x * 2;8}910console.log(result); // Outputs: 2011console.log(x); // Throws ReferenceError: x is not defined12}1314calculate();
In this example, x
is declared inside the if
block and is only accessible within that block due to block scoping. The result
variable, declared outside the block, retains its value after the block executes.
Lexical Scope
Lexical scope means that the scope of a variable is determined by its position within the source code. In JavaScript, functions are executed using the scope chain that was in effect when they were defined, not when they are executed.
1function outerFunction() {2let outerVar = 'I am outside!';34function innerFunction() {5let innerVar = 'I am inside!';6console.log(outerVar); // Can access outerVar7}89innerFunction();10console.log(innerVar); // Throws ReferenceError: innerVar is not defined11}1213outerFunction();
In this example, innerFunction
can access outerVar
defined in its outer scope due to lexical scoping. However, innerVar
defined inside innerFunction
cannot be accessed outside its scope.
- What is the Memoization?
Memoization is a technique used in programming to optimize functions by caching the results of expensive function calls and returning the cached result when the same inputs occur again. This can significantly improve performance by avoiding redundant computations.
How Memoization Works
When a function is memoized, it stores the results of expensive function calls and returns the cached result when the same inputs occur again. This caching mechanism typically uses an object (often called a cache) where the function stores the computed results indexed by the function arguments.
Benefits of Memoization
- Performance Improvement: Memoization can drastically reduce the time complexity of functions that are called frequently with the same inputs.
- Reduced Recalculation: By storing previously computed results, memoization eliminates redundant computations, especially in recursive or computationally intensive functions.
Example of Memoization in JavaScript
Here's a basic example of how memoization can be implemented in JavaScript using a higher-order function:
1// Function to calculate Fibonacci numbers (not optimized)2function fibonacci(n) {3if (n <= 1) return n;4return fibonacci(n - 1) + fibonacci(n - 2);5}67// Memoization function decorator8function memoize(fn) {9const cache = {};10return function(...args) {11const key = JSON.stringify(args);12if (cache[key] === ) {13cache[key] = fn.apply(this, args);14}15return cache[key];16};17}1819// Applying memoization to fibonacci function20const memoizedFibonacci = memoize(fibonacci);2122console.log(memoizedFibonacci(10)); // Outputs: 5523console.log(memoizedFibonacci(10)); // Outputs: 55 (cached result)
- Original Fibonacci Function:
fibonacci
calculates Fibonacci numbers recursively. - Memoization Function (
memoize
):memoize
takes a functionfn
and returns a new function that caches results. - Caching Mechanism: The
cache
object stores results indexed by the function arguments converted to a string (JSON.stringify(args)
). - Memoized Fibonacci:
memoizedFibonacci
is the memoized version offibonacci
, created usingmemoize
. - Usage: When
memoizedFibonacci(10)
is called the first time, it computes and caches the result (55
). Subsequent calls with the same argument (10
) return the cached result without recomputation.
Use Cases for Memoization
- Recursive Functions: Memoization is commonly used with recursive functions like Fibonacci, factorial calculations, or recursive traversal algorithms to optimize performance.
- Expensive Computations: Functions that involve complex calculations, database queries, or API requests can benefit from memoization to avoid repeated expensive operations.