From ec0701644f90676742b87c647ab20837b7be1261 Mon Sep 17 00:00:00 2001 From: "vitaly.basaraba" Date: Sun, 19 Jan 2025 12:09:39 +0000 Subject: [PATCH] Bugfixed: quetion theme --- helpers/output.md | 12599 -------------------------------------------- question.json | 8736 +++++++++++++++--------------- 2 files changed, 4409 insertions(+), 16926 deletions(-) delete mode 100644 helpers/output.md diff --git a/helpers/output.md b/helpers/output.md deleted file mode 100644 index 2baed98..0000000 --- a/helpers/output.md +++ /dev/null @@ -1,12599 +0,0 @@ -## What is IndexedDB - -### What is IndexedDB? - -IndexedDB is a low-level API for storing large amounts of structured data, including files and blobs. It allows developers to perform advanced queries and store data persistently in a user's browser. This API is particularly useful for web applications that need to work offline or require local storage beyond simple key-value pairs. - -**Tags**: basic, IndexedDB, db, storage - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448276165661314336](https://www.tiktok.com/@jsmentoring/photo/7448276165661314336) - ---- - -## What are the options in a cookie - -### What are the options in a cookie? - -Cookies have several options to control their behavior, such as `path`, `domain`, `secure`, `HttpOnly`, and `SameSite`. These options help define the scope, security, and accessibility of the cookie. - -**Tags**: basic, cookie, options, storage - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448261980567145761](https://www.tiktok.com/@jsmentoring/photo/7448261980567145761) - ---- - -## Differences between cookie, local storage and session storage - -### Differences between cookie, local storage, and session storage - -Cookies are primarily used for server communication and have size limitations. Local storage provides persistent client-side storage with no expiration, while session storage stores data for the duration of a session. - -**Tags**: basic, cookie, local storage, session storage, differences - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448258461030173985](https://www.tiktok.com/@jsmentoring/photo/7448258461030173985) - ---- - -## How do you delete a cookie - -### How do you delete a cookie? - -To delete a cookie, set its expiration date to a past date using the `Set-Cookie` header or JavaScript's `document.cookie`. Ensure you match the path and domain attributes of the cookie. - -**Tags**: intermediate, cookie, delete, remove - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448236859966197025](https://www.tiktok.com/@jsmentoring/photo/7448236859966197025) - ---- - -## What is a post message - -### What is a post message? - -The `postMessage` API allows secure communication between a parent window and iframes or between different windows. It is commonly used for cross-origin communication in web applications. - -**Tags**: intermediate, postMessage, communication, iframe - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448205399074934049](https://www.tiktok.com/@jsmentoring/photo/7448205399074934049) - ---- - -## What are closures - -### What are closures? - -Closures in JavaScript occur when a function retains access to its lexical scope even after the function in which it was defined has completed execution. They enable powerful programming patterns like encapsulation and callbacks. - -**Tags**: intermediate, closures, JavaScript, scope - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7447942704148811041](https://www.tiktok.com/@jsmentoring/photo/7447942704148811041) - ---- - -## What are modules - -### What are modules? - -Modules are reusable blocks of code that can be imported and exported in JavaScript. They help organize and encapsulate functionality, promoting maintainable and modular codebases. - -**Tags**: intermediate, modules, JavaScript, ES6 - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7447936859029654816](https://www.tiktok.com/@jsmentoring/photo/7447936859029654816) - ---- - -## What are classes in ES6 - -### What are classes in ES6? - -Classes in ES6 provide a syntax for object-oriented programming in JavaScript. They include constructors, methods, and inheritance, making it easier to create and manage objects. - -**Tags**: advanced, classes, ES6, object-oriented programming - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7447909741977685280](https://www.tiktok.com/@jsmentoring/photo/7447909741977685280) - ---- - -## Why do you need modules - -### Why do you need modules? - -Modules help organize code into manageable pieces, improve reusability, and avoid global namespace pollution. They also make dependency management and code maintenance easier. - -**Tags**: intermediate, modules, benefits, organization - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7447895686626020640](https://www.tiktok.com/@jsmentoring/photo/7447895686626020640) - ---- - -## What is Hoisting - -### What is Hoisting? - -Hoisting in JavaScript refers to the process where variable and function declarations are moved to the top of their scope during compilation. This allows variables to be used before they are declared. - -**Tags**: basic, hoisting, JavaScript, scope - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7447882385946938656](https://www.tiktok.com/@jsmentoring/photo/7447882385946938656) - ---- - -## What is scope in javascript - -### What is scope in JavaScript?\n\nScope determines the accessibility of variables and functions in JavaScript. There are two types of scope: global and local. Modern JavaScript also includes block scope with \`let\` and \`const\`. - -**Tags**: basic, scope, JavaScript, variables - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7447877473280265505](https://www.tiktok.com/@jsmentoring/photo/7447877473280265505) - ---- - -## What is a service worker - -### What is a service worker? - -A service worker is a script that runs in the background, separate from the web page, enabling features like offline functionality, push notifications, and background sync. It acts as a proxy between the web app and the network. - -**Tags**: advanced, service worker, offline, caching - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7447871707219594529](https://www.tiktok.com/@jsmentoring/photo/7447871707219594529) - ---- - -## How do you manipulate with DOM element - -### How do you manipulate a DOM element? - -To manipulate DOM elements, use methods like `document.getElementById`, `document.querySelector`, and properties like `.innerHTML`, `.style`, or methods like `appendChild` and `removeChild` to modify elements dynamically. - -**Tags**: basic, DOM manipulation, JavaScript, elements - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7447865971974475041](https://www.tiktok.com/@jsmentoring/photo/7447865971974475041) - ---- - -## How do you reuse information across service worker restarts - -### How do you reuse information across service worker restarts? - -To reuse information across service worker restarts, store data in persistent storage mechanisms like IndexedDB or localStorage. This ensures data remains accessible even when the service worker restarts. - -**Tags**: advanced, service worker, persistence, IndexedDB - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7447841580880350497](https://www.tiktok.com/@jsmentoring/photo/7447841580880350497) - ---- - -## What is IndexedDB - -### What is IndexedDB? - -IndexedDB is a low-level API for storing large amounts of structured data, including files and blobs. It allows advanced querying and persistent storage, making it ideal for offline-capable applications. - -**Tags**: advanced, IndexedDB, database, storage - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7447814335323278624](https://www.tiktok.com/@jsmentoring/photo/7447814335323278624) - ---- - -## What is memoization - -### What is memoization? - -Memoization is an optimization technique where function results are cached based on input arguments, avoiding redundant computations and improving performance. - -**Tags**: intermediate, memoization, caching, performance - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7447658154155871520](https://www.tiktok.com/@jsmentoring/photo/7447658154155871520) - ---- - -## What is memoization - -### What is memoization? - -Memoization is an optimization technique where function results are cached based on input arguments, avoiding redundant computations and improving performance. - -**Tags**: intermediate, memoization, caching, performance - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7447658154155871520](https://www.tiktok.com/@jsmentoring/photo/7447658154155871520) - ---- - -## 5 Ways to Create Objects in JavaScript - -### 5 Ways to Create Objects in JavaScript - -In JavaScript, objects can be created in various ways. The five most common methods are: - -1. **Object Literal**: `const obj = {}` -2. **Object Constructor**: `const obj = new Object()` -3. **Object.create()**: `const obj = Object.create(null)` -4. **Class Syntax**: `class MyClass { constructor() {} }` -5. **Factory Functions**: `function createObject() { return {}}` - -**Tags**: basic, objects, creation, JavaScript - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7447557117344582944](https://www.tiktok.com/@jsmentoring/photo/7447557117344582944) - ---- - -## What is a Prototype Chain in JavaScript? - -### What is a Prototype Chain in JavaScript? - -The prototype chain is a fundamental concept in JavaScript's inheritance model. Every object in JavaScript has a prototype, which is another object. When you access a property of an object, JavaScript will first look for it in the object itself. If not found, it will look in the object's prototype, and then the prototype's prototype, and so on, until it reaches `null`. - -**Tags**: basic, prototype, inheritance, JavaScript - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7447534074211601697](https://www.tiktok.com/@jsmentoring/photo/7447534074211601697) - ---- - -## What is a higher order function - -### What is a higher order function? - -A higher order function is a function that either takes one or more functions as arguments, returns a function, or both. This allows for more abstract and reusable code. Examples of higher order functions include `map()`, `filter()`, and `reduce()` in JavaScript. - -**Tags**: intermediate, higher order functions, JavaScript - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7447469800642727200](https://www.tiktok.com/@jsmentoring/photo/7447469800642727200) - ---- - -## What is the currying function - -### What is the currying function? - -Currying is a technique in functional programming where a function that takes multiple arguments is transformed into a sequence of functions, each taking a single argument. This can make the code more modular and reusable. For example, `function add(a) { return function(b) { return a + b; } }`. - -**Tags**: advanced, currying, functions, JavaScript - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7447172210076208417](https://www.tiktok.com/@jsmentoring/photo/7447172210076208417) - ---- - -## How do you compare Object and Map - -### How do you compare Object and Map? - -Both `Object` and `Map` are key-value stores in JavaScript, but they have differences: - -1. **Key Types**: `Map` can use any data type as a key, while `Object` keys are always converted to strings. -2. **Iteration**: `Map` preserves the order of insertion, while `Object` does not guarantee order. -3. **Performance**: `Map` is generally more efficient for frequent additions and removals of key-value pairs. - -**Tags**: advanced, Object, Map, JavaScript - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7447122335863147808](https://www.tiktok.com/@jsmentoring/photo/7447122335863147808) - ---- - -## What is a pure function - -### What is a pure function? - -A pure function is a function that, given the same input, will always return the same output and does not have any side effects. It does not modify any external state or depend on external variables. This makes pure functions predictable and easier to test, as well as a key concept in functional programming. - -**Tags**: advanced, pure function, functional programming - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7447104096424725792](https://www.tiktok.com/@jsmentoring/photo/7447104096424725792) - ---- - -## What is a Prototype Chain in JavaScript? - -### What is a Prototype Chain in JavaScript? - -The prototype chain is a fundamental concept in JavaScript's inheritance model. Every object in JavaScript has a prototype, which is another object. When you access a property of an object, JavaScript will first look for it in the object itself. If not found, it will look in the object's prototype, and then the prototype's prototype, and so on, until it reaches `null`. - -**Tags**: basic, prototype, inheritance, JavaScript - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7446735468848270625](https://www.tiktok.com/@jsmentoring/photo/7446735468848270625) - ---- - -## What is the purpose of the let keyword - -### What is the purpose of the let keyword? - -The `let` keyword in JavaScript is used to declare block-scoped variables. Unlike `var`, which declares variables globally or within a function scope, `let` restricts the variable's scope to the block, statement, or expression in which it is used. This makes `let` more predictable and avoids issues with variable hoisting. - -**Tags**: basic, let keyword, JavaScript - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7446499450626772256](https://www.tiktok.com/@jsmentoring/photo/7446499450626772256) - ---- - -## Arrow func? - -### Arrow func? - -Arrow functions in JavaScript are a shorter syntax for writing functions. They are defined using `=>` and do not have their own `this` value, which means they inherit `this` from the surrounding context. This makes them useful in situations like event handling and callbacks where `this` behavior can be tricky. - -**Tags**: basic, arrow functions, JavaScript - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7446420047448247585](https://www.tiktok.com/@jsmentoring/photo/7446420047448247585) - ---- - -## What is the difference between let and var - -### What is the difference between let and var? - -The primary differences between `let` and `var` are their scoping rules and hoisting behavior: - -1. **Scope**: `let` is block-scoped, while `var` is function-scoped. -2. **Hoisting**: Both `let` and `var` are hoisted to the top of their scope, but `let` is not initialized until the code execution reaches it, leading to a Temporal Dead Zone (TDZ). - -**Tags**: basic, let, var, JavaScript - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7446417854699687200](https://www.tiktok.com/@jsmentoring/photo/7446417854699687200) - ---- - -## What is git bisect command? - -### What is git bisect command? - -The `git bisect` command is used to find the commit that introduced a bug by performing a binary search. You start by marking a known good commit and a known bad commit. Git then checks out the midpoint commit, and you test it. Based on the result, Git narrows down the range of commits until the problematic one is found. - -**Tags**: advanced, git, bisect, debugging - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7446337497484791073](https://www.tiktok.com/@jsmentoring/photo/7446337497484791073) - ---- - -## What are lambda expressions or arrow functions? - -### What are lambda expressions or arrow functions? - -Lambda expressions, also known as arrow functions, are a concise way to write functions in JavaScript. They use the `=>` syntax and do not have their own `this` value, meaning they inherit `this` from the surrounding context. They are often used for short, anonymous functions in callbacks or array methods. - -**Tags**: basic, lambda expressions, arrow functions, JavaScript - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7446080608989678880](https://www.tiktok.com/@jsmentoring/photo/7446080608989678880) - ---- - -## What is the difference between == and === operators? - -### What is the difference between == and === operators? - -In JavaScript, `==` is the equality operator that compares values after performing type coercion, meaning it converts the values to a common type before comparing them. On the other hand, `===` is the strict equality operator, which compares both the value and the type without any type conversion. - -**Tags**: basic, == vs ===, JavaScript - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7446055928723508512](https://www.tiktok.com/@jsmentoring/photo/7446055928723508512) - ---- - -## What is the purpose of the array splice method? - -### What is the purpose of the array splice method? - -The `splice()` method in JavaScript is used to modify an array by adding, removing, or replacing elements. It takes at least two arguments: the index at which to start changing the array, and the number of elements to remove. Additional arguments can be provided to add new elements. - -**Tags**: basic, splice, array, JavaScript - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7446035575565520160](https://www.tiktok.com/@jsmentoring/photo/7446035575565520160) - ---- - -## What is the difference between slice and splice? - -### What is the difference between slice and splice? - -`slice()` is used to extract a shallow copy of a portion of an array without modifying the original array, while `splice()` is used to change the contents of an array by removing or replacing elements. The key difference is that `slice()` does not alter the array, while `splice()` does. - -**Tags**: basic, slice, splice, JavaScript - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7446029933446565152](https://www.tiktok.com/@jsmentoring/photo/7446029933446565152) - ---- - -## 5 Ways to Create Objects in JavaScript? - -### 5 Ways to Create Objects in JavaScript - -In JavaScript, objects can be created in various ways. The five most common methods are: - -1. **Object Literal**: `const obj = {}` -2. **Object Constructor**: `const obj = new Object()` -3. **Object.create()**: `const obj = Object.create(null)` -4. **Class Syntax**: `class MyClass { constructor() {} }` -5. **Factory Functions**: `function createObject() { return {}}` - -**Tags**: basic, objects, creation, JavaScript - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7445448146685136161](https://www.tiktok.com/@jsmentoring/photo/7445448146685136161) - ---- - -## What is git rebase command? - -### What is git rebase command? - -The `git rebase` command is used to integrate changes from one branch into another. It works by moving or 'replaying' commits from one branch onto another, creating a linear history. This is different from `git merge`, which creates a merge commit. `git rebase` can be used to keep a cleaner, more linear commit history. - -**Tags**: basic, git, rebase, version control - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7444874869394771232](https://www.tiktok.com/@jsmentoring/photo/7444874869394771232) - ---- - -## What is git reflog command? - -### What is git reflog command? - -The `git reflog` command is used to show the history of changes to the reference logs, which track updates to the branches in a repository. This can be useful for recovering lost commits or understanding the changes made to a branch, especially after actions like rebasing or resetting. - -**Tags**: basic, git, reflog, version control - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7444873101717884192](https://www.tiktok.com/@jsmentoring/photo/7444873101717884192) - ---- - -## What is git revert command? - -### What is git revert command? - -The `git revert` command is used to create a new commit that undoes the changes made by a previous commit. Unlike `git reset`, which alters the commit history, `git revert` preserves the commit history and is often used in shared repositories to undo changes safely. - -**Tags**: basic, git, revert, version control - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7444867368431439136](https://www.tiktok.com/@jsmentoring/photo/7444867368431439136) - ---- - -## What is a storage event and its event handler? - -### What is a storage event and its event handler? - -A storage event is triggered when a change is made to the `localStorage` or `sessionStorage` in the browser, such as adding, removing, or modifying a key-value pair. The event handler for this event allows you to respond to these changes, providing a way to synchronize or react to storage updates across different windows or tabs. - -**Tags**: intermediate, storage event, event handler, web storage - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448353911720742177](https://www.tiktok.com/@jsmentoring/photo/7448353911720742177) - ---- - -## What are the methods available on session storage? - -### What are the methods available on session storage? - -`sessionStorage` provides methods to interact with the browser's session storage. Key methods include: - -- `setItem(key, value)`: Adds a key-value pair. -- `getItem(key)`: Retrieves the value for a given key. -- `removeItem(key)`: Removes the key-value pair. -- `clear()`: Clears all data stored in sessionStorage. - -**Tags**: basic, sessionStorage, web storage - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448368128825888032](https://www.tiktok.com/@jsmentoring/photo/7448368128825888032) - ---- - -## How do you access web storage? - -### How do you access web storage? - -Web storage is accessed using the `localStorage` or `sessionStorage` objects in JavaScript. For example, you can use `localStorage.setItem('key', 'value')` to store data, and `localStorage.getItem('key')` to retrieve it. Both `localStorage` and `sessionStorage` are part of the Window interface and provide a simple API for storing key-value pairs. - -**Tags**: basic, web storage, sessionStorage, localStorage - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448375078183587105](https://www.tiktok.com/@jsmentoring/photo/7448375078183587105) - ---- - -## What is the main difference between localStorage and sessionStorage? - -### What is the main difference between localStorage and sessionStorage? - -The main difference is the lifespan of the stored data: -- **`localStorage`** persists data even after the browser is closed, and the data remains available until explicitly removed. -- **`sessionStorage`** only stores data for the duration of the page session. Once the tab or window is closed, the data is cleared. - -**Tags**: basic, localStorage, sessionStorage, web storage - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448379916778851617](https://www.tiktok.com/@jsmentoring/photo/7448379916778851617) - ---- - -## Why do you need a Cookie? - -### Why do you need a Cookie? - -Cookies are used to store data on the client-side, typically for purposes like tracking user sessions, saving preferences, or authenticating users. They are sent to the server with every HTTP request, allowing the server to remember information about the client across requests and sessions. - -**Tags**: intermediate, cookies, web storage, HTTP - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448385477113171233](https://www.tiktok.com/@jsmentoring/photo/7448385477113171233) - ---- - -## What is a Cookie? - -### What is a Cookie? - -A cookie is a small piece of data stored by the browser on the client-side. It is sent to the server with every HTTP request and is used for various purposes such as maintaining user sessions, tracking user activity, and storing preferences. - -**Tags**: basic, cookies, web storage, HTTP - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448395347279236384](https://www.tiktok.com/@jsmentoring/photo/7448395347279236384) - ---- - -## What is web storage? - -### What is web storage? - -Web storage provides a way to store data in the browser. It includes two types: `localStorage` and `sessionStorage`. `localStorage` stores data persistently, while `sessionStorage` stores data for the duration of a session, which is cleared when the browser or tab is closed. - -**Tags**: basic, web storage, localStorage, sessionStorage - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448401312728878368](https://www.tiktok.com/@jsmentoring/photo/7448401312728878368) - ---- - -## What Are Server-Sent Events (SSE)? - -### What Are Server-Sent Events (SSE)? - -Server-Sent Events (SSE) is a technology that allows a server to push updates to the client over a single HTTP connection. This is typically used for real-time applications such as notifications, live scores, or chat apps, where the server sends updates to the client automatically. - -**Tags**: intermediate, SSE, real-time communication, web technologies - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448434434774142240](https://www.tiktok.com/@jsmentoring/photo/7448434434774142240) - ---- - -## What Is a Callback Hell? - -### What Is a Callback Hell? - -Callback hell, also known as 'Pyramid of Doom,' refers to a situation where multiple nested callback functions in JavaScript make the code hard to read and maintain. It usually occurs in asynchronous code and can be mitigated by using Promises or async/await. - -**Tags**: intermediate, callback hell, asynchronous, JavaScript - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448549870673169696](https://www.tiktok.com/@jsmentoring/photo/7448549870673169696) - ---- - -## Importance of Callbacks in Javascript? - -### Importance of Callbacks in Javascript? - -Callbacks in JavaScript are functions passed as arguments to other functions, enabling asynchronous programming. They allow for non-blocking code execution, making it possible to handle events like user input or network requests without freezing the application. - -**Tags**: basic, callbacks, JavaScript, asynchronous programming - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448582345390591265](https://www.tiktok.com/@jsmentoring/photo/7448582345390591265) - ---- - -## What is a callback function in javascript? - -### What is a callback function in javascript? - -A callback function is a function passed into another function as an argument and executed after the completion of a task. Callbacks are commonly used in asynchronous programming, such as handling events or making HTTP requests. - -**Tags**: basic, callback function, JavaScript, asynchronous programming - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448614606278282529](https://www.tiktok.com/@jsmentoring/photo/7448614606278282529) - ---- - -## What Are the Three States of a Promise? - -### What Are the Three States of a Promise? - -A Promise in JavaScript can be in one of three states: -- **Pending**: The initial state, neither fulfilled nor rejected. -- **Fulfilled**: The operation completed successfully. -- **Rejected**: The operation failed. - -**Tags**: intermediate, Promise, JavaScript, asynchronous programming - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448655823150058785](https://www.tiktok.com/@jsmentoring/photo/7448655823150058785) - ---- - -## Why do you need a promise? - -### Why do you need a promise? - -Promises are used to handle asynchronous operations in JavaScript. They provide a cleaner way to handle asynchronous code, avoiding callback hell by chaining `.then()` and `.catch()` methods to handle success and failure, respectively. - -**Tags**: intermediate, Promise, asynchronous programming - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448671709634235681](https://www.tiktok.com/@jsmentoring/photo/7448671709634235681) - ---- - -## What is a promise? - -### What is a promise? - -A promise is an object in JavaScript that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It allows you to attach `.then()` and `.catch()` methods to handle the results or errors of the asynchronous task. - -**Tags**: intermediate, Promise, JavaScript, asynchronous programming - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448715825642540320](https://www.tiktok.com/@jsmentoring/photo/7448715825642540320) - ---- - -## What are the restrictions of web workers on DOM? - -### What are the restrictions of web workers on DOM? - -Web workers run in a separate thread and cannot directly access or modify the DOM. They are designed for heavy computations and background tasks. To interact with the DOM, workers communicate with the main thread using message passing via `postMessage()`. - -**Tags**: advanced, web workers, DOM, JavaScript - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448725365574372641](https://www.tiktok.com/@jsmentoring/photo/7448725365574372641) - ---- - -## Give an example of a web worker? - -### Give an example of a web worker? - -A simple web worker example: - -```javascript -const worker = new Worker('worker.js'); -worker.postMessage('Hello'); -worker.onmessage = function(event) { - console.log('Received from worker:', event.data); -}; -``` -In the `worker.js` file, you would handle the message with `onmessage` and use `postMessage` to send a response back. - -**Tags**: intermediate, web workers, JavaScript - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448739040213437729](https://www.tiktok.com/@jsmentoring/photo/7448739040213437729) - ---- - -## How do you check web storage browser support? - -### How do you check web storage browser support? - -To check if a browser supports web storage, you can check if `localStorage` or `sessionStorage` is available: - -```javascript -if (typeof(Storage) !== 'undefined') { - // Web storage is supported -} else { - // Web storage is not supported -} -``` - -**Tags**: basic, web storage, browser support, JavaScript - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448750198848769313](https://www.tiktok.com/@jsmentoring/photo/7448750198848769313) - ---- - -## Why do you need web storage? - -### Why do you need web storage? - -Web storage allows you to store data on the client side, providing faster access to information without requiring a round-trip to the server. It helps with tasks like saving user preferences, session information, and caching data for offline use. - -**Tags**: basic, web storage, JavaScript - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448934582965046561](https://www.tiktok.com/@jsmentoring/photo/7448934582965046561) - ---- - -## How Do You Receive Server-Sent Event Notifications? - -### How Do You Receive Server-Sent Event Notifications? - -To receive Server-Sent Event (SSE) notifications, you need to create an `EventSource` object in JavaScript, which listens for events sent by the server. For example: - -```javascript -const eventSource = new EventSource('https://example.com/sse'); -eventSource.onmessage = function(event) { - console.log('New message:', event.data); -}; -``` - -**Tags**: intermediate, Server-Sent Events, notifications, web technologies - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7448989685881376033](https://www.tiktok.com/@jsmentoring/photo/7448989685881376033) - ---- - -## What Is a Callback in Callback? - -### What Is a Callback in Callback? - -A 'callback in callback' refers to a situation where a function is passed as a parameter to another function, and that function in turn calls another function (callback) within it. This can lead to nested callbacks, which may result in 'callback hell' if not managed properly. - -**Tags**: intermediate, callbacks, asynchronous programming, JavaScript - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7449011382449720608](https://www.tiktok.com/@jsmentoring/photo/7449011382449720608) - ---- - -## What Is Promise Chaining in JavaScript? - -### What Is Promise Chaining in JavaScript? - -Promise chaining allows you to chain multiple `.then()` calls to handle sequential asynchronous operations. Each `.then()` returns a new promise, enabling the next step in the chain to execute after the previous one is fulfilled. - -```javascript -fetchData() - .then(result => processData(result)) - .then(processedData => displayData(processedData)) - .catch(error => console.error(error)); -``` - -**Tags**: intermediate, Promises, JavaScript, asynchronous programming - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7449040289345457441](https://www.tiktok.com/@jsmentoring/photo/7449040289345457441) - ---- - -## What Are the Main Rules of Promise in JavaScript? - -### What Are the Main Rules of Promise in JavaScript? - -The main rules of Promises in JavaScript are: -1. A promise can be in one of three states: pending, fulfilled, or rejected. -2. A promise can only transition from pending to fulfilled or rejected, and cannot change back. -3. You can attach `.then()` to handle success and `.catch()` for errors. - -**Tags**: intermediate, Promises, JavaScript - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7449057432086580513](https://www.tiktok.com/@jsmentoring/photo/7449057432086580513) - ---- - -## What Are the Events Available for Server-Sent Events? - -### What Are the Events Available for Server-Sent Events? - -Server-Sent Events (SSE) support several event types, including: -- `message`: The default event for incoming data. -- `open`: Fired when the connection to the server is established. -- `error`: Fired when there is an error with the connection. - -**Tags**: intermediate, Server-Sent Events, web technologies - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7449065499603881248](https://www.tiktok.com/@jsmentoring/photo/7449065499603881248) - ---- - -## How Do You Check Browser Support for Server-Sent Events? - -### How Do You Check Browser Support for Server-Sent Events? - -To check if the browser supports Server-Sent Events, you can check for the `EventSource` object: - -```javascript -if (typeof(EventSource) !== 'undefined') { - // SSE is supported -} else { - // SSE is not supported -} -``` - -**Tags**: basic, Server-Sent Events, browser support - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7449149383142018336](https://www.tiktok.com/@jsmentoring/photo/7449149383142018336) - ---- - -## What Is `Promise.all` in JavaScript? - -### What Is `Promise.all` in JavaScript? - -`Promise.all` is a method that accepts an array of promises and returns a single promise that resolves when all the promises in the array are resolved. If any of the promises reject, the returned promise will reject immediately. - -```javascript -Promise.all([promise1, promise2, promise3]) - .then(results => console.log(results)) - .catch(error => console.error(error)); -``` - -**Tags**: intermediate, Promises, JavaScript, asynchronous programming - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7449321820743847200](https://www.tiktok.com/@jsmentoring/photo/7449321820743847200) - ---- - -## What Is the Purpose of the `race` Method in Promises? - -### What Is the Purpose of the `race` Method in Promises? - -The `Promise.race()` method returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects. It is useful when you need to wait for the first promise to settle. - -```javascript -Promise.race([promise1, promise2, promise3]) - .then(result => console.log(result)) - .catch(error => console.error(error)); -``` - -**Tags**: intermediate, Promises, JavaScript, asynchronous programming - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7449363438461144353](https://www.tiktok.com/@jsmentoring/photo/7449363438461144353) - ---- - -## What Is Strict Mode in JavaScript? - -### What Is Strict Mode in JavaScript? - -Strict mode is a way to opt in to a restricted version of JavaScript. It helps catch common coding mistakes and prevents the use of certain features that can lead to bugs, such as using undeclared variables. - -```javascript -'use strict'; -var x = 3.14; // Error in strict mode: assignment to undeclared variable -``` - -**Tags**: intermediate, JavaScript, strict mode - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7449392707455175968](https://www.tiktok.com/@jsmentoring/photo/7449392707455175968) - ---- - -## What Is the Purpose of Double Exclamation in JavaScript? - -### What Is the Purpose of Double Exclamation in JavaScript? - -Double exclamation (`!!`) is used to convert a value into a boolean. The first exclamation negates the value, and the second negates it again, resulting in a boolean representation of the value. - -```javascript -console.log(!!'string'); // true -console.log(!!0); // false -``` - -**Tags**: basic, JavaScript, type coercion - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7449429710985022753](https://www.tiktok.com/@jsmentoring/photo/7449429710985022753) - ---- - -## How Do You Declare Strict Mode in JavaScript? - -### How Do You Declare Strict Mode in JavaScript? - -To declare strict mode in JavaScript, simply add `'use strict';` at the beginning of a script or a function. - -```javascript -'use strict'; -// Code here will be executed in strict mode -``` - -**Tags**: basic, JavaScript, strict mode - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7449490448533507361](https://www.tiktok.com/@jsmentoring/photo/7449490448533507361) - ---- - -## How Do You Detect Caps Lock Key Turned On or Not? - -### How Do You Detect Caps Lock Key Turned On or Not? - -To detect whether Caps Lock is on, you can use the `keydown` or `keypress` event and check the `event.getModifierState('CapsLock')` property. - -```javascript -document.addEventListener('keydown', function(event) { - if (event.getModifierState('CapsLock')) { - console.log('Caps Lock is on'); - } -}); -``` - -**Tags**: intermediate, JavaScript, event handling, keyboard events - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7449671849920761120](https://www.tiktok.com/@jsmentoring/photo/7449671849920761120) - ---- - -## How Do You Access History in JavaScript? - -### How Do You Access History in JavaScript? - -You can access the browser history using the `window.history` object. This allows you to manipulate the session history (navigate, go back, forward, etc.). - -```javascript -window.history.back(); // Go back to the previous page -window.history.forward(); // Go forward in history -``` - -**Tags**: basic, JavaScript, history API - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7449732288268487969](https://www.tiktok.com/@jsmentoring/photo/7449732288268487969) - ---- - -## What Is the Difference Between `window` and `document` in JavaScript? - -### What Is the Difference Between `window` and `document` in JavaScript? - -`window` represents the browser window and is the global object in the browser's JavaScript environment. `document`, on the other hand, represents the HTML document loaded in the browser, allowing interaction with the DOM. - -```javascript -console.log(window); // Browser window -console.log(document); // HTML document -``` - -**Tags**: basic, JavaScript, DOM - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7449755076182215968](https://www.tiktok.com/@jsmentoring/photo/7449755076182215968) - ---- - -## What Is the Purpose of Double Exclamation in JavaScript? - -### What Is the Purpose of Double Exclamation in JavaScript? - -Double exclamation (`!!`) is used to convert a value to a boolean. The first negation converts it to a boolean, and the second negation reverts it to the correct boolean value. - -```javascript -console.log(!!'text'); // true -console.log(!!null); // false -``` - -**Tags**: basic, JavaScript, type coercion - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7449813378895203617](https://www.tiktok.com/@jsmentoring/photo/7449813378895203617) - ---- - -## What Is `eval` in JavaScript? - -### What Is `eval` in JavaScript? - -`eval()` is a JavaScript function that evaluates a string of JavaScript code. It is generally discouraged due to security risks such as code injection vulnerabilities. - -```javascript -eval('console.log("Hello, World!")'); // Logs 'Hello, World!' -``` - -**Tags**: intermediate, JavaScript, security - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7449833381975559446](https://www.tiktok.com/@jsmentoring/photo/7449833381975559446) - ---- - -## What Is the `null` Value in JavaScript? - -### What Is the `null` Value in JavaScript? - -`null` is a primitive value that represents the intentional absence of any object value. It is used to indicate that a variable is empty or uninitialized. - -```javascript -let x = null; -console.log(x); // null -``` - -**Tags**: basic, JavaScript, data types - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7449876086793489696](https://www.tiktok.com/@jsmentoring/photo/7449876086793489696) - ---- - -## What Is the `undefined` Property in JavaScript? - -### What Is the `undefined` Property in JavaScript? - -`undefined` is a primitive value that is automatically assigned to variables that are declared but not initialized. It represents the absence of a defined value. - -```javascript -let x; -console.log(x); // undefined -``` - -**Tags**: basic, JavaScript, data types - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7450179747931278624](https://www.tiktok.com/@jsmentoring/photo/7450179747931278624) - ---- - -## What Is the Purpose of the `delete` Operator in JavaScript? - -### What Is the Purpose of the `delete` Operator in JavaScript? - -The `delete` operator is used to remove a property from an object or an element from an array. - -```javascript -let obj = { name: 'John', age: 30 }; -delete obj.age; -console.log(obj); // { name: 'John' } -``` - -**Tags**: intermediate, JavaScript, operators - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7450258222222560544](https://www.tiktok.com/@jsmentoring/photo/7450258222222560544) - ---- - -## What Is the `typeof` Operator in JavaScript? - -### What Is the `typeof` Operator in JavaScript? - -The `typeof` operator returns a string indicating the type of the unevaluated operand. It is commonly used to check the type of variables or expressions. - -```javascript -console.log(typeof 'Hello'); // string -console.log(typeof 123); // number -``` - -**Tags**: basic, JavaScript, operators - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7450568773712497953](https://www.tiktok.com/@jsmentoring/photo/7450568773712497953) - ---- - -## What Is `isNaN` in JavaScript? - -### What Is `isNaN` in JavaScript? - -`isNaN()` is a function that checks whether a value is NaN (Not-a-Number). It returns `true` if the value is NaN, and `false` otherwise. - -```javascript -console.log(isNaN(123)); // false -console.log(isNaN('Hello')); // true -``` - -**Tags**: basic, JavaScript, type checking - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7450774214459673888](https://www.tiktok.com/@jsmentoring/photo/7450774214459673888) - ---- - -## What are the differences between undeclared and undefined variables - -### What are the differences between undeclared and undefined variables? - -An undeclared variable is one that has not been declared using `var`, `let`, or `const`. An undefined variable is one that has been declared but not assigned a value. - -**Tags**: basic, JavaScript, variables - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7450925531370884385](https://www.tiktok.com/@jsmentoring/photo/7450925531370884385) - ---- - -## What are global variables - -### What are global variables? - -Global variables are variables that are declared outside of any function and are accessible from any part of the code. - -**Tags**: basic, JavaScript, variables - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7450838618257575201](https://www.tiktok.com/@jsmentoring/photo/7450838618257575201) - ---- - -## What are the problems with global variables - -### What are the problems with global variables? - -Global variables can cause issues like name collisions, difficulty in debugging, and unintended side effects. It's recommended to limit the use of global variables. - -**Tags**: intermediate, JavaScript, best practices - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7451163740982070561](https://www.tiktok.com/@jsmentoring/photo/7451163740982070561) - ---- - -## What is NaN property - -### What is NaN property? - -`NaN` (Not-a-Number) is a special value in JavaScript that represents an invalid or undefined numerical result, such as the result of dividing 0 by 0. - -**Tags**: basic, JavaScript, type checking - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7451255958266760480](https://www.tiktok.com/@jsmentoring/photo/7451255958266760480) - ---- - -## What is the purpose of isFinite function - -### What is the purpose of isFinite function? - -`isFinite()` is used to check if a value is a finite number. It returns `true` if the value is a finite number, and `false` otherwise. - -**Tags**: intermediate, JavaScript, type checking - - - ---- - -## What is an event flow - -### What is an event flow? - -Event flow in JavaScript refers to the order in which events are propagated through the DOM. It consists of three phases: capturing phase, target phase, and bubbling phase. - -**Tags**: intermediate, JavaScript, events - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7451321489682468128](https://www.tiktok.com/@jsmentoring/photo/7451321489682468128) - ---- - -## What is event bubbling - -### What is event bubbling? - -Event bubbling is the process where an event triggered on a child element is propagated up to its parent elements. It is the default behavior for most events in JavaScript. - -**Tags**: basic, JavaScript, events - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7451597511862603040](https://www.tiktok.com/@jsmentoring/photo/7451597511862603040) - ---- - -## [Can I add getters and setters using defineProperty method](#can-i-add-getters-and-setters-using-defineproperty-method) - -### Can I add getters and setters using defineProperty method? - -Yes, you can add getters and setters using `Object.defineProperty()`. This allows you to define custom getter and setter methods for specific properties. - -Example: - -```javascript -const person = {}; -Object.defineProperty(person, 'name', { - get() { return this._name; }, - set(value) { this._name = value.toUpperCase(); } -}); -person.name = 'John'; -console.log(person.name); // 'JOHN' -``` - -**Tags**: basic, JavaScript, objects - - - ---- - -## [Can I avoid using postMessages completely](#can-i-avoid-using-postmessages-completely) - -### Can I avoid using postMessages completely? - -While `postMessage` is a useful API for cross-origin communication, alternatives like `localStorage`, `cookies`, or server-side messaging (e.g., WebSockets) can be used depending on the use case. Avoiding `postMessage` may increase security in certain scenarios. - -**Tags**: advanced, JavaScript, Security - - - ---- - -## [Can I redeclare let and const variables](#can-i-redeclare-let-and-const-variables) - -### Can I redeclare `let` and `const` variables? - -No, you cannot redeclare `let` and `const` variables in the same scope. The `let` and `const` declarations are block-scoped, and attempting to redeclare them will result in a syntax error. - -Example: - -```javascript -let x = 10; -let x = 20; // Error: Cannot redeclare block-scoped variable 'x' -``` - -**Tags**: intermediate, JavaScript, Variables - - - ---- - -## [Can I use reserved words as identifiers](#can-i-use-reserved-words-as-identifiers) - -### Can I use reserved words as identifiers? - -No, you cannot use reserved words (such as `let`, `class`, `function`, etc.) as identifiers (variable names, function names, etc.) in JavaScript. - -Example: - -```javascript -let let = 5; // SyntaxError: Unexpected token 'let' -``` - -**Tags**: basic, JavaScript, syntax - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7457212868161850657](https://www.tiktok.com/@jsmentoring/photo/7457212868161850657) - ---- - -## [Can we define properties for functions](#can-we-define-properties-for-functions) - -### Can we define properties for functions? - -Yes, functions in JavaScript are objects, so you can define properties for them. - -```javascript -function myFunc() {} -myFunc.property = 'value'; -console.log(myFunc.property); // 'value' -``` - -**Tags**: basic, JavaScript, functions - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7456170349391023393](https://www.tiktok.com/@jsmentoring/photo/7456170349391023393) - ---- - -## [Can you apply chaining on conditional operator](#can-you-apply-chaining-on-conditional-operator) - -### Can you apply chaining on conditional operator? - -Yes, you can chain multiple conditional operators together to evaluate multiple conditions in a single expression. - -Example: - -```javascript -const result = (age >= 18) ? 'Adult' : (age >= 13) ? 'Teen' : 'Child'; -``` - -**Tags**: basic, JavaScript, operators - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7458016862446570785](https://www.tiktok.com/@jsmentoring/photo/7458016862446570785) - ---- - -## [Can you give an example of when you really need a semicolon](#can-you-give-an-example-of-when-you-really-need-a-semicolon) - -### Can you give an example of when you really need a semicolon? - -Semicolons are generally optional in JavaScript, but there are situations where they are required. For example, when returning an object from a function on the same line. - -Example: - -```javascript -return { key: 'value' }; // Requires semicolon -``` - -**Tags**: basic, JavaScript, syntax - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7457679188732939553](https://www.tiktok.com/@jsmentoring/photo/7457679188732939553) - ---- - -## [Can you write a random integers function to print integers within a range](#can-you-write-a-random-integers-function-to-print-integers-within-a-range) - -### Can you write a random integers function to print integers within a range? - -You can create a function that generates random integers within a specified range. - -Example: - -```javascript -function getRandomInt(min, max) { - return Math.floor(Math.random() * (max - min + 1)) + min; -} -console.log(getRandomInt(1, 100)); // Generates a random integer between 1 and 100 -``` - -**Tags**: basic, JavaScript, math - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7456920292397518112](https://www.tiktok.com/@jsmentoring/photo/7456920292397518112) - ---- - -## [Check for Anagrams](#check-for-anagrams) - -### Check for Anagrams - -An anagram is a word or phrase formed by rearranging the letters of another, using all the original letters exactly once. - -#### Algorithm: -1. Remove any non-alphanumeric characters and convert both strings to lowercase. -2. Check if the lengths of the two strings are the same. If not, they cannot be anagrams. -3. Count the frequency of each character in the first string. -4. Compare the character counts with the second string by decrementing the counts. If any count becomes negative or mismatches, the strings are not anagrams. - -#### Example: -```javascript -function areAnagrams(str1, str2) { - // Normalize the strings: remove non-alphanumeric characters and convert to lowercase - const normalize = str => str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase(); - const s1 = normalize(str1); - const s2 = normalize(str2); - - if (s1.length !== s2.length) { - return false; // Different lengths mean they can't be anagrams - } - - const charCount = {}; - - // Count characters in the first string - for (const char of s1) { - charCount[char] = (charCount[char] || 0) + 1; - } - - // Compare characters with the second string - for (const char of s2) { - if (!charCount[char]) { - return false; // Character mismatch - } - charCount[char]--; - } - - return true; // Strings are anagrams -} - -// Example usage -console.log(areAnagrams("listen", "silent")); // Output: true -console.log(areAnagrams("hello", "world")); // Output: false -``` - -This method has a time complexity of O(n), where n is the length of the strings. - -**Tags**: intermediate, JavaScript, Strings, Algorithm - -**URL**: [https://www.tiktok.com/@jsmentoring/video/7458386392272473377](https://www.tiktok.com/@jsmentoring/video/7458386392272473377) - ---- - -## [Check if a Number is Perfect](#check-if-a-number-is-perfect) - -### Check if a Number is Perfect - -A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding the number itself). - -#### Algorithm: -1. Initialize a variable to store the sum of divisors. -2. Iterate from 1 to half of the number. -3. For each divisor, add it to the sum. -4. If the sum equals the original number, return `true`, otherwise return `false`. - -#### Example: -```javascript -function isPerfectNumber(num) { - let sum = 0; - for (let i = 1; i <= num / 2; i++) { - if (num % i === 0) sum += i; - } - return sum === num; -} - -// Example usage -console.log(isPerfectNumber(28)); // Output: true -console.log(isPerfectNumber(6)); // Output: true -console.log(isPerfectNumber(10)); // Output: false -``` - -This method has a time complexity of O(n), where n is the number being checked. - -**Tags**: intermediate, JavaScript, Math, Algorithm - - - ---- - -## [Check if a Number is Prime](#check-if-a-number-is-prime) - -### Check if a Number is Prime - -To check if a number is prime, verify that it is greater than 1 and divisible only by 1 and itself. - -#### Algorithm: -1. Check if the number is less than or equal to 1; if so, return false. -2. Iterate through numbers from 2 to the square root of the number. -3. If the number is divisible by any of these, return false. -4. If no divisors are found, return true. - -#### Example: -```javascript -function isPrime(num) { - if (num <= 1) { - return false; - } - - for (let i = 2; i <= Math.sqrt(num); i++) { - if (num % i === 0) { - return false; - } - } - - return true; -} - -// Example usage -console.log(isPrime(7)); // Output: true -console.log(isPrime(10)); // Output: false -``` - -This method has a time complexity of O(sqrt(n)), where n is the number being checked. - -**Tags**: basic, JavaScript, Numbers, Algorithm - - - ---- - -## [Check if a String is a Palindrome](#check-if-a-string-is-a-palindrome) - -### Check if a String is a Palindrome - -A palindrome is a word, phrase, or sequence that reads the same backward as forward. - -#### Algorithm: -1. Remove all non-alphanumeric characters and convert the string to lowercase to handle case sensitivity. -2. Use two pointers: one starting at the beginning and the other at the end of the string. -3. Compare characters at the two pointers. If they differ, the string is not a palindrome. -4. Move the pointers closer to the center and repeat the comparison. -5. If all characters match, the string is a palindrome. - -#### Example: -```javascript -function isPalindrome(str) { - // Normalize the string: remove non-alphanumeric characters and convert to lowercase - const cleanStr = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase(); - - let left = 0; - let right = cleanStr.length - 1; - - while (left < right) { - if (cleanStr[left] !== cleanStr[right]) { - return false; // Not a palindrome - } - left++; - right--; - } - - return true; // It's a palindrome -} - -// Example usage -console.log(isPalindrome("A man, a plan, a canal, Panama")); // Output: true -console.log(isPalindrome("hello")); // Output: false -``` - -This method has a time complexity of O(n), where n is the length of the string. - -**Tags**: basic, JavaScript, Strings, Algorithm - -**URL**: [https://www.tiktok.com/@jsmentoring/video/7458413373315681569](https://www.tiktok.com/@jsmentoring/video/7458413373315681569) - ---- - -## [Check if a String is a Palindromic Permutation](#check-if-a-string-is-palindromic-permutation) - -### Check if a String is a Palindromic Permutation - -To check if a string is a permutation of a palindrome, the string's characters must appear in pairs (except possibly one character for odd-length strings). - -#### Algorithm: -1. Count the frequency of each character in the string. -2. Check how many characters have an odd frequency. -3. If more than one character has an odd frequency, return false; otherwise, return true. - -#### Example: -```javascript -function isPalindromicPermutation(str) { - const freqMap = {}; - - for (const char of str) { - freqMap[char] = (freqMap[char] || 0) + 1; - } - - let oddCount = 0; - for (const count of Object.values(freqMap)) { - if (count % 2 !== 0) { - oddCount += 1; - } - } - - return oddCount <= 1; -} - -// Example usage -console.log(isPalindromicPermutation("civic")); // Output: true -console.log(isPalindromicPermutation("ivicc")); // Output: true -console.log(isPalindromicPermutation("hello")); // Output: false -``` - -This method has a time complexity of O(n), where n is the length of the string. - -**Tags**: intermediate, JavaScript, Strings, Algorithm - - - ---- - -## [Check if a String is Rotated](#check-if-a-string-is-rotated) - -### Check if a String is Rotated - -To check if one string is a rotation of another, concatenate the first string with itself and check if the second string is a substring of the result. - -#### Algorithm: -1. Concatenate the first string with itself. -2. Check if the second string is a substring of the concatenated string. -3. If it is, return `true`; otherwise, return `false`. - -#### Example: -```javascript -function isRotated(str1, str2) { - if (str1.length !== str2.length) return false; - return (str1 + str1).includes(str2); -} - -// Example usage -console.log(isRotated('abcde', 'cdeab')); // Output: true -console.log(isRotated('abcde', 'abced')); // Output: false -``` - -This method has a time complexity of O(n), where n is the length of the strings. - -**Tags**: intermediate, JavaScript, Strings, Algorithm - - - ---- - -## [Check if an Array is Sorted](#check-if-an-array-is-sorted) - -### Check if an Array is Sorted - -To check if an array is sorted, compare each element with the next one to ensure it is in the correct order. - -#### Algorithm: -1. Iterate through the array and compare each element with the next. -2. If any element is greater than the next one, the array is not sorted. -3. If no such element is found, return true; otherwise, return false. - -#### Example: -```javascript -function isArraySorted(arr) { - for (let i = 0; i < arr.length - 1; i++) { - if (arr[i] > arr[i + 1]) { - return false; - } - } - return true; -} - -// Example usage -console.log(isArraySorted([1, 2, 3, 4])); // Output: true -console.log(isArraySorted([1, 3, 2, 4])); // Output: false -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: basic, JavaScript, Arrays, Algorithm - - - ---- - -## [Check if Two Strings Are Palindromes of Each Other](#check-if-two-strings-are-palindromes-of-each-other) - -### Check if Two Strings Are Palindromes of Each Other - -To check if two strings are palindromes of each other, reverse one string and compare it with the other string. - -#### Algorithm: -1. Reverse one of the strings. -2. Compare the reversed string with the other string. -3. If they are equal, return true, indicating that they are palindromes of each other. - -#### Example: -```javascript -function arePalindromes(str1, str2) { - return str1 === str2.split('').reverse().join(''); -} - -// Example usage -console.log(arePalindromes('abcd', 'dcba')); // Output: true -console.log(arePalindromes('abc', 'def')); // Output: false -``` - -This method has a time complexity of O(n), where n is the length of the string. - -**Tags**: intermediate, JavaScript, Strings, Algorithm - - - ---- - -## [Count the Number of 1 Bits in a Number](#count-the-number-of-1-bits-in-a-number) - -### Count the Number of 1 Bits in a Number - -To count the number of 1 bits in a number, use bitwise operations. The idea is to repeatedly clear the least significant 1 bit and count how many times this operation is performed. - -#### Algorithm: -1. Initialize a counter variable to 0. -2. Repeatedly perform the operation `n & (n - 1)` to clear the least significant 1 bit of `n`. -3. Increment the counter for each operation. -4. Return the counter. - -#### Example: -```javascript -function hammingWeight(n) { - let count = 0; - while (n !== 0) { - n &= (n - 1); - count++; - } - return count; -} - -// Example usage -console.log(hammingWeight(11)); // Output: 3 (binary: 1011) -console.log(hammingWeight(128)); // Output: 1 (binary: 10000000) -``` - -This method has a time complexity of O(k), where k is the number of 1 bits in the number. - -**Tags**: basic, JavaScript, Bit Manipulation, Algorithm - - - ---- - -## [Count the Occurrences of an Element in an Array](#count-the-occurences-of-an-element-in-an-array) - -### Count the Occurrences of an Element in an Array - -To count the occurrences of an element in an array, iterate through the array and keep track of how many times the element appears. - -#### Algorithm: -1. Initialize a counter variable to 0. -2. Iterate through the array and check if each element matches the target element. -3. Increment the counter for each match. -4. Return the counter. - -#### Example: -```javascript -function countOccurrences(arr, elem) { - let count = 0; - - for (const item of arr) { - if (item === elem) { - count++; - } - } - - return count; -} - -// Example usage -console.log(countOccurrences([1, 2, 3, 2, 4], 2)); // Output: 2 -console.log(countOccurrences(["apple", "banana", "apple"], "apple")); // Output: 2 -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: basic, JavaScript, Arrays, Algorithm - - - ---- - -## [Count Vowels in a String](#count-vowels-in-a-string) - -### Count Vowels in a String - -To count the vowels in a string, iterate through the string and check if each character is a vowel. - -#### Algorithm: -1. Normalize the string by converting it to lowercase to handle case insensitivity. -2. Define a set or array containing all vowel characters (`a, e, i, o, u`). -3. Iterate through the string and count characters that match any vowel. -4. Return the total count of vowels. - -#### Example: -```javascript -function countVowels(str) { - const vowels = new Set(['a', 'e', 'i', 'o', 'u']); - let count = 0; - - for (const char of str.toLowerCase()) { - if (vowels.has(char)) { - count++; - } - } - - return count; -} - -// Example usage -console.log(countVowels("Hello World")); // Output: 3 -console.log(countVowels("JavaScript is awesome!")); // Output: 8 -``` - -This method has a time complexity of O(n), where n is the length of the string. - -**Tags**: basic, JavaScript, Strings, Algorithm - - - ---- - -## [Count Words in a String](#count-words-in-a-string) - -### Count Words in a String - -To count the number of words in a string, split the string by spaces and count the resulting elements. - -#### Algorithm: -1. Split the string by spaces into an array of words. -2. Filter out any empty strings from the array. -3. Return the length of the array. - -#### Example: -```javascript -function countWords(str) { - return str.split(' ').filter(word => word !== '').length; -} - -// Example usage -console.log(countWords('Hello world, how are you?')); // Output: 5 -console.log(countWords(' This is a test ')); // Output: 4 -``` - -This method has a time complexity of O(n), where n is the length of the string. - -**Tags**: basic, JavaScript, Strings, Algorithm - - - ---- - -## [Do all objects have prototypes](#do-all-objects-have-prototypes) - -### Do all objects have prototypes? - -Yes, in JavaScript, all objects inherit from `Object.prototype` by default, which means they have access to its methods and properties. However, objects created with `Object.create(null)` do not have a prototype. - -Example: - -```javascript -let obj = {}; -console.log(Object.getPrototypeOf(obj)); // Output: [object Object] -``` - -**Tags**: intermediate, JavaScript, Objects - - - ---- - -## [Does JavaScript supports namespace](#does-javascript-supports-namespace) - -### Does JavaScript support namespaces? - -JavaScript does not have a built-in `namespace` feature like some other programming languages. However, you can create a namespace-like structure using objects or modules. - -Example using objects as namespaces: - -```javascript -const MyNamespace = { - myFunction: function() { console.log('Hello!'); }, - myVariable: 42 -}; -MyNamespace.myFunction(); // 'Hello!' -``` - -**Tags**: intermediate, JavaScript, namespaces - - - ---- - -## [Does javascript uses mixins](#does-javascript-uses-mixins) - -### Does JavaScript use mixins? - -Yes, JavaScript can implement mixins, which are objects that provide methods to other objects. A mixin is a way to reuse functionality across different objects without using inheritance. - -Example: - -```javascript -let mixin = { - greet() { console.log('Hello!'); } -}; - -let obj = Object.assign({}, mixin); -obj.greet(); // Output: 'Hello!' -``` - -**Tags**: advanced, JavaScript, Object-Oriented Programming - - - ---- - -## [Does the const variable make the value immutable](#does-the-const-variable-make-the-value-immutable) - -### Does the `const` variable make the value immutable? - -No, `const` only ensures that the variable identifier cannot be reassigned. It does not make the value immutable. If the value is an object or array, its properties or elements can still be modified. - -Example: - -```javascript -const arr = [1, 2, 3]; -arr.push(4); // Works fine -arr = [4, 5, 6]; // Error: Assignment to constant variable -``` - -**Tags**: intermediate, JavaScript, Variables - - - ---- - -## [Find All Pairs in an Array with a Given Sum](#find-all-pairs-in-an-array-with-a-given-sum) - -### Find All Pairs in an Array with a Given Sum - -To find all pairs that sum to a specific target, use a hash set to track the complements of each element. - -#### Algorithm: -1. Initialize an empty set to store elements. -2. Iterate through the array and calculate the complement (target - current element). -3. If the complement exists in the set, add the pair to the result. -4. Otherwise, add the current element to the set. -5. Return the list of pairs. - -#### Example: -```javascript -function findPairsWithSum(arr, target) { - const seen = new Set(), pairs = []; - for (let num of arr) { - const complement = target - num; - if (seen.has(complement)) { - pairs.push([complement, num]); - } - seen.add(num); - } - return pairs; -} - -// Example usage -console.log(findPairsWithSum([1, 2, 3, 4, 5], 5)); // Output: [[2, 3], [1, 4]] -console.log(findPairsWithSum([10, 15, 3, 7], 17)); // Output: [[10, 7]] -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find All Pairs That Sum to a Target](#find-all-pairs-that-sum-to-a-target) - -### Find All Pairs That Sum to a Target - -To find all pairs of numbers in an array that sum up to a target value, use a hash set to track the numbers seen so far and check if the complement of each number exists in the set. - -#### Algorithm: -1. Initialize an empty set to store the numbers. -2. Iterate through the array and for each number, check if the complement (target - number) is already in the set. -3. If the complement exists, add the pair to the result array. -4. If the complement doesn't exist, add the current number to the set. - -#### Example: -```javascript -function findPairs(arr, target) { - let pairs = []; - let seen = new Set(); - for (let num of arr) { - let complement = target - num; - if (seen.has(complement)) { - pairs.push([complement, num]); - } - seen.add(num); - } - return pairs; -} - -// Example usage -console.log(findPairs([1, 2, 3, 4, 5], 5)); // Output: [[2, 3], [1, 4]] -console.log(findPairs([1, 3, 2, 4, 5], 6)); // Output: [[1, 5], [2, 4]] -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find All Pairs with a Given Sum](#find-all-pairs-with-sum) - -### Find All Pairs with a Given Sum - -To find all pairs in an array that sum up to a specific target value, use a hash set to track the numbers that can form pairs. - -#### Algorithm: -1. Initialize an empty set to store numbers. -2. Iterate through the array and for each element, check if the complement (target - current element) is in the set. -3. If the complement exists, add the pair to the result array. -4. If not, add the current element to the set. -5. Return the array of pairs. - -#### Example: -```javascript -function findPairs(arr, target) { - const pairs = []; - const seen = new Set(); - for (let num of arr) { - const complement = target - num; - if (seen.has(complement)) { - pairs.push([complement, num]); - } - seen.add(num); - } - return pairs; -} - -// Example usage -console.log(findPairs([1, 2, 3, 4, 5], 5)); // Output: [[1, 4], [2, 3]] -console.log(findPairs([10, 15, 3, 7], 17)); // Output: [[10, 7]] -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find All Prime Numbers in a Range](#find-all-prime-numbers-in-a-range) - -### Find All Prime Numbers in a Range - -To find all prime numbers within a given range, use the Sieve of Eratosthenes algorithm to efficiently find primes. - -#### Algorithm: -1. Create a boolean array `isPrime` where each index represents a number. -2. Set all values to `true` except for 0 and 1. -3. Starting from 2, mark all multiples of each prime as `false`. -4. Return the indices that are still `true` as the prime numbers. - -#### Example: -```javascript -function sieveOfEratosthenes(limit) { - let isPrime = new Array(limit + 1).fill(true); - isPrime[0] = isPrime[1] = false; - for (let i = 2; i * i <= limit; i++) { - if (isPrime[i]) { - for (let j = i * i; j <= limit; j += i) { - isPrime[j] = false; - } - } - } - return isPrime.map((prime, index) => prime ? index : -1).filter(index => index !== -1); -} - -// Example usage -console.log(sieveOfEratosthenes(20)); // Output: [2, 3, 5, 7, 11, 13, 17, 19] -``` - -This method has a time complexity of O(n log log n), where n is the limit. - -**Tags**: basic, JavaScript, Math, Algorithm - - - ---- - -## [Find All Prime Numbers in an Array](#find-all-prime-numbers-in-an-array) - -### Find All Prime Numbers in an Array - -To find all prime numbers in an array, check each number in the array to see if it is prime. - -#### Algorithm: -1. Define a helper function `isPrime` to check if a number is prime. -2. Iterate through the array, calling `isPrime` on each element. -3. Collect the prime numbers and return them. - -#### Example: -```javascript -function isPrime(num) { - if (num <= 1) return false; - for (let i = 2; i <= Math.sqrt(num); i++) { - if (num % i === 0) return false; - } - return true; -} - -function findPrimes(arr) { - return arr.filter(isPrime); -} - -// Example usage -console.log(findPrimes([1, 2, 3, 4, 5, 6])); // Output: [2, 3, 5] -console.log(findPrimes([10, 15, 23, 30])); // Output: [23] -``` - -This method has a time complexity of O(n * sqrt(m)), where n is the length of the array and m is the largest number in the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find All Subsets of an Array](#find-all-subsets-of-an-array) - -### Find All Subsets of an Array - -To find all subsets of an array, use a bitwise approach. Each element can either be included or excluded from a subset, so there are `2^n` possible subsets. - -#### Algorithm: -1. Initialize an empty array to store the subsets. -2. Iterate over the range from 0 to `2^n - 1`. -3. For each number in the range, use its binary representation to decide which elements to include in the subset. -4. Return the array of subsets. - -#### Example: -```javascript -function getSubsets(arr) { - let subsets = []; - let n = arr.length; - for (let i = 0; i < (1 << n); i++) { - let subset = []; - for (let j = 0; j < n; j++) { - if (i & (1 << j)) { - subset.push(arr[j]); - } - } - subsets.push(subset); - } - return subsets; -} - -// Example usage -console.log(getSubsets([1, 2, 3])); -// Output: [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] -``` - -This method has a time complexity of O(2^n), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find All Substrings of a String](#find-all-substrings-of-a-string) - -### Find All Substrings of a String - -To find all substrings of a string, iterate through all possible starting and ending indices to extract substrings. - -#### Algorithm: -1. Initialize an empty array to store substrings. -2. Iterate through the string with two nested loops: one for the starting index and one for the ending index. -3. Extract the substring for each pair of indices and add it to the result array. -4. Return the array of substrings. - -#### Example: -```javascript -function findAllSubstrings(str) { - const substrings = []; - for (let i = 0; i < str.length; i++) { - for (let j = i + 1; j <= str.length; j++) { - substrings.push(str.slice(i, j)); - } - } - return substrings; -} - -// Example usage -console.log(findAllSubstrings('abc')); // Output: ['a', 'ab', 'abc', 'b', 'bc', 'c'] -console.log(findAllSubstrings('hello')); // Output: ['h', 'he', 'hel', 'hell', 'hello', 'e', 'el', 'ell', 'ello', 'l', 'll', 'llo', 'l', 'lo', 'o'] -``` - -This method has a time complexity of O(n^2), where n is the length of the string. - -**Tags**: intermediate, JavaScript, Strings, Algorithm - - - ---- - -## [Find Common Characters in Two Strings](#find-common-characters-in-two-strings) - -### Find Common Characters in Two Strings - -To find common characters in two strings, use a frequency map for each string and compare the characters. - -#### Algorithm: -1. Create a frequency map for each string to count the occurrences of each character. -2. Compare the frequency maps to find common characters. -3. Return the list of common characters. - -#### Example: -```javascript -function findCommonCharacters(str1, str2) { - const map1 = {}, map2 = {}; - for (let char of str1) map1[char] = (map1[char] || 0) + 1; - for (let char of str2) map2[char] = (map2[char] || 0) + 1; - const common = []; - for (let char in map1) { - if (map2[char]) { - const count = Math.min(map1[char], map2[char]); - for (let i = 0; i < count; i++) common.push(char); - } - } - return common; -} - -// Example usage -console.log(findCommonCharacters('abc', 'cde')); // Output: ['c'] -console.log(findCommonCharacters('aabb', 'abcc')); // Output: ['a', 'b'] -``` - -This method has a time complexity of O(n + m), where n and m are the lengths of the two strings. - -**Tags**: basic, JavaScript, Strings, Algorithm - - - ---- - -## [Find Common Prefix in an Array of Strings](#find-common-prefix-in-an-array-of-strings) - -### Find Common Prefix in an Array of Strings - -To find the longest common prefix among an array of strings, compare characters from each string in the array. - -#### Algorithm: -1. Initialize the first string in the array as the common prefix. -2. Iterate through the rest of the strings, updating the common prefix by comparing it with each string. -3. If no common prefix is found, return an empty string. -4. Return the final common prefix. - -#### Example: -```javascript -function findCommonPrefix(arr) { - if (arr.length === 0) return ""; - - let prefix = arr[0]; - for (let i = 1; i < arr.length; i++) { - while (arr[i].indexOf(prefix) !== 0) { - prefix = prefix.slice(0, prefix.length - 1); - if (prefix === "") return ""; - } - } - return prefix; -} - -// Example usage -console.log(findCommonPrefix(["flower", "flow", "flight"])); // Output: "fl" -console.log(findCommonPrefix(["dog", "racecar", "car"])); // Output: "" -``` - -This method has a time complexity of O(n * m), where n is the length of the array and m is the length of the longest string. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find Duplicate Elements in an Array](#find-duplicate-elements-in-an-array) - -### Find Duplicate Elements in an Array - -To find duplicate elements in an array, use a set to track the elements you've seen as you iterate through the array. - -#### Algorithm: -1. Initialize an empty set to store unique elements. -2. Iterate through the array and check if each element is already in the set. -3. If it is, add it to the result array. -4. Return the array of duplicates. - -#### Example: -```javascript -function findDuplicates(arr) { - const seen = new Set(); - const duplicates = []; - - for (const num of arr) { - if (seen.has(num)) { - duplicates.push(num); - } - seen.add(num); - } - - return duplicates; -} - -// Example usage -console.log(findDuplicates([1, 2, 3, 2, 4, 5, 1])); // Output: [2, 1] -console.log(findDuplicates(["apple", "banana", "apple", "orange"])); // Output: ["apple"] -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find Duplicates in an Array Without Extra Space](#find-duplicates-in-an-array-without-extra-space) - -### Find Duplicates in an Array Without Extra Space - -To find duplicates without using extra space, you can modify the array in-place. - -#### Algorithm: -1. Iterate through the array and use the value of each element as an index. -2. If the value at that index is negative, it means the element has been seen before, so it is a duplicate. -3. If the value at that index is positive, make it negative to mark it as visited. -4. Return the duplicates. - -#### Example: -```javascript -function findDuplicatesInPlace(arr) { - const duplicates = []; - for (let i = 0; i < arr.length; i++) { - const absVal = Math.abs(arr[i]); - if (arr[absVal] < 0) { - duplicates.push(absVal); - } else { - arr[absVal] = -arr[absVal]; - } - } - return duplicates; -} - -// Example usage -console.log(findDuplicatesInPlace([4, 3, 2, 7, 8, 2, 3, 1])); // Output: [2, 3] -console.log(findDuplicatesInPlace([1, 1, 1, 2, 2])); // Output: [1, 2] -``` - -This method has a time complexity of O(n), where n is the length of the array, and does not use extra space. - -**Tags**: advanced, JavaScript, Arrays, Algorithm - - - ---- - -## [Find if a Number is Prime](#find-if-a-number-is-prime) - -### Find if a Number is Prime - -A prime number is a number greater than 1 that has no divisors other than 1 and itself. To check if a number is prime, iterate through numbers from 2 to the square root of the number. - -#### Algorithm: -1. If the number is less than or equal to 1, return `false`. -2. Check for divisibility by all numbers from 2 to the square root of the number. -3. If any number divides evenly, return `false`. Otherwise, return `true`. - -#### Example: -```javascript -function isPrime(num) { - if (num <= 1) return false; - for (let i = 2; i <= Math.sqrt(num); i++) { - if (num % i === 0) return false; - } - return true; -} - -// Example usage -console.log(isPrime(7)); // Output: true -console.log(isPrime(10)); // Output: false -``` - -This method has a time complexity of O(sqrt(n)), where n is the number being checked. - -**Tags**: basic, JavaScript, Math, Algorithm - - - ---- - -## [Find if a String is Rotated](#find-if-a-string-is-rotated) - -### Find if a String is Rotated - -To check if one string is a rotation of another, concatenate the second string with itself and check if the first string is a substring of the concatenated string. - -#### Algorithm: -1. Concatenate the second string with itself. -2. Check if the first string is a substring of the concatenated string. -3. Return true if it is a substring, false otherwise. - -#### Example: -```javascript -function isRotated(str1, str2) { - if (str1.length !== str2.length) return false; - return (str2 + str2).includes(str1); -} - -// Example usage -console.log(isRotated('abc', 'bca')); // Output: true -console.log(isRotated('abc', 'acb')); // Output: false -``` - -This method has a time complexity of O(n), where n is the length of the string. - -**Tags**: intermediate, JavaScript, Strings, Algorithm - - - ---- - -## [Find Largest Palindrome in an Array](#find-largest-palindrome-in-an-array) - -### Find Largest Palindrome in an Array - -To find the largest palindrome in an array, iterate through the array and check each element to see if it is a palindrome. - -#### Algorithm: -1. Iterate through the array and check if each element is a palindrome. -2. Keep track of the largest palindrome found. -3. Return the largest palindrome. - -#### Example: -```javascript -function isPalindrome(str) { - return str === str.split('').reverse().join(''); -} - -function largestPalindrome(arr) { - let largest = ''; - for (let str of arr) { - if (isPalindrome(str) && str.length > largest.length) { - largest = str; - } - } - return largest; -} - -// Example usage -console.log(largestPalindrome(['madam', 'racecar', 'apple'])); // Output: 'racecar' -console.log(largestPalindrome(['hello', 'world', 'civic'])); // Output: 'civic' -``` - -This method has a time complexity of O(n * m), where n is the length of the array and m is the average length of the strings. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Missing Number in an Array](#find-missing-number-in-an-array) - -### Find the Missing Number in an Array - -To find the missing number in a sequential array, calculate the expected sum and subtract the actual sum of the array. - -#### Algorithm: -1. Calculate the sum of numbers from 1 to n using the formula `n * (n + 1) / 2`. -2. Calculate the sum of the elements in the array. -3. Subtract the actual sum from the expected sum to find the missing number. - -#### Example: -```javascript -function findMissingNumber(arr) { - const n = arr.length + 1; - const expectedSum = (n * (n + 1)) / 2; - const actualSum = arr.reduce((sum, num) => sum + num, 0); - - return expectedSum - actualSum; -} - -// Example usage -console.log(findMissingNumber([1, 2, 4, 5, 6])); // Output: 3 -console.log(findMissingNumber([3, 7, 1, 2, 8, 4, 5])); // Output: 6 -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Average of an Array](#find-the-average-of-an-array) - -### Find the Average of an Array - -To find the average of an array, sum all the elements in the array and then divide the sum by the number of elements. - -#### Algorithm: -1. Initialize a variable to store the sum of the array elements. -2. Iterate through the array and add each element to the sum. -3. Divide the sum by the length of the array to get the average. -4. Return the average. - -#### Example: -```javascript -function findAverage(arr) { - let sum = 0; - for (const num of arr) { - sum += num; - } - return sum / arr.length; -} - -// Example usage -console.log(findAverage([1, 2, 3, 4, 5])); // Output: 3 -console.log(findAverage([10, 20, 30])); // Output: 20 -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: basic, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Common Elements Between Two Arrays](#find-the-common-elements-between-two-arrays) - -### Find the Common Elements Between Two Arrays - -To find common elements between two arrays, use a set to store the elements of one array and check for intersections with the other array. - -#### Algorithm: -1. Convert the first array into a set. -2. Iterate through the second array and check if each element exists in the set. -3. If it does, add it to the result array. -4. Return the result array. - -#### Example: -```javascript -function findCommonElements(arr1, arr2) { - const set1 = new Set(arr1); - const common = []; - - for (const num of arr2) { - if (set1.has(num)) { - common.push(num); - } - } - - return common; -} - -// Example usage -console.log(findCommonElements([1, 2, 3], [3, 4, 5])); // Output: [3] -console.log(findCommonElements(["a", "b", "c"], ["d", "b", "e"])); // Output: ["b"] -``` - -This method has a time complexity of O(n + m), where n and m are the lengths of the two arrays. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Common Elements in Two Arrays](#find-the-common-elements-in-two-arrays) - -### Find the Common Elements in Two Arrays - -To find the common elements in two arrays, you can use a set to track elements from one array and check if they exist in the other array. - -#### Algorithm: -1. Create a set from the first array to store unique elements. -2. Iterate through the second array and check if each element is present in the set. -3. If an element is found in both arrays, add it to the result array. -4. Return the array of common elements. - -#### Example: -```javascript -function findCommonElements(arr1, arr2) { - const set1 = new Set(arr1); - const common = []; - - for (const elem of arr2) { - if (set1.has(elem)) { - common.push(elem); - } - } - - return common; -} - -// Example usage -console.log(findCommonElements([1, 2, 3], [2, 3, 4])); // Output: [2, 3] -console.log(findCommonElements(["apple", "banana"], ["banana", "orange"])); // Output: ["banana"] -``` - -This method has a time complexity of O(n + m), where n and m are the lengths of the two arrays. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Difference Between Two Arrays](#find-the-difference-between-two-arrays) - -### Find the Difference Between Two Arrays - -To find the difference between two arrays, use a set to track elements that are in one array but not the other. - -#### Algorithm: -1. Convert one array into a set for efficient lookup. -2. Iterate through the second array and add elements that are not in the set to the result array. -3. Return the resulting array of differences. - -#### Example: -```javascript -function arrayDifference(arr1, arr2) { - const set = new Set(arr1); - return arr2.filter(item => !set.has(item)); -} - -// Example usage -console.log(arrayDifference([1, 2, 3], [3, 4, 5])); // Output: [4, 5] -console.log(arrayDifference([1, 2, 3, 4], [3, 4, 5])); // Output: [5] -``` - -This method has a time complexity of O(n + m), where n and m are the lengths of the two arrays. - -**Tags**: basic, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Duplicate Element in an Array](#find-the-duplicate-element-in-an-array) - -### Find the Duplicate Element in an Array - -To find a duplicate element in an array, use a set to track the elements that have been seen. If an element is already in the set, it's a duplicate. - -#### Algorithm: -1. Create an empty set to store elements. -2. Iterate through the array. -3. If the element is already in the set, return it as the duplicate. -4. If the element is not in the set, add it to the set. - -#### Example: -```javascript -function findDuplicate(arr) { - let seen = new Set(); - for (let num of arr) { - if (seen.has(num)) { - return num; - } - seen.add(num); - } - return null; -} - -// Example usage -console.log(findDuplicate([1, 2, 3, 4, 5, 3])); // Output: 3 -console.log(findDuplicate([1, 2, 3, 4, 5])); // Output: null -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: basic, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Duplicate Elements in an Array](#find-the-duplicate-elements-in-an-array) - -### Find the Duplicate Elements in an Array - -To find duplicate elements in an array, you can use a frequency map or set to track the elements that have already been encountered. - -#### Algorithm: -1. Create a set to store elements you've seen. -2. Iterate through the array and check if an element is already in the set. -3. If it is, add it to the result array. -4. If not, add it to the set. -5. Return the result array with duplicates. - -#### Example: -```javascript -function findDuplicates(arr) { - let seen = new Set(), duplicates = []; - for (let num of arr) { - if (seen.has(num)) { - duplicates.push(num); - } else { - seen.add(num); - } - } - return duplicates; -} - -// Example usage -console.log(findDuplicates([1, 2, 3, 1, 4, 5, 3])); // Output: [1, 3] -console.log(findDuplicates([10, 20, 30, 40])); // Output: [] -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Duplicate Number in an Array](#find-the-duplicate-number-in-an-array) - -### Find the Duplicate Number in an Array - -To find the duplicate number in an array, use a set to track numbers that have been encountered. If a number is encountered more than once, it's the duplicate. - -#### Algorithm: -1. Initialize an empty set to track numbers. -2. Iterate through the array, and for each element, check if it already exists in the set. -3. If it does, return that element as the duplicate. -4. If it does not, add the element to the set. - -#### Example: -```javascript -function findDuplicate(arr) { - const seen = new Set(); - for (let num of arr) { - if (seen.has(num)) { - return num; - } - seen.add(num); - } - return null; // No duplicates found -} - -// Example usage -console.log(findDuplicate([1, 2, 3, 4, 5, 3])); // Output: 3 -console.log(findDuplicate([1, 2, 3, 4, 5])); // Output: null -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the First Index of an Element in an Array](#find-the-first-index-of-an-element-in-an-array) - -### Find the First Index of an Element in an Array - -To find the first index of an element in an array, you can use the `indexOf` method. - -#### Algorithm: -1. Use the `indexOf` method to search for the element in the array. -2. If the element is found, return its index. -3. If the element is not found, return `-1`. - -#### Example: -```javascript -function findFirstIndex(arr, elem) { - return arr.indexOf(elem); -} - -// Example usage -console.log(findFirstIndex([1, 2, 3, 4], 3)); // Output: 2 -console.log(findFirstIndex(["apple", "banana", "cherry"], "banana")); // Output: 1 -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: basic, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the First Missing Positive Integer](#find-the-first-missing-positive-integer) - -### Find the First Missing Positive Integer - -To find the first missing positive integer in an unsorted array, use an in-place hash set technique to rearrange the elements and identify the missing number. - -#### Algorithm: -1. Iterate through the array and move each number to its correct position (i.e., `arr[i] = i + 1`). -2. After rearranging, find the first index where the value is not equal to `index + 1`. -3. Return `index + 1` as the first missing positive integer. - -#### Example: -```javascript -function firstMissingPositive(nums) { - for (let i = 0; i < nums.length; i++) { - while (nums[i] > 0 && nums[i] <= nums.length && nums[nums[i] - 1] !== nums[i]) { - [nums[nums[i] - 1], nums[i]] = [nums[i], nums[nums[i] - 1]]; - } - } - for (let i = 0; i < nums.length; i++) { - if (nums[i] !== i + 1) return i + 1; - } - return nums.length + 1; -} - -// Example usage -console.log(firstMissingPositive([1, 2, 0])); // Output: 3 -console.log(firstMissingPositive([3, 4, -1, 1])); // Output: 2 -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the First Non-Repeating Character](#find-the-first-non-repeating-character) - -### Find the First Non-Repeating Character - -To find the first non-repeating character in a string, you can use a frequency counter to track character occurrences. - -#### Algorithm: -1. Create an empty object to store character frequencies. -2. Iterate through the string and count occurrences of each character by updating the object. -3. Iterate through the string again and check the frequency of each character in the object. -4. Return the first character with a frequency of 1. -5. If no non-repeating character is found, return `null`. - -#### Example: -```javascript -function firstNonRepeatingChar(str) { - const charCount = {}; - - // Count occurrences of each character - for (const char of str) { - charCount[char] = (charCount[char] || 0) + 1; - } - - // Find the first character with a count of 1 - for (const char of str) { - if (charCount[char] === 1) { - return char; - } - } - - return null; // Return null if no non-repeating character is found -} - -// Example usage -console.log(firstNonRepeatingChar("swiss")); // Output: "w" -``` - -This method has a time complexity of O(n) as it involves two iterations over the string. - -**Tags**: intermediate, JavaScript, Strings, Algorithm, Data Structures - -**URL**: [https://www.tiktok.com/@jsmentoring/video/7458383226621529376](https://www.tiktok.com/@jsmentoring/video/7458383226621529376) - ---- - -## [Find the First Repeated Character](#find-the-first-repeated-character) - -### Find the First Repeated Character - -To find the first repeated character in a string, use a frequency counter to track character occurrences. - -#### Algorithm: -1. Initialize an empty set to track characters as you iterate through the string. -2. For each character, check if it already exists in the set. -3. If it does, return the character as the first repeated character. -4. If no repeated character is found, return `null`. - -#### Example: -```javascript -function findFirstRepeatedChar(str) { - const seen = new Set(); - - for (const char of str) { - if (seen.has(char)) { - return char; - } - seen.add(char); - } - - return null; -} - -// Example usage -console.log(findFirstRepeatedChar("abcdab")); // Output: "a" -console.log(findFirstRepeatedChar("abcdef")); // Output: null -``` - -This method has a time complexity of O(n), where n is the length of the string. - -**Tags**: intermediate, JavaScript, Strings, Algorithm - - - ---- - -## [Find the First Repeated Character in a String](#find-the-first-repeated-character-in-a-string) - -### Find the First Repeated Character in a String - -To find the first repeated character in a string, use a set to track characters that have been seen. - -#### Algorithm: -1. Initialize an empty set to store characters. -2. Iterate through the string, checking if each character has already been seen in the set. -3. If a character is found in the set, return it as the first repeated character. -4. If no repeated character is found, return `null`. - -#### Example: -```javascript -function findFirstRepeatedCharacter(str) { - const seen = new Set(); - for (let char of str) { - if (seen.has(char)) return char; - seen.add(char); - } - return null; -} - -// Example usage -console.log(findFirstRepeatedCharacter('abcdeab')); // Output: 'a' -console.log(findFirstRepeatedCharacter('abcdef')); // Output: null -``` - -This method has a time complexity of O(n), where n is the length of the string. - -**Tags**: intermediate, JavaScript, Strings, Algorithm - - - ---- - -## [Find the First Repeating Character](#find-the-first-repeating-character) - -### Find the First Repeating Character - -To find the first repeating character in a string, use a set to track characters that have been seen. As you iterate through the string, check if the character is already in the set. - -#### Algorithm: -1. Initialize an empty set to track seen characters. -2. Iterate through the string. -3. If a character is already in the set, return it as the first repeating character. -4. If not, add it to the set. - -#### Example: -```javascript -function firstRepeatingCharacter(str) { - let seen = new Set(); - for (let char of str) { - if (seen.has(char)) { - return char; - } - seen.add(char); - } - return null; -} - -// Example usage -console.log(firstRepeatingCharacter('abca')); // Output: 'a' -console.log(firstRepeatingCharacter('abcdef')); // Output: null -``` - -This method has a time complexity of O(n), where n is the length of the string. - -**Tags**: basic, JavaScript, Strings, Algorithm - - - ---- - -## [Find the First Repeating Element in an Array](#find-the-first-repeating-element-in-an-array) - -### Find the First Repeating Element in an Array - -To find the first repeating element in an array, you can use a set to keep track of the elements you've already seen. - -#### Algorithm: -1. Initialize an empty set to store the elements. -2. Iterate through the array, checking if each element is in the set. -3. If it is, return the element as the first repeating one. -4. If no repeating element is found, return `null`. - -#### Example: -```javascript -function findFirstRepeating(arr) { - const seen = new Set(); - - for (const num of arr) { - if (seen.has(num)) { - return num; - } - seen.add(num); - } - - return null; -} - -// Example usage -console.log(findFirstRepeating([1, 2, 3, 2, 4])); // Output: 2 -console.log(findFirstRepeating([5, 3, 4, 1])); // Output: null -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Greatest Common Divisor (GCD)](#find-the-greatest-common-divisor) - -### Find the Greatest Common Divisor (GCD) - -To find the GCD of two numbers, you can use the Euclidean algorithm. - -#### Algorithm: -1. If `b` is 0, return `a` as the GCD. -2. Otherwise, call the function recursively with `b` and `a % b` as the arguments. -3. Repeat until the second number becomes 0. - -#### Example: -```javascript -function gcd(a, b) { - if (b === 0) return a; - return gcd(b, a % b); -} - -// Example usage -console.log(gcd(56, 98)); // Output: 14 -console.log(gcd(100, 25)); // Output: 25 -``` - -This method has a time complexity of O(log(min(a, b))), where a and b are the two numbers. - -**Tags**: intermediate, JavaScript, Math, Algorithm - - - ---- - -## [Find the Kth Largest Element in an Array](#find-the-kth-largest-element-in-an-array) - -### Find the Kth Largest Element in an Array - -To find the Kth largest element in an array, you can sort the array in descending order and return the element at the Kth position. - -#### Algorithm: -1. Sort the array in descending order. -2. Return the element at index K-1. -3. If K is larger than the length of the array, return `null`. - -#### Example: -```javascript -function findKthLargest(arr, k) { - arr.sort((a, b) => b - a); - return arr[k - 1] || null; -} - -// Example usage -console.log(findKthLargest([1, 3, 5, 2, 4], 2)); // Output: 4 -console.log(findKthLargest([7, 2, 9, 4], 3)); // Output: 4 -``` - -This method has a time complexity of O(n log n), where n is the length of the array due to sorting. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Kth Smallest Element in an Array](#find-the-kth-smallest-element-in-an-array) - -### Find the Kth Smallest Element in an Array - -To find the Kth smallest element in an array, use the Quickselect algorithm or sort the array and return the element at the Kth index. - -#### Algorithm (Quickselect): -1. Select a pivot element from the array. -2. Partition the array into two subarrays: one with elements smaller than the pivot, and one with elements larger. -3. If the Kth element is in the smaller subarray, repeat the process with that subarray. -4. If the Kth element is in the larger subarray, repeat the process with that subarray. -5. Return the Kth smallest element. - -#### Example (using sorting): -```javascript -function kthSmallest(arr, k) { - arr.sort((a, b) => a - b); - return arr[k - 1]; -} - -// Example usage -console.log(kthSmallest([7, 10, 4, 3, 20, 15], 4)); // Output: 10 -console.log(kthSmallest([12, 3, 5, 7, 19], 2)); // Output: 5 -``` - -This method has a time complexity of O(n log n) for sorting, where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Largest Even Number in an Array](#find-the-largest-even-number-in-an-array) - -### Find the Largest Even Number in an Array - -To find the largest even number in an array, iterate through the array and check each element for evenness, keeping track of the largest even number. - -#### Algorithm: -1. Initialize a variable to store the largest even number, starting with a value like `-Infinity`. -2. Iterate through the array and check if each element is even. -3. If the element is even and larger than the current largest even number, update the largest even number. -4. Return the largest even number. - -#### Example: -```javascript -function findLargestEven(arr) { - let largestEven = -Infinity; - - for (const num of arr) { - if (num % 2 === 0 && num > largestEven) { - largestEven = num; - } - } - - return largestEven === -Infinity ? null : largestEven; -} - -// Example usage -console.log(findLargestEven([1, 2, 3, 4, 5])); // Output: 4 -console.log(findLargestEven([7, 5, 9, 1])); // Output: null -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Largest Number in an Array](#find-the-largest-number-in-an-array) - -### Find the Largest Number in an Array - -To find the largest number in an array, iterate through the array and keep track of the largest number. - -#### Algorithm: -1. Initialize a variable to store the largest number with a small value (e.g., `-Infinity`). -2. Iterate through the array and compare each element to the current largest number. -3. Update the largest number whenever a larger element is found. -4. Return the largest number. - -#### Example: -```javascript -function findLargest(arr) { - let largest = -Infinity; - - for (const num of arr) { - if (num > largest) { - largest = num; - } - } - - return largest; -} - -// Example usage -console.log(findLargest([5, 3, 8, 1, 6])); // Output: 8 -console.log(findLargest([7, 4, 9, 2])); // Output: 9 -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: basic, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Largest Palindrome in an Array](#find-the-largest-palindrome-in-an-array) - -### Find the Largest Palindrome in an Array - -To find the largest palindrome in an array, iterate through the array and check if each number is a palindrome, keeping track of the largest one. - -#### Algorithm: -1. Iterate through the array and check if each element is a palindrome. -2. For each palindrome, compare it with the current largest palindrome. -3. Return the largest palindrome found. - -#### Example: -```javascript -function isPalindrome(num) { - return num.toString() === num.toString().split('').reverse().join(''); -} - -function findLargestPalindrome(arr) { - let largest = -Infinity; - for (let num of arr) { - if (isPalindrome(num) && num > largest) { - largest = num; - } - } - return largest === -Infinity ? 'No palindrome found' : largest; -} - -// Example usage -console.log(findLargestPalindrome([121, 123, 232, 456])); // Output: 232 -console.log(findLargestPalindrome([123, 456, 789])); // Output: No palindrome found -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Largest Product of Two Numbers in an Array](#find-the-largest-product-of-two-numbers-in-an-array) - -### Find the Largest Product of Two Numbers in an Array - -To find the largest product of two numbers in an array, iterate through the array while keeping track of the two largest numbers. - -#### Algorithm: -1. Initialize two variables, `max1` and `max2`, to negative infinity. -2. Iterate through the array, updating `max1` and `max2` as you find larger numbers. -3. Return the product of `max1` and `max2`. - -#### Example: -```javascript -function largestProduct(arr) { - let max1 = -Infinity, max2 = -Infinity; - for (let num of arr) { - if (num > max1) { - max2 = max1; - max1 = num; - } else if (num > max2) { - max2 = num; - } - } - return max1 * max2; -} - -// Example usage -console.log(largestProduct([1, 2, 3, 4, 5])); // Output: 20 -console.log(largestProduct([-10, -10, 5, 2])); // Output: 100 -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Largest Sum of Consecutive Subarray](#find-the-largest-sum-of-consecutive-subarray) - -### Find the Largest Sum of Consecutive Subarray - -To find the largest sum of a consecutive subarray, you can use Kadane's Algorithm. - -#### Algorithm: -1. Initialize two variables: `maxSum` and `currentSum`, both set to the first element of the array. -2. Iterate through the array, updating `currentSum` to the larger of the current element or the sum of `currentSum` and the current element. -3. Update `maxSum` to the larger of `maxSum` and `currentSum`. -4. Return `maxSum`. - -#### Example: -```javascript -function maxSubArraySum(arr) { - let maxSum = arr[0], currentSum = arr[0]; - - for (let i = 1; i < arr.length; i++) { - currentSum = Math.max(arr[i], currentSum + arr[i]); - maxSum = Math.max(maxSum, currentSum); - } - - return maxSum; -} - -// Example usage -console.log(maxSubArraySum([1, -2, 3, 4, -1, 2, 1, -5, 4])); // Output: 7 -console.log(maxSubArraySum([-2, -3, 4, -1, -2, 1, 5, -3])); // Output: 7 -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Largest Sum of Contiguous Subarray](#find-the-largest-sum-of-contiguous-subarray) - -### Find the Largest Sum of Contiguous Subarray - -To find the largest sum of a contiguous subarray, use Kadane's Algorithm, which helps to find the maximum sum efficiently in linear time. - -#### Algorithm: -1. Initialize two variables, `maxCurrent` and `maxGlobal`, to the first element of the array. -2. Iterate through the array starting from the second element. -3. For each element, update `maxCurrent` to the maximum of the current element or the sum of the current element and `maxCurrent`. -4. If `maxCurrent` exceeds `maxGlobal`, update `maxGlobal`. -5. Return `maxGlobal` as the result. - -#### Example: -```javascript -function maxSubArraySum(arr) { - let maxCurrent = maxGlobal = arr[0]; - for (let i = 1; i < arr.length; i++) { - maxCurrent = Math.max(arr[i], maxCurrent + arr[i]); - if (maxCurrent > maxGlobal) { - maxGlobal = maxCurrent; - } - } - return maxGlobal; -} - -// Example usage -console.log(maxSubArraySum([1, -2, 3, 4, -1, 2, 1, -5, 4])); // Output: 7 -console.log(maxSubArraySum([-1, -2, -3, -4])); // Output: -1 -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Longest Common Prefix](#find-the-longest-common-prefix) - -### Find the Longest Common Prefix - -To find the longest common prefix among a set of strings, iterate through the strings character by character and check if they match. - -#### Algorithm: -1. Sort the array of strings. -2. Compare the first and the last string character by character. -3. The characters that match are the common prefix. -4. Return the common prefix. - -#### Example: -```javascript -function longestCommonPrefix(strs) { - if (strs.length === 0) return ''; - strs.sort(); - let first = strs[0], last = strs[strs.length - 1]; - let i = 0; - while (i < first.length && first[i] === last[i]) { - i++; - } - return first.substring(0, i); -} - -// Example usage -console.log(longestCommonPrefix(['flower', 'flow', 'flight'])); // Output: 'fl' -console.log(longestCommonPrefix(['dog', 'racecar', 'car'])); // Output: '' -``` - -This method has a time complexity of O(n log n), where n is the number of strings. - -**Tags**: basic, JavaScript, Strings, Algorithm - - - ---- - -## [Find the Longest Increasing Subarray](#find-the-longest-increasing-subarray) - -### Find the Longest Increasing Subarray - -To find the longest increasing subarray, iterate through the array and track the length of the current increasing subarray. - -#### Algorithm: -1. Initialize variables to track the current and maximum subarray lengths. -2. Iterate through the array and check if the current element is greater than the previous one. -3. If the current element is greater, increment the current subarray length. -4. If not, compare the current subarray length with the maximum length and reset the current subarray length. -5. Return the maximum subarray length. - -#### Example: -```javascript -function longestIncreasingSubarray(arr) { - let maxLength = 1, currentLength = 1; - - for (let i = 1; i < arr.length; i++) { - if (arr[i] > arr[i - 1]) { - currentLength++; - maxLength = Math.max(maxLength, currentLength); - } else { - currentLength = 1; - } - } - - return maxLength; -} - -// Example usage -console.log(longestIncreasingSubarray([1, 2, 3, 1, 2, 3, 4])); // Output: 4 -console.log(longestIncreasingSubarray([5, 4, 3, 2, 1])); // Output: 1 -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Longest Increasing Subsequence](#find-the-longest-increasing-subsequence) - -### Find the Longest Increasing Subsequence - -The longest increasing subsequence (LIS) is a subsequence of a given array where the elements are in strictly increasing order. The goal is to find the length of the LIS. - -#### Algorithm: -1. Initialize an array `dp` where `dp[i]` stores the length of the longest increasing subsequence that ends at index `i`. -2. Iterate through the array, and for each element, check all previous elements to see if it can form a longer subsequence. -3. Return the maximum value in `dp`. - -#### Example: -```javascript -function lengthOfLIS(nums) { - if (nums.length === 0) return 0; - let dp = new Array(nums.length).fill(1); - for (let i = 1; i < nums.length; i++) { - for (let j = 0; j < i; j++) { - if (nums[i] > nums[j]) { - dp[i] = Math.max(dp[i], dp[j] + 1); - } - } - } - return Math.max(...dp); -} - -// Example usage -console.log(lengthOfLIS([10, 9, 2, 5, 3, 7, 101, 18])); // Output: 4 -``` - -This method has a time complexity of O(n^2), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Longest Palindrome in a String](#find-the-longest-palindrome-in-a-string) - -### Find the Longest Palindrome in a String - -To find the longest palindrome in a string, expand around each character and check for the longest palindromic substring. - -#### Algorithm: -1. Initialize variables to store the start and end indices of the longest palindrome. -2. For each character in the string, expand outwards while the characters on both sides match. -3. Track the maximum length of palindrome found during the expansion. -4. Return the longest palindromic substring. - -#### Example: -```javascript -function longestPalindrome(s) { - let start = 0, end = 0; - for (let i = 0; i < s.length; i++) { - let len1 = expandAroundCenter(s, i, i); - let len2 = expandAroundCenter(s, i, i + 1); - let len = Math.max(len1, len2); - if (len > (end - start)) { - start = i - Math.floor((len - 1) / 2); - end = i + Math.floor(len / 2); - } - } - return s.substring(start, end + 1); -} - -function expandAroundCenter(s, left, right) { - while (left >= 0 && right < s.length && s[left] === s[right]) { - left--; - right++; - } - return right - left - 1; -} - -// Example usage -console.log(longestPalindrome('babad')); // Output: 'bab' or 'aba' -console.log(longestPalindrome('cbbd')); // Output: 'bb' -``` - -This method has a time complexity of O(n^2), where n is the length of the string. - -**Tags**: intermediate, JavaScript, Strings, Algorithm - - - ---- - -## [Find the Longest Substring Without Repeating Characters](#find-the-longest-substring-without-repeating-characters) - -### Find the Longest Substring Without Repeating Characters - -To find the longest substring without repeating characters, use a sliding window technique with two pointers to track the current substring. - -#### Algorithm: -1. Initialize two pointers, one for the start and one for the end of the window. -2. Move the end pointer to expand the window and add characters to a set. -3. If a character is already in the set, move the start pointer to shrink the window and remove the character from the set. -4. Keep track of the maximum window length. -5. Return the maximum length of the substring. - -#### Example: -```javascript -function longestSubstring(str) { - let start = 0, maxLength = 0, seen = new Set(); - for (let end = 0; end < str.length; end++) { - while (seen.has(str[end])) { - seen.delete(str[start]); - start++; - } - seen.add(str[end]); - maxLength = Math.max(maxLength, end - start + 1); - } - return maxLength; -} - -// Example usage -console.log(longestSubstring('abcabcbb')); // Output: 3 -console.log(longestSubstring('bbbbb')); // Output: 1 -``` - -This method has a time complexity of O(n), where n is the length of the string. - -**Tags**: intermediate, JavaScript, Strings, Algorithm - - - ---- - -## [Find the Longest Word in a Sentence](#find-the-longest-word-in-a-sentence) - -### Find the Longest Word in a Sentence - -To find the longest word in a sentence, split the sentence into words and compare their lengths. - -#### Algorithm: -1. Remove any non-alphanumeric characters except spaces to clean the input. -2. Split the sentence into an array of words using spaces as the delimiter. -3. Iterate through the array, keeping track of the longest word encountered. -4. Return the longest word. If there are multiple words of the same length, return the first one encountered. - -#### Example: -```javascript -function findLongestWord(sentence) { - // Normalize the sentence: remove non-alphanumeric characters except spaces - const words = sentence.replace(/[^a-zA-Z0-9\s]/g, '').split(' '); - - let longestWord = ''; - - for (const word of words) { - if (word.length > longestWord.length) { - longestWord = word; - } - } - - return longestWord; -} - -// Example usage -console.log(findLongestWord("The quick brown fox jumps over the lazy dog.")); // Output: "jumps" -console.log(findLongestWord("Hello world!")); // Output: "Hello" -``` - -This method has a time complexity of O(n), where n is the total number of characters in the sentence. - -**Tags**: basic, JavaScript, Strings, Algorithm - - - ---- - -## [Find the Majority Element](#find-the-majority-element) - -### Find the Majority Element - -The majority element in an array is the element that appears more than `n/2` times. The Boyer-Moore Voting Algorithm is an efficient way to find this element. - -#### Algorithm: -1. Initialize a candidate element and a count variable. -2. Iterate through the array, updating the count based on the current element. -3. If the count becomes 0, set the current element as the new candidate. -4. After the first pass, the candidate will be the majority element if it exists. - -#### Example: -```javascript -function majorityElement(arr) { - let candidate = null; - let count = 0; - for (let num of arr) { - if (count === 0) { - candidate = num; - } - count += (num === candidate) ? 1 : -1; - } - return candidate; -} - -// Example usage -console.log(majorityElement([3, 3, 4, 2, 4, 4, 2, 4, 4])); // Output: 4 -console.log(majorityElement([1, 2, 3, 4, 5])); // Output: 5 (or no majority) -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Majority Element in an Array](#find-the-majority-element-in-an-array) - -### Find the Majority Element in an Array - -To find the majority element in an array (an element that appears more than n/2 times), use the Boyer-Moore Voting Algorithm. - -#### Algorithm: -1. Initialize a `candidate` variable and a `count` variable. -2. Iterate through the array. If the count is 0, set the current element as the `candidate` and set `count` to 1. If the current element is the `candidate`, increment the count, otherwise decrement it. -3. Return the `candidate`. - -#### Example: -```javascript -function majorityElement(nums) { - let candidate = null, count = 0; - for (let num of nums) { - if (count === 0) { - candidate = num; - } - count += (num === candidate) ? 1 : -1; - } - return candidate; -} - -// Example usage -console.log(majorityElement([3, 2, 3])); // Output: 3 -console.log(majorityElement([1, 2, 3, 4])); // Output: null -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Maximum Number in an Array](#find-the-maximum-number-in-an-array) - -### Find the Maximum Number in an Array - -To find the maximum number in an array, iterate through the array and keep track of the largest value encountered. - -#### Algorithm: -1. Initialize a variable to store the maximum value. Start with the first element of the array. -2. Iterate through the array, comparing each element with the current maximum. -3. If an element is greater than the current maximum, update the maximum. -4. Return the maximum value after completing the iteration. - -#### Example: -```javascript -function findMaxNumber(arr) { - if (arr.length === 0) { - throw new Error("Array is empty"); - } - - let max = arr[0]; - - for (const num of arr) { - if (num > max) { - max = num; - } - } - - return max; -} - -// Example usage -console.log(findMaxNumber([3, 1, 4, 1, 5, 9])); // Output: 9 -console.log(findMaxNumber([-10, -20, -3, -7])); // Output: -3 -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: basic, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Median of an Array](#find-the-median-of-an-array) - -### Find the Median of an Array - -To find the median of an array, first sort the array and then find the middle element. - -#### Algorithm: -1. Sort the array in ascending order. -2. If the array has an odd length, return the middle element. -3. If the array has an even length, return the average of the two middle elements. - -#### Example: -```javascript -function findMedian(arr) { - arr.sort((a, b) => a - b); - const mid = Math.floor(arr.length / 2); - return arr.length % 2 !== 0 ? arr[mid] : (arr[mid - 1] + arr[mid]) / 2; -} - -// Example usage -console.log(findMedian([1, 3, 5, 2, 4])); // Output: 3 -console.log(findMedian([7, 1, 2, 8])); // Output: 4.5 -``` - -This method has a time complexity of O(n log n), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Middle Element of an Array](#find-the-middle-element-of-an-array) - -### Find the Middle Element of an Array - -To find the middle element of an array, calculate the index of the middle and return the corresponding element. - -#### Algorithm: -1. If the array length is odd, the middle element is the element at index `Math.floor(arr.length / 2)`. -2. If the array length is even, you can choose either of the two middle elements. -3. Return the middle element. - -#### Example: -```javascript -function findMiddleElement(arr) { - const middleIndex = Math.floor(arr.length / 2); - return arr[middleIndex]; -} - -// Example usage -console.log(findMiddleElement([1, 2, 3, 4, 5])); // Output: 3 -console.log(findMiddleElement([10, 20, 30, 40])); // Output: 30 -``` - -This method has a time complexity of O(1), as it directly accesses the middle element. - -**Tags**: basic, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Missing Number in an Array](#find-the-missing-number-in-an-array) - -### Find the Missing Number in an Array - -To find the missing number in an array that contains all numbers from 1 to n except one, you can use the sum formula of an arithmetic series. - -#### Algorithm: -1. Calculate the expected sum of the numbers from 1 to n using the formula `n * (n + 1) / 2`. -2. Calculate the actual sum of the elements in the array. -3. Subtract the actual sum from the expected sum to find the missing number. - -#### Example: -```javascript -function findMissingNumber(arr) { - let n = arr.length + 1; - let expectedSum = (n * (n + 1)) / 2; - let actualSum = arr.reduce((sum, num) => sum + num, 0); - return expectedSum - actualSum; -} - -// Example usage -console.log(findMissingNumber([1, 2, 4, 5])); // Output: 3 -console.log(findMissingNumber([1, 3, 4, 5])); // Output: 2 -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: basic, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Mode of an Array](#find-the-mode-of-an-array) - -### Find the Mode of an Array - -To find the mode (most frequent element) of an array, use an object to count the occurrences of each element. - -#### Algorithm: -1. Initialize an empty object to store counts of elements. -2. Iterate through the array, updating the count for each element. -3. Find the element with the highest count. -4. Return the element with the highest frequency. - -#### Example: -```javascript -function findMode(arr) { - const counts = {}; - let maxCount = 0; - let mode = null; - - for (let num of arr) { - counts[num] = (counts[num] || 0) + 1; - if (counts[num] > maxCount) { - maxCount = counts[num]; - mode = num; - } - } - - return mode; -} - -// Example usage -console.log(findMode([1, 2, 3, 3, 4, 5])); // Output: 3 -console.log(findMode([10, 10, 10, 5, 5, 1])); // Output: 10 -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: basic, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Most Frequent Element in an Array](#find-the-most-frequent-element-in-an-array) - -### Find the Most Frequent Element in an Array - -To find the most frequent element in an array, you can use a frequency counter to track occurrences of each element. - -#### Algorithm: -1. Create an empty object to store element frequencies. -2. Iterate through the array and count occurrences of each element by updating the object. -3. Keep track of the element with the highest frequency while iterating through the object. -4. Return the element with the highest frequency. - -#### Example: -```javascript -function findMostFrequentElement(arr) { - const frequency = {}; - let maxFreq = 0; - let mostFrequent = null; - - // Count occurrences of each element - for (const elem of arr) { - frequency[elem] = (frequency[elem] || 0) + 1; - if (frequency[elem] > maxFreq) { - maxFreq = frequency[elem]; - mostFrequent = elem; - } - } - - return mostFrequent; -} - -// Example usage -console.log(findMostFrequentElement([1, 3, 2, 1, 4, 1, 3, 3])); // Output: 1 -console.log(findMostFrequentElement(["apple", "banana", "apple", "orange", "banana", "apple"])); // Output: "apple" -``` - -This method has a time complexity of O(n) as it involves a single iteration over the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm, Data Structures - -**URL**: [https://www.tiktok.com/@jsmentoring/video/7458418483282316576](https://www.tiktok.com/@jsmentoring/video/7458418483282316576) - ---- - -## [Find the Second Largest Element in an Array](#find-the-second-largest-element-in-an-array) - -### Find the Second Largest Element in an Array - -To find the second largest element in an array, iterate through the array and keep track of the largest and second largest elements. - -#### Algorithm: -1. Initialize two variables, `largest` and `secondLargest`, with a very small value (e.g., `-Infinity`). -2. Iterate through the array, updating `largest` and `secondLargest` as needed. -3. Return the second largest element. - -#### Example: -```javascript -function findSecondLargest(arr) { - let largest = -Infinity, secondLargest = -Infinity; - - for (const num of arr) { - if (num > largest) { - secondLargest = largest; - largest = num; - } else if (num > secondLargest && num < largest) { - secondLargest = num; - } - } - - return secondLargest; -} - -// Example usage -console.log(findSecondLargest([5, 2, 8, 3, 1])); // Output: 5 -console.log(findSecondLargest([10, 10, 9, 8])); // Output: 9 -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Second Largest Number in an Array](#find-the-second-largest-number-in-an-array) - -### Find the Second Largest Number in an Array - -To find the second largest number in an array, iterate through the array and keep track of the largest and second largest elements. - -#### Algorithm: -1. Initialize two variables, `first` and `second`, to `-Infinity`. -2. Iterate through the array, and for each element, check if it is greater than `first`. -3. If it is, update `second` to `first` and then update `first` to the current element. -4. If the element is smaller than `first` but greater than `second`, update `second`. -5. Return `second` as the second largest element. - -#### Example: -```javascript -function findSecondLargest(arr) { - let first = -Infinity, second = -Infinity; - for (let num of arr) { - if (num > first) { - second = first; - first = num; - } else if (num > second && num !== first) { - second = num; - } - } - return second; -} - -// Example usage -console.log(findSecondLargest([10, 20, 4, 45, 99])); // Output: 45 -console.log(findSecondLargest([1, 1, 1])); // Output: -Infinity -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: basic, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Second Smallest Number in an Array](#find-the-second-smallest-number-in-an-array) - -### Find the Second Smallest Number in an Array - -To find the second smallest number in an array, iterate through the array while keeping track of the smallest and second smallest values. - -#### Algorithm: -1. Initialize two variables to store the smallest and second smallest values, starting with `Infinity`. -2. Iterate through the array and update the smallest and second smallest values as you go. -3. Return the second smallest number. - -#### Example: -```javascript -function findSecondSmallest(arr) { - let smallest = Infinity; - let secondSmallest = Infinity; - - for (const num of arr) { - if (num < smallest) { - secondSmallest = smallest; - smallest = num; - } else if (num < secondSmallest && num > smallest) { - secondSmallest = num; - } - } - - return secondSmallest === Infinity ? null : secondSmallest; -} - -// Example usage -console.log(findSecondSmallest([5, 3, 8, 1, 6])); // Output: 3 -console.log(findSecondSmallest([1, 1, 1])); // Output: null -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: intermediate, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Smallest Element in an Array](#find-the-smallest-element-in-an-array) - -### Find the Smallest Element in an Array - -To find the smallest element in an array, iterate through the array and keep track of the smallest element. - -#### Algorithm: -1. Initialize a variable to store the smallest element with a large value (e.g., `Infinity`). -2. Iterate through the array and compare each element to the current smallest value. -3. Update the smallest value whenever a smaller element is found. -4. Return the smallest value. - -#### Example: -```javascript -function findSmallest(arr) { - let smallest = Infinity; - - for (const num of arr) { - if (num < smallest) { - smallest = num; - } - } - - return smallest; -} - -// Example usage -console.log(findSmallest([5, 3, 8, 1, 6])); // Output: 1 -console.log(findSmallest([7, 4, 9, 2])); // Output: 2 -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: basic, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Smallest Number in an Array](#find-the-smallest-number-in-an-array) - -### Find the Smallest Number in an Array - -To find the smallest number in an array, iterate through the array and keep track of the smallest value encountered. - -#### Algorithm: -1. Initialize a variable to store the smallest value, starting with the first element of the array. -2. Iterate through the array and compare each element with the current smallest value. -3. If an element is smaller than the current smallest, update the smallest value. -4. Return the smallest value after completing the iteration. - -#### Example: -```javascript -function findSmallestNumber(arr) { - if (arr.length === 0) { - throw new Error('Array is empty'); - } - - let smallest = arr[0]; - - for (const num of arr) { - if (num < smallest) { - smallest = num; - } - } - - return smallest; -} - -// Example usage -console.log(findSmallestNumber([3, 1, 4, 1, 5, 9])); // Output: 1 -console.log(findSmallestNumber([-10, -20, -3, -7])); // Output: -20 -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: basic, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Unique Element in an Array](#find-the-unique-element-in-an-array) - -### Find the Unique Element in an Array - -To find the unique element in an array, use the XOR operation, as XOR of a number with itself is 0, and XOR of a number with 0 is the number itself. - -#### Algorithm: -1. Initialize a variable `unique` to 0. -2. Iterate through the array, applying XOR to each element and the `unique` variable. -3. The result will be the unique element in the array. - -#### Example: -```javascript -function findUnique(arr) { - let unique = 0; - for (let num of arr) { - unique ^= num; - } - return unique; -} - -// Example usage -console.log(findUnique([1, 2, 3, 2, 1])); // Output: 3 -console.log(findUnique([4, 4, 5, 5, 6])); // Output: 6 -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: basic, JavaScript, Arrays, Algorithm - - - ---- - -## [Find the Unique Elements in an Array](#find-the-unique-elements-in-an-array) - -### Find the Unique Elements in an Array - -To find the unique elements in an array (elements that appear only once), you can use a frequency count with the help of an object or a `Map`. - -#### Algorithm: -1. Create a frequency map to count the occurrences of each element in the array. -2. Filter the array to return elements that appear only once. -3. Return the filtered result. - -#### Example: -```javascript -function findUniqueElements(arr) { - let frequency = new Map(); - arr.forEach(item => frequency.set(item, (frequency.get(item) || 0) + 1)); - return arr.filter(item => frequency.get(item) === 1); -} - -// Example usage -console.log(findUniqueElements([1, 2, 2, 3, 4, 4])); // Output: [1, 3] -console.log(findUniqueElements([5, 6, 7, 5, 6])); // Output: [7] -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: basic, JavaScript, Arrays, Algorithm - - - ---- - -## [Find Unique Characters in a String](#find-unique-characters-in-a-string) - -### Find Unique Characters in a String - -To find unique characters in a string, you can use a set to keep track of characters you've seen. - -#### Algorithm: -1. Initialize an empty set. -2. Iterate through the string and add each character to the set. -3. Return the characters in the set as a string. - -#### Example: -```javascript -function findUniqueChars(str) { - const uniqueChars = new Set(str); - return [...uniqueChars].join(''); -} - -// Example usage -console.log(findUniqueChars('aabbcc')); // Output: 'abc' -console.log(findUniqueChars('hello')); // Output: 'helo' -``` - -This method has a time complexity of O(n), where n is the length of the string. - -**Tags**: basic, JavaScript, Strings, Algorithm - - - ---- - -## [Find Unique Elements in an Array](#find-unique-elements-in-an-array) - -### Find Unique Elements in an Array - -To find unique elements in an array, you can use a set to filter out duplicates. - -#### Algorithm: -1. Convert the array to a set, which automatically removes duplicates. -2. Convert the set back to an array to get the unique elements. -3. Return the unique array. - -#### Example: -```javascript -function findUnique(arr) { - return [...new Set(arr)]; -} - -// Example usage -console.log(findUnique([1, 2, 2, 3, 4, 4])); // Output: [1, 2, 3, 4] -console.log(findUnique(["apple", "banana", "apple"])); // Output: ["apple", "banana"] -``` - -This method has a time complexity of O(n), where n is the length of the array. - -**Tags**: basic, JavaScript, Arrays, Algorithm - - - ---- - -## [Give an example of statements affected by automatic semicolon insertion?](#give-an-example-of-statements-affected-by-automatic-semicolon-insertion) - -### Give an example of statements affected by automatic semicolon insertion - -Automatic Semicolon Insertion (ASI) can lead to unexpected behavior when a semicolon is inserted incorrectly. - -Example: -```javascript -function test() { - return - { - key: 'value' - }; -} - -console.log(test()); // undefined -``` - -Explanation: -- ASI inserts a semicolon after `return`, so the object is never returned. The correct version: - -```javascript -function test() { - return { - key: 'value' - }; -} - -console.log(test()); // { key: 'value' } -``` - -**Tags**: advanced, JavaScript, Syntax - - - ---- - -## [Give an example usage of rangeOverflow property](#give-an-example-usage-of-rangeoverflow-property) - -### Give an example usage of rangeOverflow property - -The `rangeOverflow` property checks if the value entered in an input field exceeds the maximum value specified by the `max` attribute. - -Example: - -```html - - -``` - -**Tags**: intermediate, JavaScript, DOM, validation - - - ---- - -## [How can you get the list of keys of any object](#how-can-you-get-the-list-of-keys-of-any-object) - -### How can you get the list of keys of any object? - -You can use `Object.keys()` to get an array of the object's keys (property names). - -Example: - -```javascript -const person = { name: 'John', age: 30 }; -const keys = Object.keys(person); -console.log(keys); // ['name', 'age'] -``` - -**Tags**: basic, JavaScript, objects - - - ---- - -## [How do get query string values in javascript](#how-do-get-query-string-values-in-javascript) - -### How do you get query string values in JavaScript? - -To get query string values, you can use the `URLSearchParams` object. - -```javascript -const params = new URLSearchParams(window.location.search); -console.log(params.get('id')); // Gets the value of the 'id' parameter -``` - -**Tags**: basic, JavaScript, web navigation - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7455462347759471905](https://www.tiktok.com/@jsmentoring/photo/7455462347759471905) - ---- - -## [How do get the timezone offset from date](#how-do-get-the-timezone-offset-from-date) - -### How do you get the timezone offset from date? - -You can get the timezone offset from a `Date` object in JavaScript using the `getTimezoneOffset()` method. This method returns the difference between UTC and the local time, in minutes. - -Example: - -```javascript -const date = new Date(); -const offset = date.getTimezoneOffset(); -console.log(offset); // Logs the timezone offset in minutes -``` - -**Tags**: basic, JavaScript, Date - - - ---- - -## [How do I modify the url without reloading the page](#how-do-i-modify-the-url-without-reloading-the-page) - -### How do I modify the url without reloading the page? - -You can modify the URL without reloading the page using the `history.pushState()` or `history.replaceState()` methods. These methods allow you to change the URL in the browser without triggering a page reload. - -Example using `pushState`: - -```javascript -history.pushState(null, '', '/new-url'); -console.log(window.location.href); // '/new-url' -``` - -**Tags**: intermediate, JavaScript, URL manipulation - - - ---- - -## [How do style the console output using CSS?](#how-do-style-the-console-output-using-css) - -### How do style the console output using CSS? - -You can style the console output by using `%c` in the `console.log` method: - -```javascript -console.log('%cStyled Text', 'color: red; font-size: 20px;'); -``` - -The second argument specifies the CSS styles to apply to the text. - -**Tags**: intermediate, JavaScript, Console - - - ---- - -## [How do you add a key value pair in javascript](#how-do-you-add-a-key-value-pair-in-javascript) - -### How do you add a key-value pair in JavaScript? - -To add a key-value pair to an object, you can simply assign a value to a new key. - -```javascript -const obj = {}; -obj.name = 'John'; -console.log(obj); // { name: 'John' } -``` - -**Tags**: basic, JavaScript, objects - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7456001248484003104](https://www.tiktok.com/@jsmentoring/photo/7456001248484003104) - ---- - -## [How do you assign default values to variables](#how-do-you-assign-default-values-to-variables) - -### How do you assign default values to variables? - -You can assign default values to variables using the `||` operator or by using destructuring assignment. - -```javascript -const name = userInput || 'Default Name'; -``` - -**Tags**: basic, JavaScript, variables - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7456018568077937953](https://www.tiktok.com/@jsmentoring/photo/7456018568077937953) - ---- - -## [How do you avoid receiving postMessages from attackers](#how-do-you-avoid-receiving-postmessages-from-attackers) - -### How do you avoid receiving postMessages from attackers? - -To prevent receiving messages from attackers, always validate the `origin` property of the message and ensure it matches the trusted source. You can also check the message's content for additional security. - -Example: - -```javascript -window.addEventListener('message', (event) => { - if (event.origin !== 'https://trusted.com') { - return; - } - // Process message -}); -``` - -**Tags**: advanced, JavaScript, Security - - - ---- - -## [How do you call the constructor of a parent class](#how-do-you-call-the-constructor-of-a-parent-class) - -### How do you call the constructor of a parent class? - -In JavaScript, you can call the constructor of a parent class using the `super()` keyword inside the child class’s constructor. This allows the child class to inherit properties and methods from the parent class. - -Example: - -```javascript -class Animal { - constructor(name) { - this.name = name; - } -} -class Dog extends Animal { - constructor(name, breed) { - super(name); // Calls the parent constructor - this.breed = breed; - } -} -const dog = new Dog('Rex', 'German Shepherd'); -console.log(dog.name); // Rex -``` - -**Tags**: basic, JavaScript, classes - - - ---- - -## [How do you capture browser back button](#how-do-you-capture-browser-back-button) - -### How do you capture browser back button? - -You can capture the browser's back button by listening to the `popstate` event. This event is triggered when the active history entry changes. - -Example: - -```javascript -window.addEventListener('popstate', function(event) { - console.log('Back button was pressed'); -}); -``` - -**Tags**: intermediate, JavaScript, Browser Events - - - ---- - -## [How do you change the style of a HTML element](#how-do-you-change-the-style-of-a-html-element) - -### How do you change the style of a HTML element? - -You can change the style of an HTML element by accessing its `style` property in JavaScript. - -Example: - -```javascript -const element = document.getElementById('myElement'); -element.style.backgroundColor = 'blue'; -``` - -**Tags**: basic, JavaScript, DOM manipulation - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7456849197690621217](https://www.tiktok.com/@jsmentoring/photo/7456849197690621217) - ---- - -## [How do you check an object is a promise or not](#how-do-you-check-an-object-is-a-promise-or-not) - -### How do you check if an object is a promise or not? - -To check if an object is a promise, verify that it is an object with a `then` method that is a function. - -Example: - -```javascript -function isPromise(obj) { - return !!obj && typeof obj.then === 'function'; -} - -console.log(isPromise(Promise.resolve())); // Output: true -console.log(isPromise({})); // Output: false -``` - -**Tags**: intermediate, JavaScript, Promises - - - ---- - -## [How do you check if a key exists in an object](#how-do-you-check-if-a-key-exists-in-an-object) - -### How do you check if a key exists in an object? - -You can check if a key exists in an object using the `in` operator or the `hasOwnProperty()` method. - -```javascript -const obj = {name: 'John'}; -console.log('name' in obj); // true -console.log(obj.hasOwnProperty('name')); // true -``` - -**Tags**: basic, JavaScript, objects - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7455464658166680864](https://www.tiktok.com/@jsmentoring/photo/7455464658166680864) - ---- - -## [How do you check if a string starts with another string](#how-do-you-check-if-a-string-starts-with-another-string) - -### How do you check if a string starts with another string? - -You can use the `startsWith()` method to check if a string starts with a given substring. - -```javascript -const str = 'Hello World'; -console.log(str.startsWith('Hello')); // true -``` - -**Tags**: basic, JavaScript, string manipulation - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7455819349048315169](https://www.tiktok.com/@jsmentoring/photo/7455819349048315169) - ---- - -## [How do you check whether a string contains a substring](#how-do-you-check-whether-a-string-contains-a-substring) - -### How do you check whether a string contains a substring? - -To check if a string contains a substring, you can use the `includes()` method, which returns `true` if the substring is found. - -```javascript -const str = 'Hello World'; -console.log(str.includes('World')); // true -``` - -**Tags**: basic, JavaScript, string manipulation - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7457960152197614880](https://www.tiktok.com/@jsmentoring/photo/7457960152197614880) - ---- - -## [How do you check whether an array includes a particular value or not](#how-do-you-check-whether-an-array-includes-a-particular-value-or-not) - -### How do you check whether an array includes a particular value or not? - -In JavaScript, you can use the `includes()` method to check if an array contains a particular value. This method returns `true` if the array contains the specified element, and `false` otherwise. - -Example: - -```javascript -const arr = [1, 2, 3, 4, 5]; -console.log(arr.includes(3)); // true -console.log(arr.includes(6)); // false -``` - -**Tags**: basic, JavaScript, arrays - - - ---- - -## [How do you check whether an object can be extendable or not](#how-do-you-check-whether-an-object-can-be-extendable-or-not) - -### How do you check whether an object can be extendable or not? - -You can check whether an object is extensible (i.e., if new properties can be added) using the `Object.isExtensible()` method. This method returns `true` if the object is extensible, and `false` if it is not. - -Example: - -```javascript -const obj = {}; -console.log(Object.isExtensible(obj)); // true -Object.preventExtensions(obj); -console.log(Object.isExtensible(obj)); // false -``` - -**Tags**: basic, JavaScript, objects - - - ---- - -## [How do you combine two or more arrays](#how-do-you-combine-two-or-more-arrays) - -### How do you combine two or more arrays? - -You can combine two or more arrays in JavaScript using methods like `concat()` or the spread operator (`...`). - -Example using `concat()`: - -```javascript -let arr1 = [1, 2]; -let arr2 = [3, 4]; -let combined = arr1.concat(arr2); -console.log(combined); // Output: [1, 2, 3, 4] -``` - -**Tags**: basic, JavaScript, Arrays - - - ---- - -## [How do you compare scalar arrays](#how-do-you-compare-scalar-arrays) - -### How do you compare scalar arrays? - -To compare scalar arrays (arrays with primitive data types) in JavaScript, you need to check if both arrays have the same length and if each element is equal. You can do this using loops or `Array.prototype.every()`. - -Example: - -```javascript -const arr1 = [1, 2, 3]; -const arr2 = [1, 2, 3]; -const areArraysEqual = arr1.length === arr2.length && arr1.every((val, index) => val === arr2[index]); -console.log(areArraysEqual); // true -``` - -**Tags**: intermediate, JavaScript, arrays - - - ---- - -## [How do you compare two date objects](#how-do-you-compare-two-date-objects) - -### How do you compare two date objects? - -To compare two date objects, you can use `getTime()` method, which returns the time value in milliseconds. - -```javascript -const date1 = new Date('2024-12-01'); -const date2 = new Date('2024-12-01'); -console.log(date1.getTime() === date2.getTime()); // true -``` - -**Tags**: basic, JavaScript, date and time - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7455822418272062752](https://www.tiktok.com/@jsmentoring/photo/7455822418272062752) - ---- - -## [How do you convert character to ASCII code](#how-do-you-convert-character-to-ascii-code) - -### How do you convert character to ASCII code? - -In JavaScript, you can convert a character to its ASCII code using the `charCodeAt()` method. This method returns the Unicode (ASCII) value of the character at the specified index. - -Example: - -```javascript -let char = 'A'; -console.log(char.charCodeAt(0)); // Output: 65 -``` - -**Tags**: basic, JavaScript, String Manipulation - - - ---- - -## [How do you convert date to another timezone in javascript](#how-do-you-convert-date-to-another-timezone-in-javascript) - -### How do you convert date to another timezone in javascript? - -You can use libraries like `moment.js` or the `Intl.DateTimeFormat` API to convert dates to different time zones. - -Example with `Intl.DateTimeFormat`: - -```javascript -const date = new Date(); -const formatter = new Intl.DateTimeFormat('en-US', { - timeZone: 'America/New_York', - hour: 'numeric', - minute: 'numeric' -}); -console.log(formatter.format(date)); -``` - -**Tags**: basic, JavaScript, date manipulation - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7457198473176190241](https://www.tiktok.com/@jsmentoring/photo/7457198473176190241) - ---- - -## [How do you copy properties from one object to other](#how-do-you-copy-properties-from-one-object-to-other) - -### How do you copy properties from one object to other? - -You can copy properties from one object to another using `Object.assign()` or the spread operator. - -Example using `Object.assign()`: - -```javascript -const obj1 = { name: 'John' }; -const obj2 = Object.assign({}, obj1); -console.log(obj2); // { name: 'John' } -``` -Example using the spread operator: - -```javascript -const obj2 = { ...obj1 }; -console.log(obj2); // { name: 'John' } -``` - -**Tags**: basic, JavaScript, objects - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7458032154656673056](https://www.tiktok.com/@jsmentoring/photo/7458032154656673056) - ---- - -## [How do you create an array with some data](#how-do-you-create-an-array-with-some-data) - -### How do you create an array with some data? - -You can create an array in JavaScript using array literals or the `Array` constructor. The simplest way is to use square brackets `[]` and add elements inside. - -Example: - -```javascript -let arr = [1, 2, 3, 4, 5]; -console.log(arr); // Output: [1, 2, 3, 4, 5] -``` - -**Tags**: basic, JavaScript, Arrays - - - ---- - -## [How do you create an infinite loop](#how-do-you-create-an-infinite-loop) - -### How do you create an infinite loop? - -An infinite loop occurs when a loop condition always evaluates to `true`, causing the loop to run forever. Be cautious when creating infinite loops to avoid freezing your program. - -Example: - -```javascript -while (true) { - console.log('This is an infinite loop'); -} -``` - -**Tags**: intermediate, JavaScript, Loops - - - ---- - -## [How do you create an object with prototype](#how-do-you-create-an-object-with-prototype) - -### How do you create an object with prototype? - -You can create an object with a prototype using `Object.create()`. This allows you to specify an existing object to serve as the prototype for the new object. - -Example: - -```javascript -const person = { greet() { console.log('Hello'); } }; -const student = Object.create(person); -student.greet(); // 'Hello' -``` - -**Tags**: basic, JavaScript, objects - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7458574988463983904](https://www.tiktok.com/@jsmentoring/photo/7458574988463983904) - ---- - -## [How do you create copy to clipboard button](#how-do-you-create-copy-to-clipboard-button) - -### How do you create copy to clipboard button? - -You can create a 'copy to clipboard' button using the `document.execCommand('copy')` method. However, modern browsers prefer using the `Clipboard API` for better security and compatibility. - -Example using `Clipboard API`: - -```javascript -let copyButton = document.querySelector('#copyButton'); -let textToCopy = document.querySelector('#textToCopy'); - -copyButton.addEventListener('click', () => { - navigator.clipboard.writeText(textToCopy.textContent) - .then(() => { console.log('Text copied to clipboard!'); }) - .catch(err => { console.log('Failed to copy text:', err); }); -}); -``` - -**Tags**: intermediate, JavaScript, DOM - - - ---- - -## [How do you create custom HTML element?](#how-do-you-create-custom-html-element) - -### How do you create custom HTML element? - -You can create a custom HTML element using the `customElements.define` method. Here's an example: - -```javascript -class MyElement extends HTMLElement { - constructor() { - super(); - this.innerHTML = '

Hello, Custom Element!

'; - } -} - -customElements.define('my-element', MyElement); - -// Usage in HTML: -// -``` - -This defines a new custom element `` which can be used like a standard HTML tag. - -**Tags**: advanced, JavaScript, Web Components - - - ---- - -## [How do you create polyfills for map, filter and reduce methods?](#how-do-you-create-polyfills-for-map-filter-and-reduce-methods) - -### How do you create polyfills for `map`, `filter`, and `reduce` methods? - -#### `map` Polyfill: -```javascript -Array.prototype.myMap = function(callback) { - const result = []; - for (let i = 0; i < this.length; i++) { - if (this.hasOwnProperty(i)) { - result.push(callback(this[i], i, this)); - } - } - return result; -}; -``` - -#### `filter` Polyfill: -```javascript -Array.prototype.myFilter = function(callback) { - const result = []; - for (let i = 0; i < this.length; i++) { - if (this.hasOwnProperty(i) && callback(this[i], i, this)) { - result.push(this[i]); - } - } - return result; -}; -``` - -#### `reduce` Polyfill: -```javascript -Array.prototype.myReduce = function(callback, initialValue) { - let accumulator = initialValue; - for (let i = 0; i < this.length; i++) { - if (this.hasOwnProperty(i)) { - accumulator = callback(accumulator, this[i], i, this); - } - } - return accumulator; -}; -``` - -**Tags**: advanced, JavaScript, Polyfills - - - ---- - -## [How do you create self string using special characters](#how-do-you-create-self-string-using-special-characters) - -### How do you create self string using special characters? - -To create a string that includes special characters like quotes, newlines, or tabs, you can use escape sequences. For example, `\'` for a single quote, `\"` for a double quote, `\\` for a backslash, `\n` for a newline, and `\t` for a tab. - -Example: - -```javascript -let str = 'This is a string with special characters: \' \" \\ \n'; -console.log(str); -``` - -**Tags**: basic, JavaScript, Strings - - - ---- - -## [How do you create specific number of copies of a string](#how-do-you-create-specific-number-of-copies-of-a-string) - -### How do you create specific number of copies of a string? - -You can repeat a string a specific number of times using the `repeat()` method. - -Example: - -```javascript -let str = 'Hello '; -let repeatedStr = str.repeat(3); -console.log(repeatedStr); // Output: 'Hello Hello Hello ' -``` - -**Tags**: basic, JavaScript, String Manipulation - - - ---- - -## [How do you create your own bind method using either call or apply method?](#how-do-you-create-your-own-bind-method-using-either-call-or-apply-method) - -### How do you create your own bind method using either call or apply method? - -You can create a custom `bind` method by using `call` or `apply` to explicitly set the `this` context. - -Example: - -```javascript -Function.prototype.customBind = function(context, ...args) { - const fn = this; - return function(...innerArgs) { - return fn.apply(context, [...args, ...innerArgs]); - }; -}; - -function greet(greeting, name) { - console.log(`${greeting}, ${name}!`); -} - -const boundGreet = greet.customBind(null, 'Hello'); -boundGreet('Alice'); // 'Hello, Alice!' -``` - -**Tags**: advanced, JavaScript, Functions - - - ---- - -## [How do you declare namespace](#how-do-you-declare-namespace) - -### How do you declare namespace? - -In JavaScript, namespaces are not natively supported, but you can simulate them using objects or modules. By declaring an object, you can encapsulate your functions and variables to avoid polluting the global scope. - -Example using objects as namespaces: - -```javascript -const MyNamespace = { - myFunction: function() { console.log('Hello!'); }, - myVariable: 42 -}; -MyNamespace.myFunction(); // 'Hello!' -``` - -**Tags**: intermediate, JavaScript, namespaces - - - ---- - -## [How do you decode an URL](#how-do-you-decode-an-url) - -### How do you decode an URL? - -You can use `decodeURIComponent()` to decode a URL-encoded string back into its original format. - -Example: - -```javascript -const encodedURL = 'https%3A%2F%2Fexample.com%2F%3Fname%3DJohn%20Doe'; -const decodedURL = decodeURIComponent(encodedURL); -console.log(decodedURL); // 'https://example.com/?name=John Doe' -``` - -**Tags**: basic, JavaScript, encoding - - - ---- - -## [How do you define instance and non-instance properties](#how-do-you-define-instance-and-non-instance-properties) - -### How do you define instance and non-instance properties? - -- **Instance Properties**: - - Defined within the constructor using `this`. - - Specific to each instance of a class. - -- **Non-Instance Properties**: - - Defined on the class itself (static properties). - - Shared across all instances. - -Example: - -```javascript -class Example { - constructor(name) { - this.name = name; // Instance property - } - static type = 'Example'; // Non-instance property -} -console.log(Example.type); // Output: 'Example' -``` - -**Tags**: intermediate, JavaScript, OOP - - - ---- - -## [How do you define JSON arrays](#how-do-you-define-json-arrays) - -### How do you define JSON arrays? - -JSON arrays are defined in the same way as JavaScript arrays, but they must be in a string format. They can hold any type of data (strings, numbers, objects, etc.). - -Example: - -```json -["apple", "banana", "cherry"] -``` - -**Tags**: basic, JavaScript, JSON - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7456895653067672864](https://www.tiktok.com/@jsmentoring/photo/7456895653067672864) - ---- - -## [How do you define multiline strings](#how-do-you-define-multiline-strings) - -### How do you define multiline strings? - -You can define multiline strings using template literals (backticks). - -```javascript -const str = `Hello -World`; -console.log(str); // 'Hello -World' -``` - -**Tags**: basic, JavaScript, string manipulation - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7456061031811419424](https://www.tiktok.com/@jsmentoring/photo/7456061031811419424) - ---- - -## [How do you define multiple properties on an object](#how-do-you-define-multiple-properties-on-an-object) - -### How do you define multiple properties on an object? - -You can define multiple properties on an object in JavaScript by using either object literal syntax or `Object.defineProperties()` method. - -Example using object literal: - -```javascript -const person = { name: 'John', age: 30 }; -``` - -Example using `Object.defineProperties()`: - -```javascript -const person = {}; -Object.defineProperties(person, { - name: { value: 'John', writable: true }, - age: { value: 30, writable: true } -}); -console.log(person); -``` - -**Tags**: basic, JavaScript, objects - - - ---- - -## [How do you define property on Object constructor](#how-do-you-define-property-on-object-constructor) - -### How do you define property on Object constructor? - -You can define properties on an object constructor by adding properties directly within the constructor function. - -Example: - -```javascript -function Person(name, age) { - this.name = name; - this.age = age; -} -const person = new Person('John', 30); -console.log(person.name); // 'John' -console.log(person.age); // 30 -``` - -**Tags**: basic, JavaScript, objects - - - ---- - -## [How do you detect a browser language preference](#how-do-you-detect-a-browser-language-preference) - -### How do you detect a browser language preference? - -You can detect the browser’s preferred language using `navigator.language` or `navigator.languages`. - -Example: - -```javascript -console.log(navigator.language); // 'en-US' -``` - -**Tags**: basic, JavaScript, browser features - - - ---- - -## [How do you detect a mobile browser](#how-do-you-detect-a-mobile-browser) - -### How do you detect a mobile browser? - -You can detect a mobile browser by checking the `navigator.userAgent` string for keywords like 'mobile', 'Android', or 'iPhone'. - -Example: - -```javascript -if (/Mobi/.test(navigator.userAgent)) { - console.log('Mobile browser detected'); -} -``` - -**Tags**: basic, JavaScript, mobile detection - - - ---- - -## [How do you detect a mobile browser without regexp](#how-do-you-detect-a-mobile-browser-without-regexp) - -### How do you detect a mobile browser without regexp? - -You can detect a mobile browser without using regular expressions by checking for specific properties in `navigator` or `window` objects, such as `navigator.platform` or `window.innerWidth`. - -Example: - -```javascript -if (navigator.platform.indexOf('iPhone') !== -1) { - console.log('iPhone detected'); -} -``` - -**Tags**: basic, JavaScript, mobile detection - -**URL**: [https://www.tiktok.com/@jsmentoring/photo/7457202437292674337](https://www.tiktok.com/@jsmentoring/photo/7457202437292674337) - ---- - -## [How do you detect javascript disabled in the page](#how-do-you-detect-javascript-disabled-in-the-page) - -### How do you detect JavaScript disabled in the page? - -You can detect JavaScript being disabled by using `