JavaScript Interview Questions
1. Data Types in JavaScript
JavaScript has the following primitive data types:
String: Represents textual data.
javascript
Copy code
let name = "John";
Number: Represents numeric values, both integer and floating-point.
javascript
Copy code
let age = 30;
Boolean: Represents true or false.
javascript
Copy code
let isAdult = true;
Undefined: A variable that has been declared but not assigned a value.
javascript
Copy code
let x;
console.log(x); // undefined
Null: Represents the intentional absence of any object value.
javascript
Copy code
let y = null;
Symbol: A unique and immutable primitive value.
javascript
Copy code
const sym = Symbol("description");
BigInt: For integers of arbitrary length.
javascript
Copy code
const bigInt = 1234567890123456789012345678901234567890n;
2. Hoisting in JavaScript
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compile phase. For example:
javascript
Copy code
console.log(a); // undefined
var a = 5;
foo(); // "Hello"
function foo() {
console.log("Hello");
}
In the above example, the variable a is hoisted, but its assignment is not, leading to undefined being logged.
3. Debugger in JavaScript
The debugger statement stops the execution of the code and calls the debugger. If no debugging is available, it behaves like a no-op.
javascript
Copy code
function myFunction() {
debugger; // Execution will pause here
console.log("Debugging!");
}
4. Difference between == and ===
== checks for value equality with type coercion.
=== checks for both value and type equality without coercion.
javascript
Copy code
console.log(5 == '5'); // true
console.log(5 === '5'); // false
5. Difference between var and let
var: Function-scoped or globally scoped, can be redeclared.
let: Block-scoped, cannot be redeclared in the same scope.
javascript
Copy code
var x = 10;
if (true) {
var x = 20; // Same variable
}
console.log(x); // 20
let y = 10;
if (true) {
let y = 20; // Different variable
}
console.log(y); // 10
6. Implicit Type Coercion
JavaScript automatically converts types during operations.
javascript
Copy code
console.log(1 + '2'); // "12"
console.log('5' - 2); // 3
7. Statically Typed vs. Dynamically Typed
JavaScript is dynamically typed, meaning variables can hold values of any type without explicit type declaration.
javascript
Copy code
let value = 42; // Number
value = "Hello"; // String
8. NaN Property
NaN (Not-a-Number) indicates a value that is not a legal number.
javascript
Copy code
console.log(NaN === NaN); // false
console.log(isNaN("hello")); // true
9. Passed by Value and Passed by Reference
Passed by Value: Primitive types are copied to the function.
Passed by Reference: Objects are referenced in memory.
javascript
Copy code
function updateValue(x) {
x = 10; // Does not affect the original
}
let a = 5;
updateValue(a);
console.log(a); // 5
function updateObject(obj) {
obj.key = "new value"; // Affects the original
}
let obj = { key: "value" };
updateObject(obj);
console.log(obj.key); // "new value"
10. Immediately Invoked Function
An Immediately Invoked Function Expression (IIFE) is a function that runs as soon as it is defined.
javascript
Copy code
(function() {
console.log("IIFE executed!");
})();
11. Strict Mode
Strict mode is a way to opt into a restricted variant of JavaScript, reducing some silent errors. It can be enabled by adding "use strict"; at the top of a script or function.
javascript
Copy code
"use strict";
x = 3.14; // ReferenceError: x is not defined
12. Higher Order Functions
Higher order functions are functions that can take other functions as arguments or return functions.
javascript
Copy code
function greet(name) {
return function() {
console.log("Hello, " + name);
};
}
const greetJohn = greet("John");
greetJohn(); // "Hello, John"
13. this Keyword
this refers to the context in which a function is called. Its value can change depending on how a function is called.
javascript
Copy code
const obj = {
name: "Alice",
greet() {
console.log("Hello, " + this.name);
}
};
obj.greet(); // "Hello, Alice"
14. Self Invoking Functions
Self-invoking functions (or IIFEs) are executed immediately after they are defined.
javascript
Copy code
(function() {
console.log("Executed!");
})();
15. call(), apply(), and bind()
call(): Calls a function with a specified this value and arguments.
apply(): Similar to call(), but takes an array of arguments.
bind(): Returns a new function, permanently bound to a specific this value.
javascript
Copy code
function introduce(greeting) {
console.log(greeting + ", " + this.name);
}
const person = { name: "John" };
introduce.call(person, "Hello"); // "Hello, John"
introduce.apply(person, ["Hi"]); // "Hi, John"
const boundIntroduce = introduce.bind(person);
boundIntroduce("Hey"); // "Hey, John"
16. exec() and test() Methods
exec(): Executes a search for a match in a string and returns an array or null.
test(): Tests for a match in a string and returns a boolean.
javascript
Copy code
const regex = /abc/;
console.log(regex.exec("abcdef")); // ["abc", index: 0, input: "abcdef"]
console.log(regex.test("abcdef")); // true
17. Currying
Currying is a technique of evaluating functions with multiple arguments by transforming them into a sequence of functions, each taking a single argument.
javascript
Copy code
function multiply(x) {
return function(y) {
return x * y;
};
}
const double = multiply(2);
console.log(double(5)); // 10
18. Advantages of Using External JavaScript
Improved maintainability by separating code from HTML.
Code reusability across multiple HTML pages.
Reduced page load time since files can be cached.
19. Scope and Scope Chain
Scope is the context in which variables are accessible. The scope chain is the hierarchy of scopes that allows variable resolution.
javascript
Copy code
let outer = "outer";
function outerFunction() {
let inner = "inner";
function innerFunction() {
console.log(outer); // "outer"
console.log(inner); // "inner"
}
innerFunction();
}
outerFunction();
20. Closures
A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope.
javascript
Copy code
function makeCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
21. Advantages of JavaScript
Cross-platform: Runs in any browser.
Event-driven: Responsive to user actions.
Asynchronous: Handles operations like network requests without blocking.
Rich interfaces: Can create dynamic and interactive web pages.
22. Object Prototypes
Every JavaScript object has a prototype, which is another object from which it inherits properties and methods.
javascript
Copy code
const animal = {
speak() {
console.log("Animal speaks");
}
};
const dog = Object.create(animal);
dog.bark = function() {
console.log("Woof!");
};
dog.speak(); // "Animal speaks"
dog.bark(); // "Woof!"
23. Callbacks
A callback is a function passed into another function as an argument to be executed later.
javascript
Copy code
function fetchData(callback) {
// Simulate async operation
setTimeout(() => {
callback("Data fetched");
}, 1000);
}
fetchData(data => console.log(data)); // "Data fetched" after 1 second
24. Types of Errors in JavaScript
Syntax Errors: Mistakes in the code that prevent it from running.
Reference Errors: Accessing a variable that doesn't exist.
Type Errors: Performing operations on incompatible types.
Range Errors: Numeric values that are outside the range.
25. Memoization
Memoization is an optimization technique that stores the results of expensive function calls and returns the cached result when the same inputs occur again.
javascript
Copy code
function memoizedAdd() {
const cache = {};
return function(num) {
if (num in cache) {
return cache[num];
}
const result = num + 10; // Expensive operation
cache[num] = result;
return result;
};
}
const add = memoizedAdd();
console.log(add(5)); // 15
console.log(add(5)); // 15 (cached)
26. Event Delegation
Event delegation is a technique where a single event listener is added to a parent element instead of multiple listeners on child elements. This improves performance and allows handling events for dynamically added elements.
html
Copy code
<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<script>
const list = document.getElementById('list');
list.addEventListener('click', function(event) {
if (event.target.tagName === 'LI') {
console.log(event.target.textContent); // Logs the text of the clicked item
}
});
</script>
27. Event Bubbling and Capturing
Event bubbling is the process where events propagate from the target element up to the root. Capturing is the reverse, where events go from the root down to the target.
html
Copy code
<div id="parent">
<button id="child">Click Me</button>
</div>
<script>
document.getElementById('parent').addEventListener('click', () => {
console.log('Parent clicked!');
}, true); // Capture phase
document.getElementById('child').addEventListener('click', () => {
console.log('Child clicked!');
});
</script>
When the button is clicked, "Child clicked!" will log first, followed by "Parent clicked!" if you capture in the parent.
28. Promises
A promise is an object representing the eventual completion or failure of an asynchronous operation.
javascript
Copy code
const fetchData = new Promise((resolve, reject) => {
const success = true; // Simulate success or failure
if (success) {
resolve("Data fetched successfully");
} else {
reject("Error fetching data");
}
});
fetchData
.then(response => console.log(response)) // "Data fetched successfully"
.catch(error => console.error(error));
29. Async/Await
async functions always return a promise, and await is used to wait for a promise to resolve.
javascript
Copy code
async function fetchData() {
try {
const response = await new Promise((resolve) => {
setTimeout(() => resolve("Data fetched"), 1000);
});
console.log(response); // "Data fetched"
} catch (error) {
console.error(error);
}
}
fetchData();
30. Throttling and Debouncing
Throttling: Ensures a function is only called at most once in a specified time frame.
Debouncing: Ensures a function is only called after a specified delay from the last invocation.
Throttling Example:
javascript
Copy code
function throttle(fn, limit) {
let lastFunc;
let lastRan;
return function() {
const context = this;
const args = arguments;
if (!lastRan) {
fn.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(() => {
if ((Date.now() - lastRan) >= limit) {
fn.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
}
const throttledLog = throttle(() => console.log('Throttled!'), 2000);
window.addEventListener('resize', throttledLog);
Debouncing Example:
javascript
Copy code
function debounce(fn, delay) {
let timeout;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(context, args), delay);
};
}
const debouncedLog = debounce(() => console.log('Debounced!'), 2000);
window.addEventListener('resize', debouncedLog);
31. setTimeout() and setInterval()
setTimeout(): Executes a function after a specified delay.
setInterval(): Repeatedly calls a function with a fixed time delay between each call.
Example of setTimeout():
javascript
Copy code
setTimeout(() => {
console.log("Executed after 2 seconds");
}, 2000);
Example of setInterval():
javascript
Copy code
const intervalId = setInterval(() => {
console.log("Executed every 1 second");
}, 1000);
// To stop the interval after 5 seconds
setTimeout(() => clearInterval(intervalId), 5000);
32. Understanding the Event Loop
The event loop is a mechanism that allows JavaScript to perform non-blocking I/O operations, despite being single-threaded. It executes code, collects and processes events, and executes queued sub-tasks.
javascript
Copy code
console.log("Start");
setTimeout(() => {
console.log("Timeout");
}, 0);
Promise.resolve().then(() => console.log("Promise resolved"));
console.log("End");
// Output will be:
// Start
// End
// Promise resolved
// Timeout
33. this in Different Contexts
The value of this depends on how a function is called:
Global context: this refers to the global object (in browsers, it's window).
Object method: this refers to the object the method belongs to.
Constructor function: this refers to the newly created object.
Event handler: this refers to the element that fired the event.
Arrow functions: this retains the value of the enclosing lexical context.
javascript
Copy code
const obj = {
name: "Alice",
greet: function() {
console.log(this.name); // "Alice"
}
};
obj.greet();
const greet = obj.greet;
greet(); // undefined (or "Alice" in strict mode)
const arrowGreet = () => {
console.log(this.name); // Refers to lexical scope
};
arrowGreet();
34. Object Destructuring
Object destructuring allows unpacking values from objects into distinct variables.
javascript
Copy code
const person = {
name: "John",
age: 30,
};
const { name, age } = person;
console.log(name); // "John"
console.log(age); // 30
35. Array Destructuring
Array destructuring allows unpacking values from arrays into distinct variables.
javascript
Copy code
const colors = ["red", "green", "blue"];
const [red, green] = colors;
console.log(red); // "red"
console.log(green); // "green"
36. Spread Operator
The spread operator (...) allows iterables (like arrays) to be expanded into more elements.
javascript
Copy code
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const combinedObj = { ...obj1, ...obj2 };
console.log(combinedObj); // { a: 1, b: 2 }
37. Rest Operator
The rest operator (...) collects all remaining elements into an array.
javascript
Copy code
function sum(...args) {
return args.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // 6
38. Array Methods
Common array methods include:
map(): Creates a new array with the results of calling a function on every element.
filter(): Creates a new array with all elements that pass the test implemented by the provided function.
reduce(): Executes a reducer function on each element of the array, resulting in a single output value.
Examples:
javascript
Copy code
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4]
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15
39. Object Methods
Methods are functions that belong to an object. They can access the object's properties using this.
javascript
Copy code
const calculator = {
add: function(x, y) {
return x + y;
},
multiply: function(x, y) {
return x * y;
},
};
console.log(calculator.add(2, 3)); // 5
console.log(calculator.multiply(2, 3)); // 6
40. AJAX and Fetch API
AJAX (Asynchronous JavaScript and XML) allows the browser to send and receive data asynchronously without refreshing the page. The Fetch API provides a modern way to make HTTP requests.
Example using Fetch API:
javascript
Copy code
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('There was a problem with the fetch operation:', error));
41. Closures
A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope.
javascript
Copy code
function outer() {
const outerVar = 'I am outside!';
return function inner() {
console.log(outerVar); // Accesses outerVar
};
}
const innerFunc = outer();
innerFunc(); // "I am outside!"
42. Modules
JavaScript modules allow for encapsulating code into reusable components. ES6 introduced import and export syntax.
javascript
Copy code
// module.js
export const PI = 3.14;
export function add(a, b) {
return a + b;
}
// main.js
import { PI, add } from './module.js';
console.log(PI); // 3.14
console.log(add(2, 3)); // 5
43. Prototypal Inheritance
JavaScript uses prototypal inheritance, where objects can inherit properties and methods from other objects.
javascript
Copy code
const animal = {
speak: function() {
console.log('Animal speaks');
},
};
const dog = Object.create(animal);
dog.bark = function() {
console.log('Dog barks');
};
dog.speak(); // "Animal speaks"
dog.bark(); // "Dog barks"
44. map(), filter(), and reduce()
map(): Transforms each element.
filter(): Filters elements based on a condition.
reduce(): Aggregates elements to a single value.
Example:
javascript
Copy code
const nums = [1, 2, 3, 4, 5];
// Double the numbers
const doubled = nums.map(num => num * 2); // [2, 4, 6, 8, 10]
// Filter even numbers
const evens = nums.filter(num => num % 2 === 0); // [2, 4]
// Sum the numbers
const total = nums.reduce((acc, num) => acc + num, 0); // 15
45. bind(), call(), and apply()
These methods control the value of this in a function.
call(): Calls a function with a given this value and arguments provided individually.
apply(): Similar to call(), but takes arguments as an array.
bind(): Returns a new function with a bound this.
Example:
javascript
Copy code
const person = {
name: 'Alice',
greet: function(greeting) {
console.log(`${greeting}, ${this.name}`);
}
};
person.greet('Hello'); // "Hello, Alice"
const greetAlice = person.greet.bind(person);
greetAlice('Hi'); // "Hi, Alice"
const greetUsingCall = person.greet.call(person, 'Hey'); // "Hey, Alice"
const greetUsingApply = person.greet.apply(person, ['Greetings']); // "Greetings, Alice"
46. The new Keyword
The new keyword creates an instance of an object from a constructor function.
javascript
Copy code
function Car(make, model) {
this.make = make;
this.model = model;
}
const myCar = new Car('Toyota', 'Camry');
console.log(myCar.make); // "Toyota"
47. JSON Handling
JSON (JavaScript Object Notation) is a lightweight data interchange format. You can convert between JSON and JavaScript objects using JSON.stringify() and JSON.parse().
javascript
Copy code
const obj = { name: 'Alice', age: 25 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // '{"name":"Alice","age":25}'
const parsedObj = JSON.parse(jsonString);
console.log(parsedObj.name); // "Alice"
48. The window Object
The window object is the global object in a browser environment. It represents the browser window and provides access to the DOM, as well as global functions and variables.
javascript
Copy code
console.log(window.innerWidth); // Width of the browser window
console.log(window.location.href); // Current URL
49. Understanding Scope
Scope determines the accessibility of variables. JavaScript has function scope and block scope (with let and const).
javascript
Copy code
function testScope() {
var functionScoped = 'I am function scoped';
if (true) {
let blockScoped = 'I am block scoped';
console.log(blockScoped); // "I am block scoped"
}
console.log(functionScoped); // "I am function scoped"
// console.log(blockScoped); // ReferenceError
}
testScope();
50. Handling Errors with try...catch
Error handling in JavaScript can be managed using try...catch.
javascript
Copy code
try {
throw new Error('An error occurred');
} catch (error) {
console.log(error.message); // "An error occurred"
}
51. Strict Mode
Strict mode is a way to opt into a restricted variant of JavaScript. It helps catch common coding mistakes and "unsafe" actions such as defining global variables.
javascript
Copy code
'use strict';
function example() {
x = 3.14; // ReferenceError: x is not defined
}
example();
52. Callbacks
A callback is a function passed as an argument to another function, which is then executed after some operation.
javascript
Copy code
function fetchData(callback) {
setTimeout(() => {
const data = { id: 1, name: 'Alice' };
callback(data);
}, 1000);
}
fetchData((data) => {
console.log(data); // { id: 1, name: 'Alice' }
});
53. The instanceof Operator
The instanceof operator checks whether an object is an instance of a specific constructor or class.
javascript
Copy code
class Animal {}
class Dog extends Animal {}
const dog = new Dog();
console.log(dog instanceof Dog); // true
console.log(dog instanceof Animal); // true
console.log(dog instanceof Object); // true
54. Template Literals
Template literals provide an easy way to work with strings and include expressions. They use backticks (`) instead of quotes.
javascript
Copy code
const name = 'John';
const age = 30;
const greeting = `My name is ${name} and I am ${age} years old.`;
console.log(greeting); // "My name is John and I am 30 years old."
55. Default Parameters
Default parameters allow named parameters to be initialized with default values if no value or undefined is passed.
javascript
Copy code
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet(); // "Hello, Guest!"
greet('Alice'); // "Hello, Alice!"
56. The for...of Loop
The for...of loop iterates over iterable objects (like arrays, strings, etc.) and provides the value of each element.
javascript
Copy code
const arr = [1, 2, 3];
for (const num of arr) {
console.log(num); // 1, then 2, then 3
}
57. The for...in Loop
The for...in loop iterates over the enumerable properties of an object.
javascript
Copy code
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
console.log(`${key}: ${obj[key]}`); // "a: 1", "b: 2", "c: 3"
}
58. Set and Map
Set: A collection of values where each value must be unique.
Map: A collection of keyed data items, where keys can be any value (including objects).
Set Example:
javascript
Copy code
const uniqueValues = new Set([1, 2, 3, 3]);
uniqueValues.add(4);
console.log(uniqueValues); // Set { 1, 2, 3, 4 }
Map Example:
javascript
Copy code
const map = new Map();
map.set('name', 'Alice');
map.set('age', 25);
console.log(map.get('name')); // "Alice"
console.log(map.has('age')); // true
59. The typeof Operator
The typeof operator returns a string indicating the type of the unevaluated operand.
javascript
Copy code
console.log(typeof 'Hello'); // "string"
console.log(typeof 123); // "number"
console.log(typeof true); // "boolean"
console.log(typeof {}); // "object"
console.log(typeof null); // "object" (this is a known bug)
console.log(typeof undefined); // "undefined"
console.log(typeof function(){}); // "function"
60. The with Statement
The with statement extends the scope chain for a statement. It is generally discouraged because it can lead to confusing code and performance issues.
javascript
Copy code
const obj = { a: 1, b: 2 };
with (obj) {
console.log(a); // 1
console.log(b); // 2
}
61. The delete Operator
The delete operator removes a property from an object.
javascript
Copy code
const obj = { name: 'Alice', age: 25 };
delete obj.age;
console.log(obj); // { name: 'Alice' }
62. this in Arrow Functions
Arrow functions do not have their own this. Instead, they inherit this from the parent scope.
javascript
Copy code
const obj = {
name: 'Alice',
greet: function() {
const inner = () => console.log(`Hello, ${this.name}`);
inner();
}
};
obj.greet(); // "Hello, Alice"
63. The console Object
The console object provides access to the browser's debugging console. Common methods include console.log(), console.error(), console.warn(), and console.info().
javascript
Copy code
console.log('This is a log message');
console.warn('This is a warning');
console.error('This is an error');
64. The bind() Method
The bind() method creates a new function that, when called, has its this keyword set to a provided value.
javascript
Copy code
const person = {
name: 'Alice',
greet: function() {
console.log(`Hello, ${this.name}`);
}
};
const greetAlice = person.greet.bind(person);
greetAlice(); // "Hello, Alice"
65. Closure with Private Variables
Closures can be used to create private variables that cannot be accessed from outside a function.
javascript
Copy code
function createCounter() {
let count = 0;
return {
increment: function() {
count++;
return count;
},
decrement: function() {
count--;
return count;
},
getCount: function() {
return count;
}
};
}
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.getCount()); // 2
console.log(counter.decrement()); // 1
66. Object Property Shorthand
Object property shorthand allows you to omit the property name when the key and the variable name are the same.
javascript
Copy code
const name = 'Alice';
const age = 25;
const person = { name, age };
console.log(person); // { name: 'Alice', age: 25 }
67. Object.assign() Method
The Object.assign() method is used to copy the values of all enumerable properties from one or more source objects to a target object.
javascript
Copy code
const target = { a: 1 };
const source = { b: 2, c: 3 };
const returnedTarget = Object.assign(target, source);
console.log(target); // { a: 1, b: 2, c: 3 }
console.log(returnedTarget); // { a: 1, b: 2, c: 3 }
68. The arguments Object
The arguments object is an array-like object available within functions that contains the values of the arguments passed to the function.
javascript
Copy code
function sum() {
let total = 0;
for (let i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
console.log(sum(1, 2, 3)); // 6
69. The window.onload Event
The window.onload event is triggered when the entire page, including all dependent resources, is fully loaded.
javascript
Copy code
window.onload = function() {
console.log('Page fully loaded');
};
70. JavaScript Modules (ES6)
JavaScript modules are files that contain code that is executed in strict mode. They can export variables, functions, or classes that can be imported into other modules.
javascript
Copy code
// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
// main.js
import { add, subtract } from './math.js';
console.log(add(5, 3)); // 8
console.log(subtract(5, 3)); // 2
71. setInterval() and clearInterval()
setInterval() is used to execute a function repeatedly at specified intervals, while clearInterval() stops the execution.
javascript
Copy code
const intervalId = setInterval(() => {
console.log('This will run every 2 seconds');
}, 2000);
// To stop the interval after 10 seconds
setTimeout(() => clearInterval(intervalId), 10000);
72. setTimeout() and clearTimeout()
setTimeout() executes a function after a specified delay, and clearTimeout() cancels the timeout.
javascript
Copy code
const timeoutId = setTimeout(() => {
console.log('This will run after 3 seconds');
}, 3000);
// To cancel the timeout
clearTimeout(timeoutId);
73. localStorage and sessionStorage
localStorage allows you to store data with no expiration date. sessionStorage allows you to store data for one session.
javascript
Copy code
// localStorage example
localStorage.setItem('key', 'value');
console.log(localStorage.getItem('key')); // "value"
// sessionStorage example
sessionStorage.setItem('sessionKey', 'sessionValue');
console.log(sessionStorage.getItem('sessionKey')); // "sessionValue"
74. The fetch() API
The fetch() API is used to make HTTP requests and handle responses.
javascript
Copy code
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
75. Regular Expressions
Regular expressions are patterns used to match character combinations in strings. They can be used for searching, replacing, or validating strings.
javascript
Copy code
const regex = /hello/i;
console.log(regex.test('Hello World')); // true
console.log('Hello World'.replace(regex, 'Hi')); // "Hi World"
76. Prototypal Inheritance
JavaScript uses prototypal inheritance, which means objects can inherit properties and methods from other objects through their prototype chain.
javascript
Copy code
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(`${this.name} makes a noise.`);
};
function Dog(name) {
Animal.call(this, name); // Call the parent constructor
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.bark = function() {
console.log(`${this.name} barks.`);
};
const dog = new Dog('Rex');
dog.speak(); // "Rex makes a noise."
dog.bark(); // "Rex barks."
77. The Promise Object
A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
javascript
Copy code
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise resolved!');
}, 2000);
});
myPromise.then(result => console.log(result)); // "Promise resolved!" after 2 seconds
78. async and await
async functions return a promise, and await can be used inside them to wait for a promise to resolve.
javascript
Copy code
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
}
fetchData(); // Fetches data and logs it
79. The bind() Method
The bind() method creates a new function that, when called, has its this keyword set to a provided value.
javascript
Copy code
const obj = {
value: 42,
getValue: function() {
return this.value;
}
};
const getValue = obj.getValue.bind(obj);
console.log(getValue()); // 42
80. Object Destructuring
Object destructuring allows you to extract properties from an object into distinct variables.
javascript
Copy code
const person = { name: 'Alice', age: 25 };
const { name, age } = person;
console.log(name); // "Alice"
console.log(age); // 25
81. Array Destructuring
Array destructuring allows you to unpack values from arrays into distinct variables.
javascript
Copy code
const colors = ['red', 'green', 'blue'];
const [firstColor, secondColor] = colors;
console.log(firstColor); // "red"
console.log(secondColor); // "green"
82. Spread Operator
The spread operator (...) allows an iterable (like an array) to be expanded in places where zero or more arguments are expected.
javascript
Copy code
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]
83. Rest Parameters
Rest parameters allow you to represent an indefinite number of arguments as an array.
javascript
Copy code
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
84. The Map Object
The Map object holds key-value pairs, where keys can be any datatype, and maintains the insertion order.
javascript
Copy code
const map = new Map();
map.set('name', 'Alice');
map.set(1, 'one');
map.set(true, 'boolean');
console.log(map.get('name')); // "Alice"
console.log(map.size); // 3
85. The Set Object
The Set object lets you store unique values of any type, whether primitive values or object references.
javascript
Copy code
const set = new Set([1, 2, 2, 3]);
set.add(4);
console.log(set); // Set { 1, 2, 3, 4 }
86. The typeof Operator
The typeof operator returns a string indicating the type of the unevaluated operand.
javascript
Copy code
console.log(typeof 'Hello'); // "string"
console.log(typeof 123); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof {}); // "object"
console.log(typeof []; // "object" (arrays are objects in JavaScript)
console.log(typeof null); // "object"
87. The instanceof Operator
The instanceof operator tests whether an object is an instance of a specific class or constructor.
javascript
Copy code
class Person {}
const alice = new Person();
console.log(alice instanceof Person); // true
console.log(alice instanceof Object); // true
88. Event Delegation
Event delegation is a technique for managing events by using a single event listener on a parent element instead of multiple listeners on child elements.
javascript
Copy code
document.getElementById('parent').addEventListener('click', function(event) {
if (event.target.matches('.child')) {
console.log('Child clicked:', event.target.textContent);
}
});
89. Debouncing
Debouncing is a technique used to limit the rate at which a function is executed. It's commonly used with event handlers.
javascript
Copy code
function debounce(func, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), delay);
};
}
const log = debounce(() => console.log('Debounced!'), 1000);
window.addEventListener('resize', log);
90. Throttling
Throttling is a technique to ensure a function is only executed at most once in a specified time interval.
javascript
Copy code
function throttle(func, limit) {
let lastFunc;
let lastRan;
return function() {
const context = this;
const args = arguments;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(() => {
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
}
const log = throttle(() => console.log('Throttled!'), 2000);
window.addEventListener('scroll', log);
91. Closure
A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope.
javascript
Copy code
function outerFunction() {
let count = 0;
return function innerFunction() {
count++;
return count;
};
}
const counter = outerFunction();
console.log(counter()); // 1
console.log(counter()); // 2
92. Function Currying
Currying is a technique in functional programming where a function takes multiple arguments one at a time.
javascript
Copy code
function multiply(a) {
return function(b) {
return a * b;
};
}
const double = multiply(2);
console.log(double(5)); // 10
93. The reduce() Method
The reduce() method executes a reducer function on each element of the array, resulting in a single output value.
javascript
Copy code
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 10
94. The map() Method
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
javascript
Copy code
const numbers = [1, 2, 3];
const squares = numbers.map(num => num * num);
console.log(squares); // [1, 4, 9]
95. The filter() Method
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
javascript
Copy code
const numbers = [1, 2, 3, 4];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4]
96. The every() Method
The every() method tests whether all elements in the array pass the test implemented by the provided function.
javascript
Copy code
const numbers = [2, 4, 6];
const allEven = numbers.every(num => num % 2 === 0);
console.log(allEven); // true
97. The some() Method
The some() method tests whether at least one element in the array passes the test implemented by the provided function.
javascript
Copy code
const numbers = [1, 2, 3];
const hasEven = numbers.some(num => num % 2 === 0);
console.log(hasEven); // true
98. The find() Method
The find() method returns the value of the first element in the array that satisfies the provided testing function.
javascript
Copy code
const numbers = [1, 2, 3, 4];
const firstEven = numbers.find(num => num % 2 === 0);
console.log(firstEven); // 2
99. The includes() Method
The includes() method determines whether an array includes a certain value among its entries.
javascript
Copy code
const fruits = ['apple', 'banana', 'cherry'];
const hasBanana = fruits.includes('banana');
console.log(hasBanana); // true
100. The Array.from() Method
The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object.
javascript
Copy code
const str = 'hello';
const charArray = Array.from(str);
console.log(charArray); // ['h', 'e', 'l', 'l', 'o']
101. The Array.prototype.fill() Method
The fill() method fills all the elements of an array from a start index to an end index with a static value.
javascript
Copy code
const arr = new Array(5).fill(0);
console.log(arr); // [0, 0, 0, 0, 0]
102. The Array.prototype.concat() Method
The concat() method is used to merge two or more arrays. This method does not change the existing arrays but instead returns a new array.
javascript
Copy code
const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = arr1.concat(arr2);
console.log(merged); // [1, 2, 3, 4]
103. The Array.prototype.reverse() Method
The reverse() method reverses the elements of an array in place.
javascript
Copy code
const arr = [1, 2, 3];
arr.reverse();
console.log(arr); // [3, 2, 1]
104. The Array.prototype.sort() Method
The sort() method sorts the elements of an array in place and returns the sorted array.
javascript
Copy code
const numbers = [4, 1, 3, 2];
numbers.sort();
console.log(numbers); // [1, 2, 3, 4] (lexicographical order)
105. The Array.prototype.splice() Method
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
javascript
Copy code
const arr = [1, 2, 3, 4];
arr.splice(1, 2, 5, 6); // Remove 2 elements starting from index 1, and add 5 and 6
console.log(arr); // [1, 5, 6, 4]
106. The Array.prototype.slice() Method
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (not included).
javascript
Copy code
const arr = [1, 2, 3, 4];
const sliced = arr.slice(1, 3);
console.log(sliced); // [2, 3]
107. The forEach() Method
The forEach() method executes a provided function once for each array element.
javascript
Copy code
const arr = [1, 2, 3];
arr.forEach(num => console.log(num * 2)); // Logs 2, 4, 6
108. The filter() Method
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
javascript
Copy code
const numbers = [5, 12, 8, 130, 44];
const filtered = numbers.filter(num => num >= 10);
console.log(filtered); // [12, 130, 44]
109. The map() Method
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
javascript
Copy code
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
110. The findIndex() Method
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function.
javascript
Copy code
const numbers = [5, 12, 8, 130, 44];
const index = numbers.findIndex(num => num > 10);
console.log(index); // 1 (the index of 12)
111. The Array.prototype.every() Method
The every() method tests whether all elements in the array pass the test implemented by the provided function.
javascript
Copy code
const numbers = [1, 2, 3, 4];
const allLessThanFive = numbers.every(num => num < 5);
console.log(allLessThanFive); // true
112. The Array.prototype.some() Method
The some() method tests whether at least one element in the array passes the test implemented by the provided function.
javascript
Copy code
const numbers = [1, 2, 3, 4];
const hasEven = numbers.some(num => num % 2 === 0);
console.log(hasEven); // true
113. The Array.prototype.indexOf() Method
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
javascript
Copy code
const arr = [2, 5, 9];
const index = arr.indexOf(5);
console.log(index); // 1
114. The Array.prototype.lastIndexOf() Method
The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present.
javascript
Copy code
const arr = [2, 5, 9, 5];
const index = arr.lastIndexOf(5);
console.log(index); // 3
115. The Array.prototype.fill() Method
The fill() method fills all the elements of an array from a start index to an end index with a static value.
javascript
Copy code
const arr = [1, 2, 3, 4];
arr.fill(0, 1, 3);
console.log(arr); // [1, 0, 0, 4]
116. The Object.keys() Method
The keys() method returns an array of a given object's own enumerable property names.
javascript
Copy code
const obj = { name: 'Alice', age: 25 };
const keys = Object.keys(obj);
console.log(keys); // ["name", "age"]
117. The Object.values() Method
The values() method returns an array of a given object's own enumerable property values.
javascript
Copy code
const obj = { name: 'Alice', age: 25 };
const values = Object.values(obj);
console.log(values); // ["Alice", 25]
118. The Object.entries() Method
The entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs.
javascript
Copy code
const obj = { name: 'Alice', age: 25 };
const entries = Object.entries(obj);
console.log(entries); // [["name", "Alice"], ["age", 25]]
119. The Object.assign() Method
The assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.
javascript
Copy code
const target = { a: 1 };
const source = { b: 2, c: 3 };
const returnedTarget = Object.assign(target, source);
console.log(target); // { a: 1, b: 2, c: 3 }
120. The Object.freeze() Method
The freeze() method freezes an object, preventing new properties from being added to it and marking all existing properties as read-only.
javascript
Copy code
const obj = { name: 'Alice' };
Object.freeze(obj);
obj.name = 'Bob'; // This will not change the name
console.log(obj.name); // "Alice"
121. The Object.seal() Method
The seal() method seals an object, preventing new properties from being added and marking all existing properties as non-configurable.
javascript
Copy code
const obj = { name: 'Alice' };
Object.seal(obj);
obj.name = 'Bob'; // This will change the name
delete obj.name; // This will not work
console.log(obj.name); // "Bob"
122. The Object.create() Method
The create() method creates a new object, using an existing object as the prototype of the newly created object.
javascript
Copy code
const animal = {
speaks: function() {
console.log('Animal speaks');
}
};
const dog = Object.create(animal);
dog.bark = function() {
console.log('Dog barks');
};
dog.speaks(); // "Animal speaks"
dog.bark(); // "Dog barks"
123. The JSON.stringify() Method
The stringify() method converts a JavaScript object or value to a JSON string.
javascript
Copy code
const obj = { name: 'Alice', age: 25 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // '{"name":"Alice","age":25}'
124. The JSON.parse() Method
The parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
javascript
Copy code
const jsonString = '{"name":"Alice","age":25}';
const obj = JSON.parse(jsonString);
console.log(obj); // { name: 'Alice', age: 25 }
125. The fetch() API
The fetch() API provides a way to make network requests. It returns a promise that resolves to the response.
javascript
Copy code
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
126. The Promise.all() Method
The Promise.all() method takes an array of promises and returns a single promise that resolves when all of the promises in the array have resolved.
javascript
Copy code
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'foo');
});
Promise.all([promise1, promise2, promise3]).then(values => {
console.log(values); // [3, 42, "foo"]
});
127. The async and await Keywords
The async function declaration specifies that the function will return a promise. The await operator is used to wait for a promise to be resolved.
javascript
Copy code
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
}
fetchData();
128. The this Keyword
The this keyword refers to the object it belongs to. Its value is determined by how a function is called.
javascript
Copy code
const person = {
name: 'Alice',
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
person.greet(); // "Hello, my name is Alice"
129. Arrow Functions
Arrow functions provide a more concise syntax for writing function expressions. They also lexically bind the this value.
javascript
Copy code
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
const person = {
name: 'Alice',
greet: () => {
console.log(`Hello, my name is ${this.name}`);
}
};
person.greet(); // "Hello, my name is undefined"
130. The bind() Method
The bind() method creates a new function that, when called, has its this keyword set to the provided value.
javascript
Copy code
const person = {
name: 'Alice',
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
const greetAlice = person.greet.bind(person);
greetAlice(); // "Hello, my name is Alice"
131. The call() Method
The call() method calls a function with a given this value and arguments provided individually.
javascript
Copy code
function greet() {
console.log(`Hello, my name is ${this.name}`);
}
const person = { name: 'Alice' };
greet.call(person); // "Hello, my name is Alice"
132. The apply() Method
The apply() method calls a function with a given this value and arguments provided as an array.
javascript
Copy code
function greet(greeting) {
console.log(`${greeting}, my name is ${this.name}`);
}
const person = { name: 'Alice' };
greet.apply(person, ['Hi']); // "Hi, my name is Alice"
133. The setTimeout() Function
The setTimeout() function sets a timer which executes a function or specified piece of code once the timer expires.
javascript
Copy code
setTimeout(() => {
console.log('Executed after 2 seconds');
}, 2000);
134. The setInterval() Function
The setInterval() function repeatedly calls a function or executes code, with a fixed time delay between each call.
javascript
Copy code
const intervalId = setInterval(() => {
console.log('Executed every 1 second');
}, 1000);
// To stop the interval after 5 seconds
setTimeout(() => {
clearInterval(intervalId);
}, 5000);
135. The clearTimeout() Function
The clearTimeout() function cancels a timeout previously established by calling setTimeout().
javascript
Copy code
const timeoutId = setTimeout(() => {
console.log('This will not be logged');
}, 2000);
clearTimeout(timeoutId); // Cancels the timeout
136. The clearInterval() Function
The clearInterval() function cancels a timed, repeating action that was established by calling setInterval().
javascript
Copy code
const intervalId = setInterval(() => {
console.log('Executed every 1 second');
}, 1000);
clearInterval(intervalId); // Cancels the interval
137. The Math Object
The Math object provides mathematical constants and functions.
javascript
Copy code
console.log(Math.PI); // 3.141592653589793
console.log(Math.sqrt(16)); // 4
console.log(Math.random()); // Random number between 0 and 1
138. The Math.max() and Math.min() Methods
The Math.max() and Math.min() methods return the largest and smallest of zero or more numbers, respectively.
javascript
Copy code
console.log(Math.max(1, 2, 3)); // 3
console.log(Math.min(1, 2, 3)); // 1
139. The Math.floor(), Math.ceil(), and Math.round() Methods
Math.floor() returns the largest integer less than or equal to a given number.
Math.ceil() returns the smallest integer greater than or equal to a given number.
Math.round() returns the value of a number rounded to the nearest integer.
javascript
Copy code
console.log(Math.floor(3.7)); // 3
console.log(Math.ceil(3.2)); // 4
console.log(Math.round(3.5)); // 4
140. The Array.prototype.sort() Method
The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is according to string Unicode code points.
javascript
Copy code
const numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b); // Ascending order
console.log(numbers); // [1, 2, 3, 4, 5]
141. The Array.prototype.reduce() Method
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
javascript
Copy code
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 10
142. The Object.assign() Method
The assign() method copies the values of all enumerable own properties from one or more source objects to a target object.
javascript
Copy code
const target = { a: 1 };
const source = { b: 2, c: 3 };
const returnedTarget = Object.assign(target, source);
console.log(returnedTarget); // { a: 1, b: 2, c: 3 }
143. The String.prototype.split() Method
The split() method splits a string into an array of substrings, and returns the new array.
javascript
Copy code
const str = 'Hello, world!';
const words = str.split(', ');
console.log(words); // ["Hello", "world!"]
144. The String.prototype.join() Method
The join() method joins all elements of an array into a string.
javascript
Copy code
const arr = ['Hello', 'world!'];
const str = arr.join(', ');
console.log(str); // "Hello, world!"
145. The String.prototype.replace() Method
The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.
javascript
Copy code
const str = 'Hello, world!';
const newStr = str.replace('world', 'there');
console.log(newStr); // "Hello, there!"
146. The String.prototype.includes() Method
The includes() method determines whether one string may be found within another string.
javascript
Copy code
const str = 'Hello, world!';
const hasWorld = str.includes('world');
console.log(hasWorld); // true
147. The String.prototype.indexOf() Method
The indexOf() method returns the index of the first occurrence of a specified value in a string, or -1 if not found.
javascript
Copy code
const str = 'Hello, world!';
const index = str.indexOf('world');
console.log(index); // 7
148. The String.prototype.slice() Method
The slice() method returns a shallow copy of a portion of a string into a new string object.
javascript
Copy code
const str = 'Hello, world!';
const sliced = str.slice(7, 12);
console.log(sliced); // "world"
149. The String.prototype.trim() Method
The trim() method removes whitespace from both ends of a string.
javascript
Copy code
const str = ' Hello, world! ';
const trimmed = str.trim();
console.log(trimmed); // "Hello, world!"
150. The String.prototype.toUpperCase() and toLowerCase() Methods
The toUpperCase() method converts a string to uppercase, and toLowerCase() converts a string to lowercase.
javascript
Copy code
const str = 'Hello, World!';
console.log(str.toUpperCase()); // "HELLO, WORLD!"
console.log(str.toLowerCase()); // "hello, world!"
151. The Array.prototype.shift() Method
The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.
javascript
Copy code
const arr = [1, 2, 3];
const firstElement = arr.shift();
console.log(firstElement); // 1
console.log(arr); // [2, 3]
152. The Array.prototype.unshift() Method
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
javascript
Copy code
const arr = [2, 3];
const newLength = arr.unshift(1);
console.log(newLength); // 3
console.log(arr); // [1, 2, 3]
153. The Array.prototype.pop() Method
The pop() method removes the last element from an array and returns that element. This method changes the length of the array.
javascript
Copy code
const arr = [1, 2, 3];
const lastElement = arr.pop();
console.log(lastElement); // 3
console.log(arr); // [1, 2]
154. The Array.prototype.push() Method
The push() method adds one or more elements to the end of an array and returns the new length of the array.
javascript
Copy code
const arr = [1, 2];
const newLength = arr.push(3);
console.log(newLength); // 3
console.log(arr); // [1, 2, 3]
155. The Array.prototype.includes() Method
The includes() method determines whether an array includes a certain value among its entries, returning true or false.
javascript
Copy code
const arr = [1, 2, 3];
const hasTwo = arr.includes(2);
console.log(hasTwo); // true
156. The Array.prototype.reduceRight() Method
The reduceRight() method executes a reducer function on each element of the array, from right to left, reducing it to a single value.
javascript
Copy code
const arr = [1, 2, 3];
const reversedSum = arr.reduceRight((acc, current) => acc + current, 0);
console.log(reversedSum); // 6 (3 + 2 + 1)
157. The Object.prototype.hasOwnProperty() Method
The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property.
javascript
Copy code
const obj = { name: 'Alice' };
console.log(obj.hasOwnProperty('name')); // true
console.log(obj.hasOwnProperty('age')); // false
158. The String.prototype.charAt() Method
The charAt() method returns the character at a specified index in a string.
javascript
Copy code
const str = 'Hello';
const char = str.charAt(1);
console.log(char); // "e"
159. The String.prototype.split() Method
The split() method splits a string into an array of substrings, and returns the new array.
javascript
Copy code
const str = 'a,b,c';
const arr = str.split(',');
console.log(arr); // ["a", "b", "c"]
160. The String.prototype.lastIndexOf() Method
The lastIndexOf() method returns the index of the last occurrence of a specified value in a string.
javascript
Copy code
const str = 'Hello, world! Hello!';
const index = str.lastIndexOf('Hello');
console.log(index); // 13
161. The String.prototype.match() Method
The match() method retrieves the matches when matching a string against a regular expression.
javascript
Copy code
const str = 'The rain in SPAIN stays mainly in the plain';
const matches = str.match(/ain/g);
console.log(matches); // ["ain", "ain", "ain"]
162. The String.prototype.search() Method
The search() method executes a search for a match between a regular expression and this String object.
javascript
Copy code
const str = 'The quick brown fox';
const index = str.search(/quick/);
console.log(index); // 4
163. The String.prototype.slice() Method
The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.
javascript
Copy code
const str = 'Hello, world!';
const sliced = str.slice(0, 5);
console.log(sliced); // "Hello"
164. The String.prototype.replaceAll() Method
The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement.
javascript
Copy code
const str = 'foo bar foo';
const newStr = str.replaceAll('foo', 'baz');
console.log(newStr); // "baz bar baz"
165. The String.prototype.startsWith() Method
The startsWith() method determines whether a string begins with the characters of a specified string.
javascript
Copy code
const str = 'Hello, world!';
console.log(str.startsWith('Hello')); // true
166. The String.prototype.endsWith() Method
The endsWith() method determines whether a string ends with the characters of a specified string.
javascript
Copy code
const str = 'Hello, world!';
console.log(str.endsWith('world!')); // true
167. The String.prototype.valueOf() Method
The valueOf() method returns the primitive value of a String object.
javascript
Copy code
const str = new String('Hello');
console.log(str.valueOf()); // "Hello"
168. The Number.isNaN() Method
The isNaN() method determines whether the passed value is NaN and its type is Number.
javascript
Copy code
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN(5)); // false
169. The Number.isInteger() Method
The isInteger() method determines whether the passed value is an integer.
javascript
Copy code
console.log(Number.isInteger(4)); // true
console.log(Number.isInteger(4.5)); // false
170. The Number.parseFloat() Method
The parseFloat() function parses a string argument and returns a floating point number.
javascript
Copy code
const num = Number.parseFloat('3.14');
console.log(num); // 3.14
171. The Number.parseInt() Method
The parseInt() function parses a string argument and returns an integer of the specified radix.
javascript
Copy code
const num = Number.parseInt('10', 2);
console.log(num); // 2 (binary)
172. The Array.from() Method
The from() method creates a new, shallow-copied Array instance from an array-like or iterable object.
javascript
Copy code
const str = 'Hello';
const chars = Array.from(str);
console.log(chars); // ['H', 'e', 'l', 'l', 'o']
173. The Array.of() Method
The of() method creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
javascript
Copy code
const arr = Array.of(1, 2, 3);
console.log(arr); // [1, 2, 3]
174. The Set Object
The Set object lets you store unique values of any type, whether primitive values or object references.
javascript
Copy code
const uniqueNumbers = new Set([1, 2, 2, 3]);
console.log(uniqueNumbers); // Set { 1, 2, 3 }
175. The Map Object
The Map object holds key-value pairs and remembers the original insertion order of the keys.
javascript
Copy code
const map = new Map();
map.set('name', 'Alice');
map.set('age', 25);
console.log(map.get('name')); // "Alice"
176. The WeakSet Object
The WeakSet is a collection of objects, and its references are weakly held. This means that if there are no other references to the object, it can be garbage collected.
javascript
Copy code
const obj = {};
const weakSet = new WeakSet();
weakSet.add(obj);
console.log(weakSet.has(obj)); // true
177. The WeakMap Object
The WeakMap is a collection of key-value pairs where keys are objects and values can be any value. The references to the keys are weakly held.
javascript
Copy code
const weakMap = new WeakMap();
const obj = {};
weakMap.set(obj, 'value');
console.log(weakMap.get(obj)); // "value"
178. The Promise Object
The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
javascript
Copy code
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Success!');
}, 1000);
});
myPromise.then(result => console.log(result)); // "Success!" after 1 second
179. The Promise.allSettled() Method
The allSettled() method returns a promise that resolves after all of the given promises have either resolved or rejected, with an array of objects that each describe the outcome of each promise.
javascript
Copy code
const p1 = Promise.resolve(3);
const p2 = Promise.reject('error');
const p3 = Promise.resolve('done');
Promise.allSettled([p1, p2, p3]).then(results => {
console.log(results);
// [
// { status: 'fulfilled', value: 3 },
// { status: 'rejected', reason: 'error' },
// { status: 'fulfilled', value: 'done' }
// ]
});
180. The Promise.race() Method
The race() method returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects, with the value or reason from that promise.
javascript
Copy code
const p1 = new Promise((resolve) => setTimeout(resolve, 100, 'one'));
const p2 = new Promise((resolve) => setTimeout(resolve, 200, 'two'));
Promise.race([p1, p2]).then(value => {
console.log(value); // "one" (first promise to resolve)
});
181. The async and await Keywords
The async keyword is used to declare an asynchronous function, and the await keyword is used to wait for a promise to resolve within an async function.
javascript
Copy code
const fetchData = async () => {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
};
fetchData().then(data => console.log(data));
182. The EventEmitter Class
The EventEmitter class is part of the Node.js events module and is used to handle events in Node.js.
javascript
Copy code
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {
console.log('An event occurred!');
});
myEmitter.emit('event'); // "An event occurred!"
183. The fetch API
The fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses.
javascript
Copy code
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
184. The setTimeout() Function
The setTimeout() function executes a function, after a specified number of milliseconds.
javascript
Copy code
console.log('Start');
setTimeout(() => {
console.log('Timeout executed!');
}, 1000);
console.log('End');
// Output:
// Start
// End
// Timeout executed! (after 1 second)
185. The setInterval() Function
The setInterval() function calls a function or executes a code snippet repeatedly, with a fixed time delay between each call.
javascript
Copy code
let count = 0;
const intervalId = setInterval(() => {
console.log(`Count: ${count}`);
count++;
if (count === 5) {
clearInterval(intervalId); // Clear interval after 5 counts
}
}, 1000);
186. The clearTimeout() and clearInterval() Functions
clearTimeout() and clearInterval() are used to cancel a timeout or an interval, respectively.
javascript
Copy code
const timeoutId = setTimeout(() => {
console.log('This will not run.');
}, 1000);
clearTimeout(timeoutId); // Cancels the timeout
187. The Array.prototype.find() Method
The find() method returns the value of the first element in the array that satisfies the provided testing function.
javascript
Copy code
const arr = [5, 12, 8, 130, 44];
const found = arr.find(element => element > 10);
console.log(found); // 12
188. The Array.prototype.findIndex() Method
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function.
javascript
Copy code
const arr = [5, 12, 8, 130, 44];
const index = arr.findIndex(element => element > 10);
console.log(index); // 1
189. The Array.prototype.every() Method
The every() method tests whether all elements in the array pass the test implemented by the provided function.
javascript
Copy code
const arr = [1, 30, 39, 29, 10, 13];
const allLessThan40 = arr.every(element => element < 40);
console.log(allLessThan40); // true
190. The Array.prototype.some() Method
The some() method tests whether at least one element in the array passes the test implemented by the provided function.
javascript
Copy code
const arr = [1, 30, 39, 29, 10, 13];
const someLessThan10 = arr.some(element => element < 10);
console.log(someLessThan10); // true
191. The Array.prototype.flat() Method
The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
javascript
Copy code
const arr = [1, 2, [3, 4, [5, 6]]];
const flattened = arr.flat(2);
console.log(flattened); // [1, 2, 3, 4, 5, 6]
192. The Array.prototype.flatMap() Method
The flatMap() method first maps each element using a mapping function, then flattens the result into a new array.
javascript
Copy code
const arr = [1, 2, 3];
const doubled = arr.flatMap(x => [x, x * 2]);
console.log(doubled); // [1, 2, 2, 4, 3, 6]
193. The Object.assign() Method
The assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.
javascript
Copy code
const target = { a: 1 };
const source = { b: 2, c: 3 };
const returnedTarget = Object.assign(target, source);
console.log(returnedTarget); // { a: 1, b: 2, c: 3 }
194. The Object.keys() Method
The keys() method returns an array of a given object's own enumerable property names.
javascript
Copy code
const obj = { a: 1, b: 2, c: 3 };
const keys = Object.keys(obj);
console.log(keys); // ['a', 'b', 'c']
195. The Object.values() Method
The values() method returns an array of a given object's own enumerable property values.
javascript
Copy code
const obj = { a: 1, b: 2, c: 3 };
const values = Object.values(obj);
console.log(values); // [1, 2, 3]
196. The Object.entries() Method
The entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs.
javascript
Copy code
const obj = { a: 1, b: 2, c: 3 };
const entries = Object.entries(obj);
console.log(entries); // [['a', 1], ['b', 2], ['c', 3]]
197. The JSON.stringify() Method
The stringify() method converts a JavaScript object or value to a JSON string.
javascript
Copy code
const obj = { name: 'Alice', age: 25 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // '{"name":"Alice","age":25}'
198. The JSON.parse() Method
The parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
javascript
Copy code
const jsonString = '{"name":"Alice","age":25}';
const obj = JSON.parse(jsonString);
console.log(obj); // { name: 'Alice', age: 25 }
199. The Function.prototype.bind() Method
The bind() method creates a new function that, when called, has its this keyword set to the provided value.
javascript
Copy code
const obj = { value: 42 };
function getValue() {
return this.value;
}
const boundGetValue = getValue.bind(obj);
console.log(boundGetValue()); // 42
200. The Function.prototype.call() and Function.prototype.apply() Methods
The call() method calls a function with a given this value and arguments provided individually, while the apply() method calls a function with a given this value and arguments provided as an array.
javascript
Copy code
function greet(greeting) {
return `${greeting}, ${this.name}!`;
}
const user = { name: 'Alice' };
console.log(greet.call(user, 'Hello')); // "Hello, Alice!"
console.log(greet.apply(user, ['Hi'])); // "Hi, Alice!"
201. The Function.prototype.apply() Method
The apply() method calls a function with a given this value and arguments provided as an array.
javascript
Copy code
function add(a, b) {
return a + b;
}
const result = add.apply(null, [5, 10]);
console.log(result); // 15
202. The Function.prototype.call() Method
The call() method calls a function with a given this value and arguments provided individually.
javascript
Copy code
function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
const person = { name: 'Bob' };
console.log(greet.call(person, 'Hello', '!')); // "Hello, Bob!"
203. The Math Object
The Math object is a built-in object that has properties and methods for mathematical constants and functions.
javascript
Copy code
const radius = 5;
const area = Math.PI * Math.pow(radius, 2);
console.log(area); // 78.53981633974483
204. The Date Object
The Date object is used to work with dates and times in JavaScript.
javascript
Copy code
const date = new Date();
console.log(date); // Current date and time
console.log(date.getFullYear()); // Current year
205. The Array.prototype.sort() Method
The sort() method sorts the elements of an array in place and returns the sorted array.
javascript
Copy code
const numbers = [5, 3, 8, 1];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 3, 5, 8]
206. The Array.prototype.reverse() Method
The reverse() method reverses the elements of an array in place.
javascript
Copy code
const numbers = [1, 2, 3, 4];
numbers.reverse();
console.log(numbers); // [4, 3, 2, 1]
207. The Array.prototype.concat() Method
The concat() method is used to merge two or more arrays.
javascript
Copy code
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = arr1.concat(arr2);
console.log(combined); // [1, 2, 3, 4]
208. The Array.prototype.splice() Method
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements.
javascript
Copy code
const arr = [1, 2, 3, 4];
arr.splice(1, 2, 5, 6); // Removes 2 elements starting from index 1 and adds 5 and 6
console.log(arr); // [1, 5, 6, 4]
209. The Array.prototype.slice() Method
The slice() method returns a shallow copy of a portion of an array into a new array object.
javascript
Copy code
const arr = [1, 2, 3, 4];
const sliced = arr.slice(1, 3);
console.log(sliced); // [2, 3]
210. The Array.prototype.reduce() Method
The reduce() method executes a reducer function on each element of the array, resulting in a single output value.
javascript
Copy code
const arr = [1, 2, 3, 4];
const sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 10
211. The Array.prototype.reduceRight() Method
The reduceRight() method executes a reducer function on each element of the array, from right to left.
javascript
Copy code
const arr = [1, 2, 3, 4];
const product = arr.reduceRight((acc, val) => acc * val, 1);
console.log(product); // 24
212. The Array.prototype.fill() Method
The fill() method fills all the elements of an array from a start index to an end index with a static value.
javascript
Copy code
const arr = new Array(3).fill(0);
console.log(arr); // [0, 0, 0]
213. The Array.prototype.includes() Method
The includes() method determines whether an array includes a certain value among its entries.
javascript
Copy code
const arr = [1, 2, 3];
const includesTwo = arr.includes(2);
console.log(includesTwo); // true
214. The Set Object
The Set object lets you store unique values of any type.
javascript
Copy code
const uniqueNumbers = new Set([1, 2, 2, 3]);
console.log(uniqueNumbers); // Set { 1, 2, 3 }
215. The Map Object
The Map object holds key-value pairs, and keys can be of any type.
javascript
Copy code
const map = new Map();
map.set('a', 1);
map.set('b', 2);
console.log(map.get('a')); // 1
216. The WeakSet Object
The WeakSet is a collection of objects, where the references to the objects are weakly held.
javascript
Copy code
const weakSet = new WeakSet();
const obj = {};
weakSet.add(obj);
console.log(weakSet.has(obj)); // true
217. The WeakMap Object
The WeakMap is a collection of key-value pairs, where keys are objects and values can be any type.
javascript
Copy code
const weakMap = new WeakMap();
const obj = {};
weakMap.set(obj, 'value');
console.log(weakMap.get(obj)); // 'value'
218. The Promise Object
The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
javascript
Copy code
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Success!');
}, 1000);
});
myPromise.then(result => console.log(result)); // 'Success!' (after 1 second)
219. The Promise.all() Method
The Promise.all() method takes an iterable of Promise objects and, when all of the promises have been resolved, returns a single Promise that resolves to an array of the results.
javascript
Copy code
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve) => setTimeout(resolve, 100, 'foo'));
Promise.all([promise1, promise2, promise3]).then(values => {
console.log(values); // [3, 42, 'foo']
});
220. The Promise.race() Method
The Promise.race() method returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects.
javascript
Copy code
const promise1 = new Promise((resolve) => setTimeout(resolve, 500, 'one'));
const promise2 = new Promise((resolve) => setTimeout(resolve, 100, 'two'));
Promise.race([promise1, promise2]).then(value => {
console.log(value); // 'two'
});
221. The async/await Syntax
The async function is a function that always returns a promise, and the await keyword is used to wait for a promise to resolve.
javascript
Copy code
async function fetchData() {
return 'Data fetched!';
}
fetchData().then(console.log); // 'Data fetched!'
222. Handling Errors with try/catch
You can use try and catch blocks to handle errors in asynchronous functions.
javascript
Copy code
async function fetchData() {
throw new Error('Fetch error!');
}
fetchData().catch(error => {
console.error(error.message); // 'Fetch error!'
});
223. The fetch() API
The fetch() API is a modern way to make network requests. It returns a promise that resolves to the Response object representing the response to the request.
javascript
Copy code
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));
224. The window.localStorage API
The localStorage API allows you to store data in the web browser persistently.
javascript
Copy code
localStorage.setItem('username', 'Alice');
console.log(localStorage.getItem('username')); // 'Alice'
225. The window.sessionStorage API
The sessionStorage API allows you to store data for the duration of the page session.
javascript
Copy code
sessionStorage.setItem('sessionID', '12345');
console.log(sessionStorage.getItem('sessionID')); // '12345'
226. The window.alert() Method
The alert() method displays an alert dialog with a specified message and an OK button.
javascript
Copy code
alert('This is an alert message!');
227. The window.confirm() Method
The confirm() method displays a dialog with a specified message, along with OK and Cancel buttons.
javascript
Copy code
const userConfirmed = confirm('Do you want to proceed?');
console.log(userConfirmed); // true if OK, false if Cancel
228. The window.prompt() Method
The prompt() method displays a dialog with a message prompting the user to input some text.
javascript
Copy code
const userInput = prompt('Please enter your name:');
console.log(`Hello, ${userInput}!`);
229. The setTimeout() Function
The setTimeout() function calls a function or evaluates an expression after a specified number of milliseconds.
javascript
Copy code
setTimeout(() => {
console.log('This message is delayed by 2 seconds.');
}, 2000);
230. The setInterval() Function
The setInterval() function repeatedly calls a function with a fixed time delay between each call.
javascript
Copy code
let count = 0;
const intervalId = setInterval(() => {
count++;
console.log(`Count: ${count}`);
if (count === 5) clearInterval(intervalId); // Stops after 5
}, 1000);
231. The clearTimeout() Function
The clearTimeout() function cancels a timeout previously established by setTimeout().
javascript
Copy code
const timeoutId = setTimeout(() => {
console.log('This will not run.');
}, 1000);
clearTimeout(timeoutId); // Cancels the timeout
232. The clearInterval() Function
The clearInterval() function cancels a timed, repeating action which was established by setInterval().
javascript
Copy code
const intervalId = setInterval(() => {
console.log('This will not run.');
}, 1000);
clearInterval(intervalId); // Cancels the interval
233. The this Keyword
The this keyword refers to the context in which a function is called.
javascript
Copy code
const obj = {
name: 'Alice',
greet: function() {
console.log(`Hello, ${this.name}`);
},
};
obj.greet(); // 'Hello, Alice'
234. Arrow Functions and this
Arrow functions do not have their own this context; they inherit this from the parent scope.
javascript
Copy code
const obj = {
name: 'Alice',
greet: () => {
console.log(`Hello, ${this.name}`); // 'this' is not the same as the object
},
};
obj.greet(); // 'Hello, undefined'
235. The instanceof Operator
The instanceof operator tests whether an object is an instance of a specific constructor.
javascript
Copy code
const date = new Date();
console.log(date instanceof Date); // true
console.log(date instanceof Object); // true
236. The typeof Operator
The typeof operator returns a string indicating the type of the unevaluated operand.
javascript
Copy code
console.log(typeof 'Hello'); // 'string'
console.log(typeof 42); // 'number'
console.log(typeof true); // 'boolean'
237. The in Operator
The in operator checks if a property exists in an object.
javascript
Copy code
const obj = { name: 'Alice', age: 25 };
console.log('name' in obj); // true
console.log('gender' in obj); // false
238. The delete Operator
The delete operator removes a property from an object.
javascript
Copy code
const obj = { name: 'Alice', age: 25 };
delete obj.age;
console.log(obj); // { name: 'Alice' }
239. Template Literals
Template literals are string literals that allow embedded expressions and multi-line strings, using backticks (`).
javascript
Copy code
const name = 'Alice';
const greeting = `Hello, ${name}!`;
console.log(greeting); // 'Hello, Alice!'
240. Destructuring Assignment
Destructuring assignment allows unpacking values from arrays or properties from objects into distinct variables.
javascript
Copy code
const arr = [1, 2, 3];
const [first, second] = arr;
console.log(first); // 1
console.log(second); // 2
const obj = { a: 1, b: 2 };
const { a, b } = obj;
console.log(a); // 1
console.log(b); // 2
241. Spread Operator
The spread operator (...) allows an iterable, such as an array or object, to be expanded in places where zero or more arguments or elements are expected.
javascript
Copy code
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3 };
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj); // { a: 1, b: 2, c: 3 }
242. Rest Parameters
Rest parameters allow a function to accept an indefinite number of arguments as an array.
javascript
Copy code
function sum(...args) {
return args.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
243. Default Function Parameters
Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.
javascript
Copy code
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet(); // 'Hello, Guest!'
greet('Alice'); // 'Hello, Alice!'
244. Promise Chaining
Promise chaining allows you to execute asynchronous operations in sequence by returning a promise from each then() method.
javascript
Copy code
const fetchData = () => Promise.resolve('Data fetched!');
fetchData()
.then(data => {
console.log(data);
return 'Next data';
})
.then(nextData => {
console.log(nextData);
});
245. The Promise.all() Method
The Promise.all() method takes an iterable of promises and returns a single promise that resolves when all of the promises have resolved.
javascript
Copy code
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve) => setTimeout(resolve, 100, 'foo'));
Promise.all([promise1, promise2, promise3]).then(values => {
console.log(values); // [3, 42, 'foo']
});
246. The Promise.race() Method
The Promise.race() method returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects.
javascript
Copy code
const promise1 = new Promise((resolve) => setTimeout(resolve, 500, 'one'));
const promise2 = new Promise((resolve) => setTimeout(resolve, 100, 'two'));
Promise.race([promise1, promise2]).then(value => {
console.log(value); // 'two'
});
247. The async Keyword
The async keyword is used to declare an asynchronous function that always returns a promise.
javascript
Copy code
async function fetchData() {
return 'Data fetched!';
}
fetchData().then(console.log); // 'Data fetched!'
248. The await Keyword
The await keyword is used to wait for a promise to resolve. It can only be used inside async functions.
javascript
Copy code
async function fetchData() {
const result = await Promise.resolve('Data fetched!');
console.log(result); // 'Data fetched!'
}
fetchData();
249. The bind() Method
The bind() method creates a new function that, when called, has its this keyword set to the provided value.
javascript
Copy code
const obj = {
name: 'Alice',
};
function greet() {
console.log(`Hello, ${this.name}`);
}
const boundGreet = greet.bind(obj);
boundGreet(); // 'Hello, Alice'
250. The call() Method
The call() method calls a function with a given this value and arguments provided individually.
javascript
Copy code
const obj = {
name: 'Alice',
};
function greet() {
console.log(`Hello, ${this.name}`);
}
greet.call(obj); // 'Hello, Alice'
251. The apply() Method
The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).
javascript
Copy code
const obj = {
name: 'Alice',
};
function greet(greeting) {
console.log(`${greeting}, ${this.name}`);
}
greet.apply(obj, ['Hi']); // 'Hi, Alice'
252. Prototypal Inheritance
In JavaScript, objects can inherit properties and methods from other objects through the prototype chain.
javascript
Copy code
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, ${this.name}`);
};
const alice = new Person('Alice');
alice.greet(); // 'Hello, Alice'
253. The Object.create() Method
The Object.create() method creates a new object with the specified prototype object and properties.
javascript
Copy code
const person = {
greet() {
console.log(`Hello, ${this.name}`);
},
};
const alice = Object.create(person);
alice.name = 'Alice';
alice.greet(); // 'Hello, Alice'
254. The Object.assign() Method
The Object.assign() method copies the values of all enumerable properties from one or more source objects to a target object.
javascript
Copy code
const target = { a: 1 };
const source = { b: 2, c: 3 };
const returnedTarget = Object.assign(target, source);
console.log(target); // { a: 1, b: 2, c: 3 }
console.log(returnedTarget === target); // true
255. The Object.keys() Method
The Object.keys() method returns an array of a given object's own enumerable property names.
javascript
Copy code
const obj = { a: 1, b: 2, c: 3 };
const keys = Object.keys(obj);
console.log(keys); // ['a', 'b', 'c']
256. The Object.values() Method
The Object.values() method returns an array of a given object's own enumerable property values.
javascript
Copy code
const obj = { a: 1, b: 2, c: 3 };
const values = Object.values(obj);
console.log(values); // [1, 2, 3]
257. The Object.entries() Method
The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs.
javascript
Copy code
const obj = { a: 1, b: 2, c: 3 };
const entries = Object.entries(obj);
console.log(entries); // [['a', 1], ['b', 2], ['c', 3]]
258. The Array.prototype.map() Method
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
javascript
Copy code
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
259. The Array.prototype.filter() Method
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
javascript
Copy code
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4]
260. The Array.prototype.reduce() Method
The reduce() method executes a reducer function on each element of the array, resulting in a single output value.
javascript
Copy code
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 10
261. The Array.prototype.some() Method
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
javascript
Copy code
const numbers = [1, 2, 3, 4, 5];
const hasEven = numbers.some(num => num % 2 === 0);
console.log(hasEven); // true
262. The Array.prototype.every() Method
The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
javascript
Copy code
const numbers = [2, 4, 6];
const allEven = numbers.every(num => num % 2 === 0);
console.log(allEven); // true
263. The Array.prototype.find() Method
The find() method returns the value of the first element in the provided array that satisfies the provided testing function.
javascript
Copy code
const numbers = [1, 2, 3, 4, 5];
const found = numbers.find(num => num > 3);
console.log(found); // 4
264. The Array.prototype.indexOf() Method
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
javascript
Copy code
const numbers = [1, 2, 3, 4];
const index = numbers.indexOf(3);
console.log(index); // 2
265. The Array.prototype.includes() Method
The includes() method determines whether an array includes a certain value among its entries, returning true or false.
javascript
Copy code
const numbers = [1, 2, 3, 4];
const includesThree = numbers.includes(3);
console.log(includesThree); // true
266. The String.prototype.split() Method
The split() method splits a string into an array of substrings based on a specified delimiter.
javascript
Copy code
const str = 'Hello, world!';
const arr = str.split(', ');
console.log(arr); // ['Hello', 'world!']
267. The String.prototype.join() Method
The join() method joins all elements of an array into a single string, separated by a specified delimiter.
javascript
Copy code
const arr = ['Hello', 'world'];
const str = arr.join(', ');
console.log(str); // 'Hello, world'
268. Template Literals
Template literals are string literals that allow embedded expressions. They can be used for multi-line strings and string interpolation.
javascript
Copy code
const name = 'Alice';
const greeting = `Hello, ${name}!`;
console.log(greeting); // 'Hello, Alice!'
269. Arrow Functions
Arrow functions provide a concise syntax for writing function expressions. They do not have their own this context.
javascript
Copy code
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
const square = x => x * x;
console.log(square(4)); // 16
270. Destructuring Assignment
Destructuring assignment allows unpacking values from arrays or properties from objects into distinct variables.
javascript
Copy code
const arr = [1, 2, 3];
const [a, b] = arr;
console.log(a, b); // 1 2
const obj = { x: 1, y: 2 };
const { x, y } = obj;
console.log(x, y); // 1 2
271. The for...of Loop
The for...of loop creates a loop iterating over iterable objects (like arrays, strings, etc.) and returns the values of the iterable.
javascript
Copy code
const numbers = [1, 2, 3];
for (const number of numbers) {
console.log(number); // 1 2 3
}
272. The for...in Loop
The for...in loop iterates over the enumerable properties of an object.
javascript
Copy code
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
console.log(`${key}: ${obj[key]}`); // a: 1 b: 2 c: 3
}
273. The Map Object
The Map object holds key-value pairs and remembers the original insertion order of the keys.
javascript
Copy code
const map = new Map();
map.set('a', 1);
map.set('b', 2);
console.log(map.get('a')); // 1
console.log(map.has('b')); // true
274. The Set Object
The Set object lets you store unique values of any type, whether primitive values or object references.
javascript
Copy code
const set = new Set();
set.add(1);
set.add(2);
set.add(1); // Will not be added again
console.log(set.size); // 2
275. The JSON.stringify() Method
The JSON.stringify() method converts a JavaScript object or value to a JSON string.
javascript
Copy code
const obj = { a: 1, b: 2 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // '{"a":1,"b":2}'
276. The JSON.parse() Method
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
javascript
Copy code
const jsonString = '{"a":1,"b":2}';
const obj = JSON.parse(jsonString);
console.log(obj); // { a: 1, b: 2 }
277. The fetch() API
The fetch() API provides a modern way to make network requests. It returns a promise that resolves to the response to the request.
javascript
Copy code
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
278. The localStorage API
The localStorage API provides a simple synchronous key-value store that persists even after the page is closed.
javascript
Copy code
localStorage.setItem('name', 'Alice');
console.log(localStorage.getItem('name')); // 'Alice'
localStorage.removeItem('name');
279. The sessionStorage API
The sessionStorage API provides a temporary key-value store that is available only during the page session.
javascript
Copy code
sessionStorage.setItem('sessionName', 'Bob');
console.log(sessionStorage.getItem('sessionName')); // 'Bob'
sessionStorage.removeItem('sessionName');
280. Event Delegation
Event delegation is a technique that leverages event bubbling to handle events at a higher level in the DOM rather than at the level of individual elements.
html
Copy code
<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<script>
document.getElementById('list').addEventListener('click', function(event) {
if (event.target.tagName === 'LI') {
console.log(`Clicked on ${event.target.textContent}`);
}
});
</script>