Levels (4)
Themes (218)
- indexeddb
- db
- storage
- cookie
- options
- local storage
- session storage
- differences
- delete
- remove
- postmessage
- communication
- iframe
- closures
- javascript
- scope
- modules
- es6
- classes
- object oriented programming
- benefits
- organization
- hoisting
- variables
- service worker
- offline
- caching
- dom manipulation
- elements
- persistence
- database
- memoization
- performance
- prototype
- inheritance
- higher order functions
- currying
- functions
- object
- map
- pure function
- functional programming
- let keyword
- arrow functions
- let
- var
- git
- bisect
- debugging
- lambda expressions
- splice
- array
- slice
- objects
- creation
- rebase
- version control
- reflog
- revert
- storage event
- event handler
- web storage
- sessionstorage
- localstorage
- cookies
- http
- sse
- real time communication
- web technologies
- callback hell
- asynchronous
- callbacks
- asynchronous programming
- callback function
- promise
- web workers
- dom
- browser support
- server sent events
- notifications
- promises
- strict mode
- type coercion
- event handling
- keyboard events
- history api
- security
- data types
- operators
- type checking
- best practices
- events
- syntax
- math
- strings
- algorithm
- numbers
- arrays
- bit manipulation
- namespaces
- data structures
- validation
- web navigation
- date
- url manipulation
- console
- browser events
- string manipulation
- date and time
- date manipulation
- loops
- web components
- polyfills
- encoding
- oop
- json
- browser features
- mobile detection
- page features
- environment
- iterables
- http requests
- data formats
- forms
- html
- internationalization
- number formatting
- printing
- regular expressions
- destructuring
- typescript
- iteration
- fetch api
- web apis
- ui manipulation
- features
- language concepts
- node js
- control flow
- general knowledge
- collections
- linked lists
- event loop
- v8 engine
- optimization
- rxjs
- control structures
- observables
- errors
- generators
- engines
- execution context
- window properties
- proxy
- page load
- design patterns
- web development
- logical operators
- ajax
- statements
- concurrency model
- iterators
- binary data
- tools
- browser
- runtime
- standards
- global objects
- memory
- libraries
- frameworks
- memory management
- declarations
- script tag
- comparison
- array methods
- timers
- compatibility
- string methods
- eval
- conditionals
- spread operator
- timing
- error handling
- programming paradigms
- history
- language features
- concurrency
- jest
- testing
- assertions
- setup and teardown
- mocks
- snapshot testing
- async testing
- test management
- command line
- implementation
- operations
- time complexity
- protractor
- ui testing
- setup
- commands
- locators
- waiting
- verification
- alerts
- headless testing
- async await
- express js
- algorithms
- weakmap
- v8
- devtools
- animation
- multithreading
- async
Tutorials with Videos (300)
- What is IndexedDB
- What are the options in a cookie
- Differences between cookie, local storage and session storage
- How do you delete a cookie
- What is a post message
- What are closures
- What are modules
- What are classes in ES6
- Why do you need modules
- What is Hoisting
- What is scope in javascript
- What is a service worker
- How do you manipulate with DOM element
- How do you reuse information across service worker restarts
- What is IndexedDB
- What is memoization
- What is memoization
- What is a Prototype Chain in JavaScript?
- What is a higher order function
- What is the currying function
- How do you compare Object and Map
- What is a pure function
- What is a Prototype Chain in JavaScript?
- What is the purpose of the let keyword
- Arrow func?
- What is the difference between let and var
- What is git bisect command?
- What are lambda expressions or arrow functions?
- What is the difference between == and === operators?
- What is the purpose of the array splice method?
- What is the difference between slice and splice?
- 5 Ways to Create Objects in JavaScript?
- What is git rebase command?
- What is git reflog command?
- What is git revert command?
- What is a storage event and its event handler?
- What are the methods available on session storage?
- How do you access web storage?
- What is the main difference between localStorage and sessionStorage?
- Why do you need a Cookie?
- What is a Cookie?
- What is web storage?
- What Are Server-Sent Events (SSE)?
- What Is a Callback Hell?
- Importance of Callbacks in Javascript?
- What is a callback function in javascript?
- What Are the Three States of a Promise?
- Why do you need a promise?
- What is a promise?
- What are the restrictions of web workers on DOM?
- Give an example of a web worker?
- How do you check web storage browser support?
- Why do you need web storage?
- How Do You Receive Server-Sent Event Notifications?
- What Is a Callback in Callback?
- What Is Promise Chaining in JavaScript?
- What Are the Main Rules of Promise in JavaScript?
- What Are the Events Available for Server-Sent Events?
- How Do You Check Browser Support for Server-Sent Events?
- What Is
Promise.all
in JavaScript? - What Is the Purpose of the
race
Method in Promises? - What Is Strict Mode in JavaScript?
- What Is the Purpose of Double Exclamation in JavaScript?
- How Do You Declare Strict Mode in JavaScript?
- How Do You Detect Caps Lock Key Turned On or Not?
- How Do You Access History in JavaScript?
- What Is the Difference Between
window
anddocument
in JavaScript? - What Is the Purpose of Double Exclamation in JavaScript?
- What Is
eval
in JavaScript? - What Is the
null
Value in JavaScript? - What Is the
undefined
Property in JavaScript? - What Is the Purpose of the
delete
Operator in JavaScript? - What Is the
typeof
Operator in JavaScript? - What Is
isNaN
in JavaScript? - What are the differences between undeclared and undefined variables
- What are global variables
- What are the problems with global variables
- What is NaN property
- What is an event flow
- What is event bubbling
- Can I add getters and setters using defineProperty method
- Can I use reserved words as identifiers
- Can we define properties for functions
- Can you apply chaining on conditional operator
- Can you give an example of when you really need a semicolon
- Can you write a random integers function to print integers within a range
- Check for Anagrams
- Check if a String is a Palindrome
- Does JavaScript supports namespace
- Does the const variable make the value immutable
- Find the First Non-Repeating Character
- Find the Most Frequent Element in an Array
- Give an example usage of rangeOverflow property
- How can you get the list of keys of any object
- How do get query string values in javascript
- How do get the timezone offset from date
- How do I modify the url without reloading the page
- How do you add a key value pair in javascript
- How do you assign default values to variables
- How do you call the constructor of a parent class
- How do you change the style of a HTML element
- How do you check if a key exists in an object
- How do you check if a string starts with another string
- How do you check whether a string contains a substring
- How do you check whether an array includes a particular value or not
- How do you compare scalar arrays
- How do you compare two date objects
- How do you convert date to another timezone in javascript
- How do you copy properties from one object to other
- How do you create an infinite loop
- How do you create an object with prototype
- How do you decode an URL
- How do you define JSON arrays
- How do you define multiline strings
- How do you define multiple properties on an object
- How do you define property on Object constructor
- How do you detect a browser language preference
- How do you detect a mobile browser without regexp
- How do you detect javascript disabled in the page
- How do you determine if an object is sealed or not
- How do you determine two values same or not using object
- How do you determine whether object is frozen or not
- How do you display the current date in javascript
- How do you encode an URL
- How do you extend classes
- How do you find min and max value in an array
- How do you find min and max values without Math functions
- How do you find operating system details
- How do you generate random integers
- How do you get enumerable key and value pairs
- How do you get metadata of a module
- How do you get property descriptors of an object
- How do you get the current url with javascript
- How do you get the image width and height using JS
- How do you get the prototype of an object
- How do you load CSS and JS files dynamically
- How do you loop through or enumerate javascript object
- How do you make asynchronous HTTP request
- How do you make first letter of the string in an uppercase
- How do you make synchronous HTTP request
- How do you parse JSON string
- How do you perform form validation using JavaScript
- How do you perform form validation without JavaScript
- How do you perform language specific date and time formatting
- How do you prevent an object to extend
- How do you print numbers with commas as thousand separators
- How do you print the contents of web page
- How do you redirect new page in javascript
- How do you reverse an array
- How do you search a string for a pattern
- How do you set prototype of one object to another
- How do you sort elements in an array
- How do you submit a form using JavaScript
- How do you swap variables in destructuring assignment
- How do you test for an empty object
- How do you trim a string at the beginning or ending
- How do you trim a string in javascript
- How do you validate an email in javascript
- How do you write multi-line strings in template literals
- How does synchronous iteration works
- How to convert string to title case with javascript
- How to get the value from get parameters
- How to set the cursor to wait
- Is enums feature available in JavaScript
- Is it recommended to use eval
- Is JavaScript a case-sensitive language
- Is JavaScript a compiled or interpreted language
- Is the !-- notation represents a special operator
- Is there any relation between Java and JavaScript
- List down some of the features of ES6
- List down the collection of methods available on WeakMap
- List down the collection of methods available on WeakSet
- What are break and continue statements
- What are default parameters
- What are default values in destructuring assignment
- What are dynamic imports
- What are enhanced object literals
- What are events
- What are javascript accessors
- What are JS labels
- What are modifiers in regular expression
- What are nesting templates
- What are primitive data types
- What are PWAs
- What are raw strings
- What are regular expression patterns
- What are tagged templates
- What are the advantages of Getters and Setters
- What are the advantages of Minification
- What are the advantages of module loaders
- What are the advantages of TypeScript over JavaScript
- What are the applications of assign method
- What are the applications of seal method
- What are the available constraint validation DOM properties
- What are the benefits of initializing variables
- What are the benefits of keeping declarations at the top
- What are the bitwise operators available in javascript
- What are the common tools used for Minification
- What are the conventions to be followed for the usage of switch case
- What are the differences between JavaScript and TypeScript
- What are the differences between Obfuscation and Encryption
- What are the differences between WeakMap and Map
- What are the differences between WeakSet and Set
- What are the different error names from error object
- What are the different methods to find HTML elements in DOM
- What are the different ways to make an object non-extensible
- What are the DOM methods available for constraint validation
- What are the function parameter rules
- What are the list of validity properties
- What are the properties of Intl object
- What are the properties used to get size of window
- What are the pros and cons of promises over callbacks
- What are the recommendations to create new object
- What are the steps involved in return false usage
- What are the syntax rules of JSON
- What are the tools or techniques used for debugging JavaScript code
- What are the two types of loops in javascript
- What are the use cases for dynamic imports
- What are the various URL properties of location object
- What are the ways to execute javascript after page load
- What are typed arrays
- What are various operators supported by javascript
- What happens If I pass string type for getPrototype method
- What happens if you write constructor more than once in a class
- What is a comma operator
- What is a conditional operator in javascript
- What is a constructor method
- What is a debugger statement
- What is a decorator
- What is a freeze method
- What is a polyfill
- What is a proxy object
- What is a RegExp object
- What is a Regular Expression
- What is a rest parameter
- What is a WeakMap
- What is a WeakSet
- What is an anonymous function
- What is an app shell model
- What is an arguments object
- What is an empty statement and purpose of it
- What is an enum
- What is an error object
- What is an event delegation
- What is an event queue
- What is an Intl object
- What is an Iterator
- What is an object initializer
- What is an Unary operator
- What is BOM
- What is call stack
- What is destructuring assignment
- What is ECMAScript
- What is ES6
- What is event capturing
- What is JSON
- What is MEAN in JavaScript
- What is microtask
- What is Minification
- What Is Obfuscation in JavaScript
- What is optional chaining?
- What is same-origin policy
- What is the advantage of a comma operator
- What is the difference between an attribute and a property
- What is the difference between document load and DOMContentLoaded events
- What is the difference between Java and JavaScript
- What is the difference between native, host and user objects
- What is the difference between uneval and eval
- What is the main difference between Object.values and Object.entries method
- What is the need of tree shaking
- What is the output of below spread operator array
- What is the output of the following for loops
- What is the precedence order between local and global variables
- What is the purpose JSON stringify
- What is the purpose of breakpoints in debugging
- What is the purpose of clearInterval method
- What is the purpose of clearTimeout method
- What is the purpose of compareFunction while sorting arrays
- What is the purpose of exec method
- What is the purpose of seal method
- What is the purpose of switch-case
- What is the purpose of uneval
- What is the purpose of void 0
- What is the use of preventDefault method
- What is the use of setInterval
- What is the use of setTimeout
- What is the use of stopPropagation method
- What is the way to find the number of parameters expected by a function
- What is tree shaking
- What is V8 JavaScript engine
- What would be the result of 1+2+'3'
- When you get a syntax error
- Who created JavaScript
- Why do I need to use freeze method
- Why do we call javascript as dynamic language
- Why do you need JSON
- Why do you need to avoid with statement
- Why is JavaScript treated as Single threaded
- How to catch errors in callbacks
- What are weak references?
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Both Object
and Map
are key-value stores in JavaScript, but they have differences:
- Key Types:
Map
can use any data type as a key, whileObject
keys are always converted to strings. - Iteration:
Map
preserves the order of insertion, whileObject
does not guarantee order. - 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
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
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
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
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
The primary differences between let
and var
are their scoping rules and hoisting behavior:
- Scope:
let
is block-scoped, whilevar
is function-scoped. - Hoisting: Both
let
andvar
are hoisted to the top of their scope, butlet
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
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
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
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, JavaScript
URL: https://www.tiktok.com/@jsmentoring/photo/7446055928723508512
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
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
In JavaScript, objects can be created in various ways. The five most common methods are:
- Object Literal:
const obj = {}
- Object Constructor:
const obj = new Object()
- Object.create():
const obj = Object.create(null)
- Class Syntax:
class MyClass { constructor() {} }
- Factory Functions:
function createObject() { return {}}
Tags: basic, objects, creation, JavaScript
URL: https://www.tiktok.com/@jsmentoring/photo/7445448146685136161
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
A simple web worker example:
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
To check if a browser supports web storage, you can check if localStorage
or sessionStorage
is available:
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
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
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:
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
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
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.
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
The main rules of Promises in JavaScript are:
- A promise can be in one of three states: pending, fulfilled, or rejected.
- A promise can only transition from pending to fulfilled or rejected, and cannot change back.
- You can attach
.then()
to handle success and.catch()
for errors.
Tags: intermediate, Promises, JavaScript
URL: https://www.tiktok.com/@jsmentoring/photo/7449057432086580513
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
To check if the browser supports Server-Sent Events, you can check for the EventSource
object:
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
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.
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
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.
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
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.
'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
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.
console.log(!!'string'); // true
console.log(!!0); // false
Tags: basic, JavaScript, type coercion
URL: https://www.tiktok.com/@jsmentoring/photo/7449429710985022753
To declare strict mode in JavaScript, simply add 'use strict';
at the beginning of a script or a function.
'use strict';
// Code here will be executed in strict mode
Tags: basic, JavaScript, strict mode
URL: https://www.tiktok.com/@jsmentoring/photo/7449490448533507361
To detect whether Caps Lock is on, you can use the keydown
or keypress
event and check the event.getModifierState('CapsLock')
property.
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
You can access the browser history using the window.history
object. This allows you to manipulate the session history (navigate, go back, forward, etc.).
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
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.
console.log(window); // Browser window
console.log(document); // HTML document
Tags: basic, JavaScript, DOM
URL: https://www.tiktok.com/@jsmentoring/photo/7449755076182215968
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.
console.log(!!'text'); // true
console.log(!!null); // false
Tags: basic, JavaScript, type coercion
URL: https://www.tiktok.com/@jsmentoring/photo/7449813378895203617
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.
eval('console.log("Hello, World!")'); // Logs 'Hello, World!'
Tags: intermediate, JavaScript, security
URL: https://www.tiktok.com/@jsmentoring/photo/7449833381975559446
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.
let x = null;
console.log(x); // null
Tags: basic, JavaScript, data types
URL: https://www.tiktok.com/@jsmentoring/photo/7449876086793489696
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.
let x;
console.log(x); // undefined
Tags: basic, JavaScript, data types
URL: https://www.tiktok.com/@jsmentoring/photo/7450179747931278624
The delete
operator is used to remove a property from an object or an element from an array.
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
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.
console.log(typeof 'Hello'); // string
console.log(typeof 123); // number
Tags: basic, JavaScript, operators
URL: https://www.tiktok.com/@jsmentoring/photo/7450568773712497953
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.
console.log(isNaN(123)); // false
console.log(isNaN('Hello')); // true
Tags: basic, JavaScript, type checking
URL: https://www.tiktok.com/@jsmentoring/photo/7450774214459673888
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
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
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
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
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
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
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
Yes, you can add getters and setters using Object.defineProperty()
. This allows you to define custom getter and setter methods for specific properties.
Example:
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
URL: https://www.tiktok.com/@jsmentoring/photo/7459755921485434144
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
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:
let x = 10;
let x = 20; // Error: Cannot redeclare block-scoped variable 'x'
Tags: intermediate, JavaScript, Variables
No, you cannot use reserved words (such as let
, class
, function
, etc.) as identifiers (variable names, function names, etc.) in JavaScript.
Example:
let let = 5; // SyntaxError: Unexpected token 'let'
Tags: basic, JavaScript, syntax
URL: https://www.tiktok.com/@jsmentoring/photo/7457212868161850657
Yes, functions in JavaScript are objects, so you can define properties for them.
function myFunc() {}
myFunc.property = 'value';
console.log(myFunc.property); // 'value'
Tags: basic, JavaScript, functions
URL: https://www.tiktok.com/@jsmentoring/photo/7456170349391023393
Yes, you can chain multiple conditional operators together to evaluate multiple conditions in a single expression.
Example:
const result = (age >= 18) ? 'Adult' : (age >= 13) ? 'Teen' : 'Child';
Tags: basic, JavaScript, operators
URL: https://www.tiktok.com/@jsmentoring/photo/7458016862446570785
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:
return { key: 'value' }; // Requires semicolon
Tags: basic, JavaScript, syntax
URL: https://www.tiktok.com/@jsmentoring/photo/7457679188732939553
You can create a function that generates random integers within a specified range.
Example:
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
An anagram is a word or phrase formed by rearranging the letters of another, using all the original letters exactly once.
- Remove any non-alphanumeric characters and convert both strings to lowercase.
- Check if the lengths of the two strings are the same. If not, they cannot be anagrams.
- Count the frequency of each character in the first string.
- Compare the character counts with the second string by decrementing the counts. If any count becomes negative or mismatches, the strings are not anagrams.
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
A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding the number itself).
- Initialize a variable to store the sum of divisors.
- Iterate from 1 to half of the number.
- For each divisor, add it to the sum.
- If the sum equals the original number, return
true
, otherwise returnfalse
.
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
To check if a number is prime, verify that it is greater than 1 and divisible only by 1 and itself.
- Check if the number is less than or equal to 1; if so, return false.
- Iterate through numbers from 2 to the square root of the number.
- If the number is divisible by any of these, return false.
- If no divisors are found, return true.
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
A palindrome is a word, phrase, or sequence that reads the same backward as forward.
- Remove all non-alphanumeric characters and convert the string to lowercase to handle case sensitivity.
- Use two pointers: one starting at the beginning and the other at the end of the string.
- Compare characters at the two pointers. If they differ, the string is not a palindrome.
- Move the pointers closer to the center and repeat the comparison.
- If all characters match, the string is a palindrome.
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
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).
- Count the frequency of each character in the string.
- Check how many characters have an odd frequency.
- If more than one character has an odd frequency, return false; otherwise, return true.
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
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.
- Concatenate the first string with itself.
- Check if the second string is a substring of the concatenated string.
- If it is, return
true
; otherwise, returnfalse
.
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
To check if an array is sorted, compare each element with the next one to ensure it is in the correct order.
- Iterate through the array and compare each element with the next.
- If any element is greater than the next one, the array is not sorted.
- If no such element is found, return true; otherwise, return false.
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
To check if two strings are palindromes of each other, reverse one string and compare it with the other string.
- Reverse one of the strings.
- Compare the reversed string with the other string.
- If they are equal, return true, indicating that they are palindromes of each other.
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
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.
- Initialize a counter variable to 0.
- Repeatedly perform the operation
n & (n - 1)
to clear the least significant 1 bit ofn
. - Increment the counter for each operation.
- Return the counter.
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
To count the occurrences of an element in an array, iterate through the array and keep track of how many times the element appears.
- Initialize a counter variable to 0.
- Iterate through the array and check if each element matches the target element.
- Increment the counter for each match.
- Return the counter.
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
To count the vowels in a string, iterate through the string and check if each character is a vowel.
- Normalize the string by converting it to lowercase to handle case insensitivity.
- Define a set or array containing all vowel characters (
a, e, i, o, u
). - Iterate through the string and count characters that match any vowel.
- Return the total count of vowels.
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
To count the number of words in a string, split the string by spaces and count the resulting elements.
- Split the string by spaces into an array of words.
- Filter out any empty strings from the array.
- Return the length of the array.
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
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:
let obj = {};
console.log(Object.getPrototypeOf(obj)); // Output: [object Object]
Tags: intermediate, JavaScript, Objects
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:
const MyNamespace = {
myFunction: function() { console.log('Hello!'); },
myVariable: 42
};
MyNamespace.myFunction(); // 'Hello!'
Tags: intermediate, JavaScript, namespaces
URL: https://www.tiktok.com/@jsmentoring/photo/7464760458570911008
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:
let mixin = {
greet() { console.log('Hello!'); }
};
let obj = Object.assign({}, mixin);
obj.greet(); // Output: 'Hello!'
Tags: advanced, JavaScript, Object-Oriented Programming
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:
const arr = [1, 2, 3];
arr.push(4); // Works fine
arr = [4, 5, 6]; // Error: Assignment to constant variable
Tags: intermediate, JavaScript, Variables
URL: https://www.tiktok.com/@jsmentoring/photo/7470295229015264544
To find all pairs that sum to a specific target, use a hash set to track the complements of each element.
- Initialize an empty set to store elements.
- Iterate through the array and calculate the complement (target - current element).
- If the complement exists in the set, add the pair to the result.
- Otherwise, add the current element to the set.
- Return the list of pairs.
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
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.
- Initialize an empty set to store the numbers.
- Iterate through the array and for each number, check if the complement (target - number) is already in the set.
- If the complement exists, add the pair to the result array.
- If the complement doesn't exist, add the current number to the set.
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
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.
- Initialize an empty set to store numbers.
- Iterate through the array and for each element, check if the complement (target - current element) is in the set.
- If the complement exists, add the pair to the result array.
- If not, add the current element to the set.
- Return the array of pairs.
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
To find all prime numbers within a given range, use the Sieve of Eratosthenes algorithm to efficiently find primes.
- Create a boolean array
isPrime
where each index represents a number. - Set all values to
true
except for 0 and 1. - Starting from 2, mark all multiples of each prime as
false
. - Return the indices that are still
true
as the prime numbers.
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
To find all prime numbers in an array, check each number in the array to see if it is prime.
- Define a helper function
isPrime
to check if a number is prime. - Iterate through the array, calling
isPrime
on each element. - Collect the prime numbers and return them.
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
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.
- Initialize an empty array to store the subsets.
- Iterate over the range from 0 to
2^n - 1
. - For each number in the range, use its binary representation to decide which elements to include in the subset.
- Return the array of subsets.
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
To find all substrings of a string, iterate through all possible starting and ending indices to extract substrings.
- Initialize an empty array to store substrings.
- Iterate through the string with two nested loops: one for the starting index and one for the ending index.
- Extract the substring for each pair of indices and add it to the result array.
- Return the array of substrings.
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
To find common characters in two strings, use a frequency map for each string and compare the characters.
- Create a frequency map for each string to count the occurrences of each character.
- Compare the frequency maps to find common characters.
- Return the list of common characters.
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
To find the longest common prefix among an array of strings, compare characters from each string in the array.
- Initialize the first string in the array as the common prefix.
- Iterate through the rest of the strings, updating the common prefix by comparing it with each string.
- If no common prefix is found, return an empty string.
- Return the final common prefix.
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
To find duplicate elements in an array, use a set to track the elements you've seen as you iterate through the array.
- Initialize an empty set to store unique elements.
- Iterate through the array and check if each element is already in the set.
- If it is, add it to the result array.
- Return the array of duplicates.
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
To find duplicates without using extra space, you can modify the array in-place.
- Iterate through the array and use the value of each element as an index.
- If the value at that index is negative, it means the element has been seen before, so it is a duplicate.
- If the value at that index is positive, make it negative to mark it as visited.
- Return the duplicates.
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
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.
- If the number is less than or equal to 1, return
false
. - Check for divisibility by all numbers from 2 to the square root of the number.
- If any number divides evenly, return
false
. Otherwise, returntrue
.
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
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.
- Concatenate the second string with itself.
- Check if the first string is a substring of the concatenated string.
- Return true if it is a substring, false otherwise.
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
To find the largest palindrome in an array, iterate through the array and check each element to see if it is a palindrome.
- Iterate through the array and check if each element is a palindrome.
- Keep track of the largest palindrome found.
- Return the largest palindrome.
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
To find the missing number in a sequential array, calculate the expected sum and subtract the actual sum of the array.
- Calculate the sum of numbers from 1 to n using the formula
n * (n + 1) / 2
. - Calculate the sum of the elements in the array.
- Subtract the actual sum from the expected sum to find the missing number.
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
To find the average of an array, sum all the elements in the array and then divide the sum by the number of elements.
- Initialize a variable to store the sum of the array elements.
- Iterate through the array and add each element to the sum.
- Divide the sum by the length of the array to get the average.
- Return the average.
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
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.
- Convert the first array into a set.
- Iterate through the second array and check if each element exists in the set.
- If it does, add it to the result array.
- Return the result array.
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
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.
- Create a set from the first array to store unique elements.
- Iterate through the second array and check if each element is present in the set.
- If an element is found in both arrays, add it to the result array.
- Return the array of common elements.
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
To find the difference between two arrays, use a set to track elements that are in one array but not the other.
- Convert one array into a set for efficient lookup.
- Iterate through the second array and add elements that are not in the set to the result array.
- Return the resulting array of differences.
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
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.
- Create an empty set to store elements.
- Iterate through the array.
- If the element is already in the set, return it as the duplicate.
- If the element is not in the set, add it to the set.
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
To find duplicate elements in an array, you can use a frequency map or set to track the elements that have already been encountered.
- Create a set to store elements you've seen.
- Iterate through the array and check if an element is already in the set.
- If it is, add it to the result array.
- If not, add it to the set.
- Return the result array with duplicates.
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
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.
- Initialize an empty set to track numbers.
- Iterate through the array, and for each element, check if it already exists in the set.
- If it does, return that element as the duplicate.
- If it does not, add the element to the set.
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
To find the first index of an element in an array, you can use the indexOf
method.
- Use the
indexOf
method to search for the element in the array. - If the element is found, return its index.
- If the element is not found, return
-1
.
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
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.
- Iterate through the array and move each number to its correct position (i.e.,
arr[i] = i + 1
). - After rearranging, find the first index where the value is not equal to
index + 1
. - Return
index + 1
as the first missing positive integer.
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
To find the first non-repeating character in a string, you can use a frequency counter to track character occurrences.
- Create an empty object to store character frequencies.
- Iterate through the string and count occurrences of each character by updating the object.
- Iterate through the string again and check the frequency of each character in the object.
- Return the first character with a frequency of 1.
- If no non-repeating character is found, return
null
.
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
To find the first repeated character in a string, use a frequency counter to track character occurrences.
- Initialize an empty set to track characters as you iterate through the string.
- For each character, check if it already exists in the set.
- If it does, return the character as the first repeated character.
- If no repeated character is found, return
null
.
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
To find the first repeated character in a string, use a set to track characters that have been seen.
- Initialize an empty set to store characters.
- Iterate through the string, checking if each character has already been seen in the set.
- If a character is found in the set, return it as the first repeated character.
- If no repeated character is found, return
null
.
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
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.
- Initialize an empty set to track seen characters.
- Iterate through the string.
- If a character is already in the set, return it as the first repeating character.
- If not, add it to the set.
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
To find the first repeating element in an array, you can use a set to keep track of the elements you've already seen.
- Initialize an empty set to store the elements.
- Iterate through the array, checking if each element is in the set.
- If it is, return the element as the first repeating one.
- If no repeating element is found, return
null
.
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
To find the GCD of two numbers, you can use the Euclidean algorithm.
- If
b
is 0, returna
as the GCD. - Otherwise, call the function recursively with
b
anda % b
as the arguments. - Repeat until the second number becomes 0.
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
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.
- Sort the array in descending order.
- Return the element at index K-1.
- If K is larger than the length of the array, return
null
.
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
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.
- Select a pivot element from the array.
- Partition the array into two subarrays: one with elements smaller than the pivot, and one with elements larger.
- If the Kth element is in the smaller subarray, repeat the process with that subarray.
- If the Kth element is in the larger subarray, repeat the process with that subarray.
- Return the Kth smallest element.
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
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.
- Initialize a variable to store the largest even number, starting with a value like
-Infinity
. - Iterate through the array and check if each element is even.
- If the element is even and larger than the current largest even number, update the largest even number.
- Return the largest even number.
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
To find the largest number in an array, iterate through the array and keep track of the largest number.
- Initialize a variable to store the largest number with a small value (e.g.,
-Infinity
). - Iterate through the array and compare each element to the current largest number.
- Update the largest number whenever a larger element is found.
- Return the largest number.
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
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.
- Iterate through the array and check if each element is a palindrome.
- For each palindrome, compare it with the current largest palindrome.
- Return the largest palindrome found.
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
To find the largest product of two numbers in an array, iterate through the array while keeping track of the two largest numbers.
- Initialize two variables,
max1
andmax2
, to negative infinity. - Iterate through the array, updating
max1
andmax2
as you find larger numbers. - Return the product of
max1
andmax2
.
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
To find the largest sum of a consecutive subarray, you can use Kadane's Algorithm.
- Initialize two variables:
maxSum
andcurrentSum
, both set to the first element of the array. - Iterate through the array, updating
currentSum
to the larger of the current element or the sum ofcurrentSum
and the current element. - Update
maxSum
to the larger ofmaxSum
andcurrentSum
. - Return
maxSum
.
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
To find the largest sum of a contiguous subarray, use Kadane's Algorithm, which helps to find the maximum sum efficiently in linear time.
- Initialize two variables,
maxCurrent
andmaxGlobal
, to the first element of the array. - Iterate through the array starting from the second element.
- For each element, update
maxCurrent
to the maximum of the current element or the sum of the current element andmaxCurrent
. - If
maxCurrent
exceedsmaxGlobal
, updatemaxGlobal
. - Return
maxGlobal
as the result.
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
To find the longest common prefix among a set of strings, iterate through the strings character by character and check if they match.
- Sort the array of strings.
- Compare the first and the last string character by character.
- The characters that match are the common prefix.
- Return the common prefix.
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
To find the longest increasing subarray, iterate through the array and track the length of the current increasing subarray.
- Initialize variables to track the current and maximum subarray lengths.
- Iterate through the array and check if the current element is greater than the previous one.
- If the current element is greater, increment the current subarray length.
- If not, compare the current subarray length with the maximum length and reset the current subarray length.
- Return the maximum subarray length.
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
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.
- Initialize an array
dp
wheredp[i]
stores the length of the longest increasing subsequence that ends at indexi
. - Iterate through the array, and for each element, check all previous elements to see if it can form a longer subsequence.
- Return the maximum value in
dp
.
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
To find the longest palindrome in a string, expand around each character and check for the longest palindromic substring.
- Initialize variables to store the start and end indices of the longest palindrome.
- For each character in the string, expand outwards while the characters on both sides match.
- Track the maximum length of palindrome found during the expansion.
- Return the longest palindromic substring.
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
To find the longest substring without repeating characters, use a sliding window technique with two pointers to track the current substring.
- Initialize two pointers, one for the start and one for the end of the window.
- Move the end pointer to expand the window and add characters to a set.
- If a character is already in the set, move the start pointer to shrink the window and remove the character from the set.
- Keep track of the maximum window length.
- Return the maximum length of the substring.
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
To find the longest word in a sentence, split the sentence into words and compare their lengths.
- Remove any non-alphanumeric characters except spaces to clean the input.
- Split the sentence into an array of words using spaces as the delimiter.
- Iterate through the array, keeping track of the longest word encountered.
- Return the longest word. If there are multiple words of the same length, return the first one encountered.
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
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.
- Initialize a candidate element and a count variable.
- Iterate through the array, updating the count based on the current element.
- If the count becomes 0, set the current element as the new candidate.
- After the first pass, the candidate will be the majority element if it exists.
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
To find the majority element in an array (an element that appears more than n/2 times), use the Boyer-Moore Voting Algorithm.
- Initialize a
candidate
variable and acount
variable. - Iterate through the array. If the count is 0, set the current element as the
candidate
and setcount
to 1. If the current element is thecandidate
, increment the count, otherwise decrement it. - Return the
candidate
.
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
To find the maximum number in an array, iterate through the array and keep track of the largest value encountered.
- Initialize a variable to store the maximum value. Start with the first element of the array.
- Iterate through the array, comparing each element with the current maximum.
- If an element is greater than the current maximum, update the maximum.
- Return the maximum value after completing the iteration.
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
To find the median of an array, first sort the array and then find the middle element.
- Sort the array in ascending order.
- If the array has an odd length, return the middle element.
- If the array has an even length, return the average of the two middle elements.
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
To find the middle element of an array, calculate the index of the middle and return the corresponding element.
- If the array length is odd, the middle element is the element at index
Math.floor(arr.length / 2)
. - If the array length is even, you can choose either of the two middle elements.
- Return the middle element.
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
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.
- Calculate the expected sum of the numbers from 1 to n using the formula
n * (n + 1) / 2
. - Calculate the actual sum of the elements in the array.
- Subtract the actual sum from the expected sum to find the missing number.
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
To find the mode (most frequent element) of an array, use an object to count the occurrences of each element.
- Initialize an empty object to store counts of elements.
- Iterate through the array, updating the count for each element.
- Find the element with the highest count.
- Return the element with the highest frequency.
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
To find the most frequent element in an array, you can use a frequency counter to track occurrences of each element.
- Create an empty object to store element frequencies.
- Iterate through the array and count occurrences of each element by updating the object.
- Keep track of the element with the highest frequency while iterating through the object.
- Return the element with the highest frequency.
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
To find the second largest element in an array, iterate through the array and keep track of the largest and second largest elements.
- Initialize two variables,
largest
andsecondLargest
, with a very small value (e.g.,-Infinity
). - Iterate through the array, updating
largest
andsecondLargest
as needed. - Return the second largest element.
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
To find the second largest number in an array, iterate through the array and keep track of the largest and second largest elements.
- Initialize two variables,
first
andsecond
, to-Infinity
. - Iterate through the array, and for each element, check if it is greater than
first
. - If it is, update
second
tofirst
and then updatefirst
to the current element. - If the element is smaller than
first
but greater thansecond
, updatesecond
. - Return
second
as the second largest element.
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
To find the second smallest number in an array, iterate through the array while keeping track of the smallest and second smallest values.
- Initialize two variables to store the smallest and second smallest values, starting with
Infinity
. - Iterate through the array and update the smallest and second smallest values as you go.
- Return the second smallest number.
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
To find the smallest element in an array, iterate through the array and keep track of the smallest element.
- Initialize a variable to store the smallest element with a large value (e.g.,
Infinity
). - Iterate through the array and compare each element to the current smallest value.
- Update the smallest value whenever a smaller element is found.
- Return the smallest value.
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
To find the smallest number in an array, iterate through the array and keep track of the smallest value encountered.
- Initialize a variable to store the smallest value, starting with the first element of the array.
- Iterate through the array and compare each element with the current smallest value.
- If an element is smaller than the current smallest, update the smallest value.
- Return the smallest value after completing the iteration.
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
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.
- Initialize a variable
unique
to 0. - Iterate through the array, applying XOR to each element and the
unique
variable. - The result will be the unique element in the array.
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
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
.
- Create a frequency map to count the occurrences of each element in the array.
- Filter the array to return elements that appear only once.
- Return the filtered result.
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
To find unique characters in a string, you can use a set to keep track of characters you've seen.
- Initialize an empty set.
- Iterate through the string and add each character to the set.
- Return the characters in the set as a string.
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
To find unique elements in an array, you can use a set to filter out duplicates.
- Convert the array to a set, which automatically removes duplicates.
- Convert the set back to an array to get the unique elements.
- Return the unique array.
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
Automatic Semicolon Insertion (ASI) can lead to unexpected behavior when a semicolon is inserted incorrectly.
Example:
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:
function test() {
return {
key: 'value'
};
}
console.log(test()); // { key: 'value' }
Tags: advanced, JavaScript, Syntax
The rangeOverflow
property checks if the value entered in an input field exceeds the maximum value specified by the max
attribute.
Example:
<input type="number" id="age" min="18" max="100">
<script>
const input = document.getElementById('age');
if (input.validity.rangeOverflow) {
console.log('Value exceeds the maximum limit!');
}
</script>
Tags: intermediate, JavaScript, DOM, validation
URL: https://www.tiktok.com/@jsmentoring/photo/7465086711412854048
You can use Object.keys()
to get an array of the object's keys (property names).
Example:
const person = { name: 'John', age: 30 };
const keys = Object.keys(person);
console.log(keys); // ['name', 'age']
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7459041201086319905
To get query string values, you can use the URLSearchParams
object.
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
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:
const date = new Date();
const offset = date.getTimezoneOffset();
console.log(offset); // Logs the timezone offset in minutes
Tags: basic, JavaScript, Date
URL: https://www.tiktok.com/@jsmentoring/photo/7468056195111144737
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
:
history.pushState(null, '', '/new-url');
console.log(window.location.href); // '/new-url'
Tags: intermediate, JavaScript, URL manipulation
URL: https://www.tiktok.com/@jsmentoring/photo/7465055907018263841
You can style the console output by using %c
in the console.log
method:
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
To add a key-value pair to an object, you can simply assign a value to a new key.
const obj = {};
obj.name = 'John';
console.log(obj); // { name: 'John' }
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7456001248484003104
You can assign default values to variables using the ||
operator or by using destructuring assignment.
const name = userInput || 'Default Name';
Tags: basic, JavaScript, variables
URL: https://www.tiktok.com/@jsmentoring/photo/7456018568077937953
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:
window.addEventListener('message', (event) => {
if (event.origin !== 'https://trusted.com') {
return;
}
// Process message
});
Tags: advanced, JavaScript, Security
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:
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
URL: https://www.tiktok.com/@jsmentoring/photo/7463621028627959072
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:
window.addEventListener('popstate', function(event) {
console.log('Back button was pressed');
});
Tags: intermediate, JavaScript, Browser Events
You can change the style of an HTML element by accessing its style
property in JavaScript.
Example:
const element = document.getElementById('myElement');
element.style.backgroundColor = 'blue';
Tags: basic, JavaScript, DOM manipulation
URL: https://www.tiktok.com/@jsmentoring/photo/7456849197690621217
To check if an object is a promise, verify that it is an object with a then
method that is a function.
Example:
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
You can check if a key exists in an object using the in
operator or the hasOwnProperty()
method.
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
You can use the startsWith()
method to check if a string starts with a given substring.
const str = 'Hello World';
console.log(str.startsWith('Hello')); // true
Tags: basic, JavaScript, string manipulation
URL: https://www.tiktok.com/@jsmentoring/photo/7455819349048315169
To check if a string contains a substring, you can use the includes()
method, which returns true
if the substring is found.
const str = 'Hello World';
console.log(str.includes('World')); // true
Tags: basic, JavaScript, string manipulation
URL: https://www.tiktok.com/@jsmentoring/photo/7457960152197614880
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:
const arr = [1, 2, 3, 4, 5];
console.log(arr.includes(3)); // true
console.log(arr.includes(6)); // false
Tags: basic, JavaScript, arrays
URL: https://www.tiktok.com/@jsmentoring/photo/7464755906626981152
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:
const obj = {};
console.log(Object.isExtensible(obj)); // true
Object.preventExtensions(obj);
console.log(Object.isExtensible(obj)); // false
Tags: basic, JavaScript, objects
You can combine two or more arrays in JavaScript using methods like concat()
or the spread operator (...
).
Example using concat()
:
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
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:
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
URL: https://www.tiktok.com/@jsmentoring/photo/7466925859719449889
To compare two date objects, you can use getTime()
method, which returns the time value in milliseconds.
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
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:
let char = 'A';
console.log(char.charCodeAt(0)); // Output: 65
Tags: basic, JavaScript, String Manipulation
You can use libraries like moment.js
or the Intl.DateTimeFormat
API to convert dates to different time zones.
Example with Intl.DateTimeFormat
:
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
You can copy properties from one object to another using Object.assign()
or the spread operator.
Example using Object.assign()
:
const obj1 = { name: 'John' };
const obj2 = Object.assign({}, obj1);
console.log(obj2); // { name: 'John' }
Example using the spread operator:
const obj2 = { ...obj1 };
console.log(obj2); // { name: 'John' }
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7458032154656673056
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:
let arr = [1, 2, 3, 4, 5];
console.log(arr); // Output: [1, 2, 3, 4, 5]
Tags: basic, JavaScript, Arrays
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:
while (true) {
console.log('This is an infinite loop');
}
Tags: intermediate, JavaScript, Loops
URL: https://www.tiktok.com/@jsmentoring/photo/7469423331989622048
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:
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
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
:
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
You can create a custom HTML element using the customElements.define
method. Here's an example:
class MyElement extends HTMLElement {
constructor() {
super();
this.innerHTML = '<p>Hello, Custom Element!</p>';
}
}
customElements.define('my-element', MyElement);
// Usage in HTML:
// <my-element></my-element>
This defines a new custom element <my-element>
which can be used like a standard HTML tag.
Tags: advanced, JavaScript, Web Components
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;
};
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;
};
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
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:
let str = 'This is a string with special characters: \' \" \\ \n';
console.log(str);
Tags: basic, JavaScript, Strings
You can repeat a string a specific number of times using the repeat()
method.
Example:
let str = 'Hello ';
let repeatedStr = str.repeat(3);
console.log(repeatedStr); // Output: 'Hello Hello Hello '
Tags: basic, JavaScript, String Manipulation
You can create a custom bind
method by using call
or apply
to explicitly set the this
context.
Example:
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
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:
const MyNamespace = {
myFunction: function() { console.log('Hello!'); },
myVariable: 42
};
MyNamespace.myFunction(); // 'Hello!'
Tags: intermediate, JavaScript, namespaces
You can use decodeURIComponent()
to decode a URL-encoded string back into its original format.
Example:
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
URL: https://www.tiktok.com/@jsmentoring/photo/7459171752271269153
-
Instance Properties:
- Defined within the constructor using
this
. - Specific to each instance of a class.
- Defined within the constructor using
-
Non-Instance Properties:
- Defined on the class itself (static properties).
- Shared across all instances.
Example:
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
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:
["apple", "banana", "cherry"]
Tags: basic, JavaScript, JSON
URL: https://www.tiktok.com/@jsmentoring/photo/7456895653067672864
You can define multiline strings using template literals (backticks).
const str = `Hello
World`;
console.log(str); // 'Hello
World'
Tags: basic, JavaScript, string manipulation
URL: https://www.tiktok.com/@jsmentoring/photo/7456061031811419424
You can define multiple properties on an object in JavaScript by using either object literal syntax or Object.defineProperties()
method.
Example using object literal:
const person = { name: 'John', age: 30 };
Example using Object.defineProperties()
:
const person = {};
Object.defineProperties(person, {
name: { value: 'John', writable: true },
age: { value: 30, writable: true }
});
console.log(person);
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7462833020551187745
You can define properties on an object constructor by adding properties directly within the constructor function.
Example:
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
URL: https://www.tiktok.com/@jsmentoring/photo/7459536638176234785
You can detect the browser’s preferred language using navigator.language
or navigator.languages
.
Example:
console.log(navigator.language); // 'en-US'
Tags: basic, JavaScript, browser features
URL: https://www.tiktok.com/@jsmentoring/photo/7459014680225303841
You can detect a mobile browser by checking the navigator.userAgent
string for keywords like 'mobile', 'Android', or 'iPhone'.
Example:
if (/Mobi/.test(navigator.userAgent)) {
console.log('Mobile browser detected');
}
Tags: basic, JavaScript, mobile detection
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:
if (navigator.platform.indexOf('iPhone') !== -1) {
console.log('iPhone detected');
}
Tags: basic, JavaScript, mobile detection
URL: https://www.tiktok.com/@jsmentoring/photo/7457202437292674337
You can detect JavaScript being disabled by using <noscript>
HTML tag. This tag contains content that will only be displayed if JavaScript is disabled.
Example:
<noscript>
JavaScript is disabled in your browser.
</noscript>
Tags: basic, JavaScript, page features
URL: https://www.tiktok.com/@jsmentoring/photo/7457508448763120928
In JavaScript, you can detect whether a value is primitive or non-primitive by using the typeof
operator for primitives and checking for null
or using instanceof
for non-primitives.
- Primitive types:
undefined
,null
,boolean
,number
,string
,symbol
,bigint
- Non-primitive types:
object
,array
,function
Example:
let value = 42;
console.log(typeof value); // Output: 'number'
let obj = {};
console.log(typeof obj); // Output: 'object'
Tags: intermediate, JavaScript, Data Types
You can use Object.isSealed()
to check if an object is sealed. A sealed object cannot have new properties added to it, but its existing properties can be modified.
Example:
const person = { name: 'John' };
Object.seal(person);
console.log(Object.isSealed(person)); // true
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7459001015438822689
You can use Object.is()
to determine if two values are the same. It checks both values for equality, including NaN
and -0
.
Example:
console.log(Object.is(5, 5)); // true
console.log(Object.is(5, '5')); // false
console.log(Object.is(NaN, NaN)); // true
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7457684535661137185
You can use Object.isFrozen()
to check if an object is frozen. A frozen object cannot have its properties modified, added, or removed.
Example:
const person = { name: 'John' };
Object.freeze(person);
console.log(Object.isFrozen(person)); // true
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7457681827478785312
You can disable right-click by listening for the contextmenu
event and preventing its default behavior.
Example:
document.addEventListener('contextmenu', function(event) {
event.preventDefault();
console.log('Right-click is disabled');
});
Tags: intermediate, JavaScript, DOM
You can use the console.table()
method to display data in a tabular format. This is especially useful when dealing with arrays of objects.
Example:
let arr = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 }
];
console.table(arr);
Tags: intermediate, JavaScript, Console
To display the current date, you can use the Date
object.
const currentDate = new Date();
console.log(currentDate); // Displays the current date and time
Tags: basic, JavaScript, date and time
URL: https://www.tiktok.com/@jsmentoring/photo/7458949968116682016
There are multiple ways to empty an array in JavaScript. You can set its length to 0
, use splice()
, or create a new empty array.
Example:
let arr = [1, 2, 3];
arr.length = 0;
console.log(arr); // Output: []
Tags: basic, JavaScript, Arrays
You can use encodeURIComponent()
to encode individual components of a URL, such as query parameters.
Example:
const url = 'https://example.com/?name=John Doe';
const encodedURL = encodeURIComponent(url);
console.log(encodedURL); // 'https%3A%2F%2Fexample.com%2F%3Fname%3DJohn%20Doe'
Tags: basic, JavaScript, encoding
URL: https://www.tiktok.com/@jsmentoring/photo/7459156073719680289
In JavaScript, you can extend a class using the extends
keyword. This allows a subclass to inherit properties and methods from a parent class.
Example:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks`);
}
}
const dog = new Dog('Buddy');
dog.speak(); // 'Buddy barks'
Tags: intermediate, JavaScript, classes
URL: https://www.tiktok.com/@jsmentoring/photo/7466566601702133024
You can find the minimum and maximum values in an array using the Math.min()
and Math.max()
methods combined with the spread operator (...
).
Example:
const arr = [1, 2, 3, 4, 5];
console.log(Math.min(...arr)); // 1
console.log(Math.max(...arr)); // 5
Tags: basic, JavaScript, arrays
URL: https://www.tiktok.com/@jsmentoring/photo/7462491684585147681
You can find the minimum and maximum values in an array by manually iterating over the array and comparing each element.
Example:
const arr = [1, 2, 3, 4, 5];
let min = arr[0], max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < min) min = arr[i];
if (arr[i] > max) max = arr[i];
}
console.log(min); // 1
console.log(max); // 5
Tags: basic, JavaScript, arrays
URL: https://www.tiktok.com/@jsmentoring/photo/7462011912289570080
You can access the operating system details in JavaScript using navigator.platform
or navigator.userAgent
to detect the platform or OS of the user.
Tags: intermediate, JavaScript, environment
URL: https://www.tiktok.com/@jsmentoring/photo/7451589366285126944
You can flatten multi-dimensional arrays using the flat()
method in JavaScript. This method flattens an array up to a specified depth.
Example:
let arr = [1, [2, 3], [4, [5, 6]]];
let flattened = arr.flat(2);
console.log(flattened); // Output: [1, 2, 3, 4, 5, 6]
Tags: intermediate, JavaScript, Arrays
You can use Math.random()
and Math.floor()
to generate random integers.
Example:
const randomInt = Math.floor(Math.random() * 10); // Generates a random integer between 0 and 9
console.log(randomInt);
Tags: basic, JavaScript, math
URL: https://www.tiktok.com/@jsmentoring/photo/7456916623870512417
You can use Object.entries()
to get enumerable key-value pairs from an object. This method returns an array of arrays, where each sub-array contains a key-value pair.
Example:
const person = { name: 'John', age: 30 };
const entries = Object.entries(person);
console.log(entries); // [['name', 'John'], ['age', 30]]
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7458348252274920736
In JavaScript, modules can be inspected using the import.meta
object. This object provides metadata about the module, including its URL and other properties specific to the environment.
Example:
console.log(import.meta.url);
// Outputs the URL of the current module
Tags: basic, JavaScript, modules
URL: https://www.tiktok.com/@jsmentoring/photo/7462493057984761121
In JavaScript, you can use Object.getOwnPropertyDescriptor()
to get the descriptor of a specific property on an object. This descriptor contains details about the property such as whether it's writable, enumerable, or configurable.
Example:
const person = { name: 'John' };
const descriptor = Object.getOwnPropertyDescriptor(person, 'name');
console.log(descriptor);
// { value: 'John', writable: true, enumerable: true, configurable: true }
Tags: intermediate, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7466604525500042528
You can get the current URL of the page using window.location.href
.
console.log(window.location.href); // Outputs the current URL
Tags: basic, JavaScript, web navigation
URL: https://www.tiktok.com/@jsmentoring/photo/7458367254942502177
You can get the width and height of an image element using the width
and height
properties.
Example:
const img = document.getElementById('myImage');
console.log(img.width, img.height);
Tags: basic, JavaScript, DOM manipulation
URL: https://www.tiktok.com/@jsmentoring/photo/7457292452945268000
In JavaScript, you can get the prototype of an object using the Object.getPrototypeOf()
method. This method returns the prototype (i.e., the internal [[Prototype]]
property) of the specified object.
Example:
const person = { name: 'John' };
const prototype = Object.getPrototypeOf(person);
console.log(prototype); // Outputs the prototype of the object
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7463608944322186528
You can get the status of a checkbox by accessing its checked
property. This will return true
if the checkbox is checked, and false
otherwise.
Example:
let checkbox = document.getElementById('myCheckbox');
console.log(checkbox.checked); // Output: true/false
Tags: basic, JavaScript, DOM
To get unique values from an array, you can use Set
, which stores only unique values. You can also use filter()
and indexOf()
to remove duplicates.
Example:
let arr = [1, 2, 2, 3, 4, 4, 5];
let uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // Output: [1, 2, 3, 4, 5]
Tags: intermediate, JavaScript, Arrays
You can group and nest console output using console.group
and console.groupEnd
:
console.group('Outer Group');
console.log('Message in Outer Group');
console.group('Inner Group');
console.log('Message in Inner Group');
console.groupEnd();
console.groupEnd();
Output:
Outer Group
Message in Outer Group
Inner Group
Message in Inner Group
Tags: intermediate, JavaScript, Console
In modern browsers, you can simulate a zero timeout by using setTimeout
with a delay of 0
. However, it will be subject to the browser's throttling mechanism, especially in inactive tabs.
setTimeout(() => console.log('Executed after zero delay'), 0);
Tags: intermediate, JavaScript, Performance
To invoke JavaScript code inside an iframe from the parent page, you can access the iframe's contentWindow
property, which provides a reference to the iframe's window
object.
Example:
const iframe = document.getElementById('myIframe');
const iframeWindow = iframe.contentWindow;
iframeWindow.someFunction(); // Calls a function in the iframe
Tags: intermediate, JavaScript, iframe
You can list all properties of an object in JavaScript using methods like Object.keys()
, Object.getOwnPropertyNames()
, or for...in
loops.
Example using Object.keys()
:
const person = { name: 'John', age: 30 };
console.log(Object.keys(person)); // ['name', 'age']
Example using for...in
loop:
const person = { name: 'John', age: 30 };
for (let key in person) {
console.log(key); // name, age
}
Tags: intermediate, JavaScript, objects
You can dynamically load CSS and JavaScript files by creating link
and script
elements and appending them to the document's head
.
Example for loading a CSS file:
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'style.css';
document.head.appendChild(link);
Example for loading a JS file:
const script = document.createElement('script');
script.src = 'script.js';
document.body.appendChild(script);
Tags: intermediate, JavaScript, DOM manipulation
URL: https://www.tiktok.com/@jsmentoring/photo/7468342228621020448
You can loop through an object using for...in
or Object.keys()
combined with forEach()
.
const obj = {name: 'John', age: 30};
for (let key in obj) {
console.log(key, obj[key]);
}
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7455466200588389664
To make an object iterable, you need to implement the [Symbol.iterator]
method, which returns an iterator object.
Example:
const iterableObject = {
data: [1, 2, 3],
[Symbol.iterator]() {
let index = 0;
let data = this.data;
return {
next() {
return index < data.length
? { value: data[index++], done: false }
: { done: true };
}
};
}
};
for (let value of iterableObject) {
console.log(value); // Output: 1, 2, 3
}
Tags: advanced, JavaScript, Iterables
You can make an asynchronous HTTP request using XMLHttpRequest
with open()
and send()
methods, and setting the async
parameter to true
.
Example:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com', true);
xhr.send();
xhr.onload = function() {
console.log(xhr.responseText);
};
Tags: basic, JavaScript, HTTP requests
URL: https://www.tiktok.com/@jsmentoring/photo/7457281321589656864
To make the first letter uppercase, you can use the charAt()
method and toUpperCase()
along with slice()
.
const str = 'hello';
const result = str.charAt(0).toUpperCase() + str.slice(1);
console.log(result); // 'Hello'
Tags: basic, JavaScript, string manipulation
URL: https://www.tiktok.com/@jsmentoring/photo/7456035524420062497
You can make a synchronous HTTP request using XMLHttpRequest
with open()
and send()
methods, and setting the async
parameter to false
.
Example:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com', false);
xhr.send();
console.log(xhr.responseText);
Tags: basic, JavaScript, HTTP requests
URL: https://www.tiktok.com/@jsmentoring/photo/7457614380205739296
You can use forEach()
or a for
loop to iterate over an array and perform a mapping operation manually.
Example using forEach()
:
let arr = [1, 2, 3];
let result = [];
arr.forEach(item => result.push(item * 2));
console.log(result); // Output: [2, 4, 6]
Tags: intermediate, JavaScript, Arrays
You can parse a JSON string using the JSON.parse()
method, which converts the JSON string into a JavaScript object.
const obj = JSON.parse('{"name":"John"}');
console.log(obj.name); // John
Tags: basic, JavaScript, data formats
URL: https://www.tiktok.com/@jsmentoring/photo/7457955955557403937
Form validation in JavaScript can be performed by adding event listeners to the form elements and checking their values before submitting the form. You can use the onsubmit
event or validate individual fields using the oninput
or onchange
events.
Example:
const form = document.getElementById('myForm');
form.onsubmit = function(event) {
const email = document.getElementById('email').value;
if (!email.includes('@')) {
alert('Please enter a valid email address');
event.preventDefault();
}
};
Tags: intermediate, JavaScript, forms
URL: https://www.tiktok.com/@jsmentoring/photo/7464738741056294177
HTML5 provides built-in form validation features that do not require JavaScript. You can use attributes like required
, pattern
, minlength
, maxlength
, and type
to validate form fields.
Example:
<form>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<input type="submit">
</form>
Tags: intermediate, HTML, forms
URL: https://www.tiktok.com/@jsmentoring/photo/7463632026873122081
In JavaScript, you can use the Intl.DateTimeFormat
object to format dates and times according to a specific locale. It allows you to customize the date and time formatting styles (e.g., short, long, etc.) and even customize how individual date parts (like day, month, year) are displayed.
Example:
const date = new Date();
const formatter = new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
console.log(formatter.format(date)); // 'December 21, 2024'
Tags: basic, JavaScript, internationalization
URL: https://www.tiktok.com/@jsmentoring/photo/7460895683747286304
You can prevent an object from being extended (i.e., from adding new properties) using the Object.preventExtensions()
method. This method makes the object non-extensible.
Example:
const obj = { name: 'John' };
Object.preventExtensions(obj);
obj.age = 30; // Won't be added
console.log(obj); // { name: 'John' }
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7463226904930258209
To prevent promises from swallowing errors, ensure that you handle rejections using .catch()
or use try-catch
with async-await
syntax. Additionally, always return or throw errors explicitly.
Example:
Promise.resolve()
.then(() => { throw new Error('Error occurred'); })
.catch(error => console.error('Caught error:', error));
async function asyncFunction() {
try {
await Promise.reject('Error occurred');
} catch (error) {
console.error('Caught error:', error);
}
}
asyncFunction();
Tags: advanced, JavaScript, Promises
You can use the toLocaleString()
method to format numbers with commas as thousand separators.
Example:
const number = 1234567.89;
console.log(number.toLocaleString()); // '1,234,567.89'
Tags: basic, JavaScript, number formatting
URL: https://www.tiktok.com/@jsmentoring/photo/7467333374668049696
You can use the window.print()
method to print the contents of a web page.
Example:
window.print();
Tags: basic, JavaScript, printing
URL: https://www.tiktok.com/@jsmentoring/photo/7459302428265942305
To redirect to a new page in JavaScript, you can use window.location.href
or window.location.assign()
. Both methods will navigate the browser to the specified URL.
window.location.href = 'https://example.com';
Tags: basic, JavaScript, web navigation
URL: https://www.tiktok.com/@jsmentoring/photo/7453541079804169504
You can use the filter()
method to remove falsy values (e.g., false
, null
, undefined
, 0
, NaN
, ""
) from an array.
Example:
let arr = [0, 1, false, 2, '', 3, null];
let filteredArr = arr.filter(Boolean);
console.log(filteredArr); // Output: [1, 2, 3]
Tags: basic, JavaScript, Arrays
You can use the match()
method with a regular expression to return all matching substrings in a string. The g
flag in the regular expression allows the method to match all occurrences, not just the first one.
Example:
let str = 'abc123 def456 ghi789';
let matches = str.match(/\d+/g);
console.log(matches); // Output: ['123', '456', '789']
In this example, \d+
is a regular expression that matches one or more digits, and the g
flag ensures that all matches are returned in an array.
Tags: intermediate, JavaScript, Regular Expressions
Use the slice
method to create a shallow copy and then reverse the copy:
const originalArray = [1, 2, 3];
const reversedArray = originalArray.slice().reverse();
console.log(originalArray); // [1, 2, 3]
console.log(reversedArray); // [3, 2, 1]
Tags: intermediate, JavaScript, Arrays
You can reverse the order of elements in an array using the reverse()
method in JavaScript. This method modifies the original array in place.
Example:
const arr = [1, 2, 3];
arr.reverse();
console.log(arr); // [3, 2, 1]
Tags: basic, JavaScript, arrays
URL: https://www.tiktok.com/@jsmentoring/photo/7461767458592918816
You can use toFixed()
or Math.round()
to round numbers to a specified number of decimals.
Example:
let num = 5.6789;
let rounded = num.toFixed(2);
console.log(rounded); // Output: '5.68'
Tags: intermediate, JavaScript, Numbers
You can use the test()
method of the RegExp
object to search for a pattern in a string.
Example:
const regex = /\d+/;
console.log(regex.test('abc123')); // true
Tags: basic, JavaScript, regular expressions
URL: https://www.tiktok.com/@jsmentoring/photo/7456824435211816224
You can set the prototype of one object to another using the Object.setPrototypeOf()
method. This method allows you to change the prototype chain of an object.
Example:
const animal = { speak: function() { console.log('Animal speaks'); } };
const dog = {};
Object.setPrototypeOf(dog, animal);
dog.speak(); // Animal speaks
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7463628446049127712
You can sort elements in an array using the sort()
method in JavaScript. The sort()
method sorts the array in place, and you can pass a compare function to customize the sorting order.
Example:
const arr = [3, 1, 2];
arr.sort();
console.log(arr); // ['1', '2', '3']
arr.sort((a, b) => a - b);
console.log(arr); // [1, 2, 3]
Tags: basic, JavaScript, arrays
URL: https://www.tiktok.com/@jsmentoring/photo/7461738847261478177
You can submit a form in JavaScript using the submit()
method on the form element, like so:
document.getElementById('myForm').submit();
Tags: basic, JavaScript, forms
URL: https://www.tiktok.com/@jsmentoring/photo/7454702289975119136
You can swap the values of two variables using destructuring assignment. This eliminates the need for a temporary variable.
Example:
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b); // Output: 2 1
Tags: intermediate, JavaScript, Destructuring
URL: https://www.tiktok.com/@jsmentoring/photo/7472310346334620950
To check if an object is empty, you can use Object.keys()
and check if the length is zero.
const obj = {};
console.log(Object.keys(obj).length === 0); // true
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7455470039198682401
You can use the trimStart()
and trimEnd()
methods to remove whitespace from the beginning or the end of a string, respectively. Alternatively, trim()
removes whitespace from both ends.
Example:
let str = ' Hello World! ';
console.log(str.trimStart()); // Output: 'Hello World! '
console.log(str.trimEnd()); // Output: ' Hello World!'
Tags: basic, JavaScript, String Manipulation
URL: https://www.tiktok.com/@jsmentoring/photo/7473639282557652246
To remove whitespace from both ends of a string, use the trim()
method.
const str = ' Hello World ';
console.log(str.trim()); // 'Hello World'
Tags: basic, JavaScript, string manipulation
URL: https://www.tiktok.com/@jsmentoring/photo/7455853408113675552
In TypeScript, you can use JavaScript libraries by either importing them directly or by installing type definitions (if available). To import a JavaScript library, you can use the import
keyword or the require
function.
Example using import
:
import * as library from 'library';
Tags: intermediate, TypeScript, JavaScript
To validate an email in JavaScript, you can use a regular expression. A common pattern for basic email validation looks like this:
const email = 'test@example.com';
const regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
console.log(regex.test(email)); // true
Tags: basic, JavaScript, validation
URL: https://www.tiktok.com/@jsmentoring/photo/7456043510161067296
You can verify if a value is a number by using typeof
operator or Number.isNaN()
method.
Example using typeof
:
let value = 25;
console.log(typeof value === 'number'); // Output: true
Example using Number.isNaN()
:
let value = NaN;
console.log(Number.isNaN(value)); // Output: true
Tags: basic, JavaScript, Data Types
You can create multi-line strings in template literals by simply including line breaks within the backticks. This is much easier than using traditional string concatenation.
Example:
let multilineString = `This is a
multi-line
string.`;
console.log(multilineString);
// Output:
// This is a
// multi-line
// string.
Tags: intermediate, JavaScript, Strings
URL: https://www.tiktok.com/@jsmentoring/photo/7469863541760101664
Synchronous iteration means that each iteration of the loop or iterator occurs one after the other. The code execution waits for the current iteration to complete before moving on to the next one. This is the default behavior in most loops like for
, while
, and forEach
.
Example:
const arr = [1, 2, 3];
arr.forEach(item => console.log(item)); // Output: 1, 2, 3
Tags: basic, JavaScript, iteration
URL: https://www.tiktok.com/@jsmentoring/photo/7460552114478140705
You can cancel a fetch request using an AbortController
. The AbortController
allows you to abort one or more fetch requests.
Example:
let controller = new AbortController();
let signal = controller.signal;
fetch('https://api.example.com/data', { signal: signal })
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.log('Fetch aborted', err));
// To cancel the request
controller.abort();
Tags: advanced, JavaScript, Fetch API
You can convert a string to title case by splitting the string into words, capitalizing the first letter of each word, and then joining them back together.
Example:
function toTitleCase(str) {
return str.replace(/\b(\w)/g, char => char.toUpperCase());
}
console.log(toTitleCase('hello world')); // 'Hello World'
Tags: basic, JavaScript, string manipulation
URL: https://www.tiktok.com/@jsmentoring/photo/7457578972889615648
To detect if a function is called as a constructor, check the value of this
. In a constructor call, this
refers to the newly created object.
Example:
function MyFunction() {
if (!(this instanceof MyFunction)) {
throw new Error('Must be called with new');
}
console.log('Called as constructor');
}
new MyFunction(); // Works
MyFunction(); // Throws error
Tags: advanced, JavaScript, Functions
Use the matchMedia
method with the (prefers-color-scheme)
media query.
Example:
const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
if (isDarkMode) {
console.log('Dark mode is enabled');
} else {
console.log('Light mode is enabled');
}
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
mediaQuery.addEventListener('change', event => {
if (event.matches) {
console.log('Dark mode activated');
} else {
console.log('Light mode activated');
}
});
Tags: intermediate, JavaScript, Web APIs
Use the length
property of a function.
Example:
function example(a, b, c) {}
console.log(example.length); // 3
Note: Default parameters and rest parameters are not counted in the length
property.
Tags: intermediate, JavaScript, Functions
You can get the value of a GET parameter in the URL using URLSearchParams
.
Example:
const urlParams = new URLSearchParams(window.location.search);
const value = urlParams.get('param');
console.log(value); // Logs the value of 'param' from the URL
Tags: intermediate, JavaScript, URL manipulation
URL: https://www.tiktok.com/@jsmentoring/photo/7467643182990249249
Use an Unary Operator like !
or +
before the function to execute it immediately:
Example:
!function() {
console.log('IIFE invoked!');
}();
+function() {
console.log('Another IIFE invoked!');
}();
Tags: advanced, JavaScript, Functions
You can remove line breaks using the replace()
method with a regular expression that targets line breaks (
or
).
Example:
let str = 'Hello
World
!';
let cleanedStr = str.replace(/[
]+/g, ' ');
console.log(cleanedStr); // Output: 'Hello World !'
Tags: basic, JavaScript, Strings
You can change the cursor to a wait (or busy) cursor using CSS by setting the cursor
property to wait
.
Example:
document.body.style.cursor = 'wait'; // Changes cursor to wait
// After a task is done
document.body.style.cursor = 'default'; // Changes cursor back to default
Tags: basic, JavaScript, UI manipulation
URL: https://www.tiktok.com/@jsmentoring/photo/7469414701550603553
Before ES2022, await
could only be used inside async
functions. To achieve similar behavior outside of async
functions, you could use:
-
Immediately Invoked Async Function Expression (IIAFE):
(async () => { const result = await fetch('https://api.example.com'); console.log(result); })();
-
Promise Handling with
.then()
:fetch('https://api.example.com') .then(response => response.json()) .then(data => console.log(data));
With ES2022, await
can be used in top-level code in modules.
Tags: advanced, JavaScript, Asynchronous Programming
You can verify if a variable is an array using Array.isArray()
method. It returns true
if the value is an array, otherwise false
.
Example:
const arr = [1, 2, 3];
console.log(Array.isArray(arr)); // true
const obj = { key: 'value' };
console.log(Array.isArray(obj)); // false
Tags: basic, JavaScript, Data Types
JavaScript does not have built-in support for enum
types like some other programming languages (e.g., TypeScript, C++). However, you can simulate enums
in JavaScript using objects or const
variables.
Example using an object:
const Colors = {
RED: 'red',
GREEN: 'green',
BLUE: 'blue'
};
console.log(Colors.RED); // 'red'
Alternatively, TypeScript provides a native enum
feature.
Tags: intermediate, JavaScript, features
URL: https://www.tiktok.com/@jsmentoring/photo/7464749346089749792
Yes, you can add CSS to console messages using %c
placeholder in the console.log()
method. This allows you to style the output text in the console.
Example:
console.log('%cHello, world!', 'color: red; font-size: 20px;');
Tags: intermediate, JavaScript, Console
Yes, you can debug HTML elements directly in the console by using console.dir()
to inspect their properties and methods. Additionally, you can use console.log()
to output HTML elements or other objects for debugging purposes.
Example:
let element = document.querySelector('div');
console.dir(element);
Tags: intermediate, JavaScript, Debugging
It is generally not recommended to use eval()
in JavaScript due to security risks and performance concerns. eval()
executes code passed as a string, which can be exploited by attackers.
Tags: basic, JavaScript, security
URL: https://www.tiktok.com/@jsmentoring/photo/7456751494948293920
Yes, JavaScript is a case-sensitive language. For example, variable
and Variable
would be considered two different identifiers.
Tags: basic, JavaScript, language concepts
URL: https://www.tiktok.com/@jsmentoring/photo/7454353440626445601
JavaScript is an interpreted language. It is executed line by line by the JavaScript engine in the browser, rather than being compiled beforehand like C or Java.
Tags: basic, JavaScript, language concepts
URL: https://www.tiktok.com/@jsmentoring/photo/7454351953959652640
JavaScript runs in the browser and is typically faster for client-side operations, especially for DOM manipulation and interactions. However, server-side scripts (e.g., PHP, Node.js) can be faster for processing large datasets or performing complex operations due to server-side resources.
Tags: intermediate, JavaScript, Performance
No, Node.js is not completely single-threaded. While the event loop and most of the JavaScript code execution are single-threaded, Node.js uses multiple threads for I/O operations and certain asynchronous tasks. For example, it uses the libuv library to handle file system operations and network requests in parallel.
However, JavaScript code execution in Node.js runs on a single thread, making it lightweight and efficient for handling I/O-bound tasks.
Tags: intermediate, Node.js, JavaScript
The postMessage
API is secure if used correctly. However, it can be vulnerable if not properly handled, as it can expose data to unintended origins. It is crucial to validate the targetOrigin
and avoid using wildcards to ensure secure messaging.
Example:
window.postMessage('message', 'https://example.com');
Tags: advanced, JavaScript, Security
The postMessage
API is asynchronous. The message is posted to the message queue and handled later, allowing the rest of the script to continue executing without blocking.
Example:
window.postMessage('message', 'https://example.com');
console.log('Message sent'); // Output: Message sent
Tags: intermediate, JavaScript, Web APIs
Yes, you can use expressions in case
statements. The expression is evaluated and compared with the switch
value.
Example:
const value = 10;
switch (value) {
case 5 + 5:
console.log('Matched 10');
break;
default:
console.log('No match');
}
Tags: basic, JavaScript, Control Flow
The !--
notation is not a special operator in JavaScript. It is often a typo or part of HTML comments (<!-- -->
). In JavaScript, !
is the logical NOT operator, and --
is the decrement operator.
Tags: basic, JavaScript, operators
URL: https://www.tiktok.com/@jsmentoring/photo/7456013855827791137
Despite the similar names, Java and JavaScript are not directly related. Java is a class-based, object-oriented programming language, while JavaScript is a lightweight, interpreted scripting language primarily used for web development.
Tags: basic, JavaScript, general knowledge
URL: https://www.tiktok.com/@jsmentoring/photo/7454554999335537952
ES6 (ECMAScript 2015) introduced several new features to JavaScript, including:
- Let and const: Block-scoped variables.
- Arrow functions: Shorter function syntax.
- Template literals: String interpolation.
- Destructuring assignment: Easier extraction of values from arrays or objects.
- Promises: Handling asynchronous operations more efficiently.
Example:
const [first, second] = [1, 2];
console.log(first, second); // Output: 1 2
Tags: intermediate, JavaScript, ES6
URL: https://www.tiktok.com/@jsmentoring/photo/7469439568199142689
The WeakMap
object supports the following methods:
set(key, value)
– Adds a key-value pair.get(key)
– Retrieves the value associated with the key.has(key)
– Checks if a key exists in theWeakMap
.delete(key)
– Removes a key-value pair.
Example:
const obj = { name: 'John' };
const weakmap = new WeakMap();
weakmap.set(obj, 'value');
console.log(weakmap.get(obj)); // 'value'
Tags: basic, JavaScript, collections
URL: https://www.tiktok.com/@jsmentoring/photo/7459137346080869665
The WeakSet
object supports the following methods:
add(value)
– Adds a value to the set.delete(value)
– Removes a value from the set.has(value)
– Checks if a value is in the set.
Example:
const obj = { name: 'John' };
const weakset = new WeakSet([obj]);
weakset.add(obj);
console.log(weakset.has(obj)); // true
weakset.delete(obj);
console.log(weakset.has(obj)); // false
Tags: basic, JavaScript, collections
URL: https://www.tiktok.com/@jsmentoring/photo/7458291433980579105
To merge two sorted arrays into one sorted array, use two pointers to compare the elements from both arrays.
- Initialize two pointers, one for each array.
- Compare the elements at the current pointers and add the smaller element to the result array.
- Move the pointer of the array from which the element was taken.
- If one array is exhausted, add the remaining elements of the other array to the result.
- Return the merged sorted array.
function mergeSortedArrays(arr1, arr2) {
let result = [];
let i = 0, j = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
result.push(arr1[i]);
i++;
} else {
result.push(arr2[j]);
j++;
}
}
return result.concat(arr1.slice(i), arr2.slice(j));
}
// Example usage
console.log(mergeSortedArrays([1, 3, 5], [2, 4, 6])); // Output: [1, 2, 3, 4, 5, 6]
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
To merge two sorted linked lists into one sorted linked list, use a two-pointer approach to traverse both lists and merge them in sorted order.
- Initialize two pointers, one for each list.
- Compare the elements of both lists and append the smaller element to the merged list.
- Once one list is exhausted, append the remaining elements from the other list.
- Return the merged sorted list.
function mergeLists(l1, l2) {
let dummy = new ListNode(0);
let current = dummy;
while (l1 && l2) {
if (l1.val < l2.val) {
current.next = l1;
l1 = l1.next;
} else {
current.next = l2;
l2 = l2.next;
}
current = current.next;
}
current.next = l1 || l2;
return dummy.next;
}
// Example usage
// Assuming ListNode is defined with val and next properties
This method has a time complexity of O(n + m), where n and m are the lengths of the two linked lists.
Tags: intermediate, JavaScript, Linked Lists, Algorithm
To remove duplicate characters from a string, you can use a set to store unique characters.
- Initialize an empty set to store unique characters.
- Iterate through the string and add each character to the set.
- Join the characters from the set into a new string and return it.
function removeDuplicates(str) {
return [...new Set(str)].join('');
}
// Example usage
console.log(removeDuplicates("programming")); // Output: "progamin"
console.log(removeDuplicates("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
To remove duplicates from an array, you can use a Set, which automatically stores unique values.
- Convert the array into a Set, which will automatically remove any duplicate values.
- Convert the Set back into an array.
- Return the new array with unique elements.
function removeDuplicates(arr) {
return [...new Set(arr)];
}
// Example usage
console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5])); // Output: [1, 2, 3, 4, 5]
console.log(removeDuplicates(["apple", "banana", "apple", "orange"])); // Output: ["apple", "banana", "orange"]
This method has a time complexity of O(n), where n is the length of the array.
Tags: basic, JavaScript, Arrays, Algorithm
To remove an element from an array, you can use the filter
method or manually iterate through the array.
- Use the
filter
method to create a new array without the specified element. - Alternatively, iterate through the array and remove the element manually.
- Return the modified array.
function removeElement(arr, elem) {
return arr.filter(item => item !== elem);
}
// Example usage
console.log(removeElement([1, 2, 3, 4, 5], 3)); // Output: [1, 2, 4, 5]
console.log(removeElement(["apple", "banana", "orange"], "banana")); // Output: ["apple", "orange"]
This method has a time complexity of O(n), where n is the length of the array.
Tags: basic, JavaScript, Arrays, Algorithm
To reverse a string, you can split the string into an array of characters, reverse the array, and then join the characters back into a string.
- Convert the string into an array of characters.
- Use the
reverse()
method to reverse the array. - Join the array back into a string using the
join()
method. - Return the reversed string.
function reverseString(str) {
return str.split('').reverse().join('');
}
// Example usage
console.log(reverseString("hello")); // Output: "olleh"
console.log(reverseString("JavaScript")); // Output: "tpircSavaJ"
This method has a time complexity of O(n), where n is the length of the string.
Tags: basic, JavaScript, Strings, Algorithm
To reverse an array, you can use the reverse
method or iterate through the array manually.
- Initialize two pointers: one at the beginning and one at the end of the array.
- Swap the elements at the two pointers.
- Move the pointers toward the center until they meet.
- Return the reversed array.
function reverseArray(arr) {
let left = 0, right = arr.length - 1;
while (left < right) {
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right--;
}
return arr;
}
// Example usage
console.log(reverseArray([1, 2, 3, 4])); // Output: [4, 3, 2, 1]
console.log(reverseArray(["a", "b", "c"])); // Output: ["c", "b", "a"]
This method has a time complexity of O(n), where n is the length of the array.
Tags: basic, JavaScript, Arrays, Algorithm
To reverse an array in-place, use two pointers, one at the start and one at the end of the array. Swap elements at these pointers and move towards the center.
- Initialize two pointers: one at the start and one at the end of the array.
- Swap the elements at these pointers.
- Move the pointers towards the center.
- Repeat until the pointers cross.
function reverseArray(arr) {
let start = 0;
let end = arr.length - 1;
while (start < end) {
[arr[start], arr[end]] = [arr[end], arr[start]];
start++;
end--;
}
return arr;
}
// Example usage
console.log(reverseArray([1, 2, 3, 4, 5])); // Output: [5, 4, 3, 2, 1]
console.log(reverseArray([10, 20, 30])); // Output: [30, 20, 10]
This method has a time complexity of O(n), where n is the length of the array.
Tags: basic, JavaScript, Arrays, Algorithm
To rotate an array, move the elements from one end to the other by a specified number of positions.
- Calculate the effective number of rotations by taking the modulus of the length of the array with the rotation count.
- Slice the array into two parts: the part to be moved and the remaining part.
- Concatenate the two parts in the rotated order.
- Return the rotated array.
function rotateArray(arr, k) {
const rotations = k % arr.length;
return [...arr.slice(rotations), ...arr.slice(0, rotations)];
}
// Example usage
console.log(rotateArray([1, 2, 3, 4, 5], 2)); // Output: [3, 4, 5, 1, 2]
console.log(rotateArray([1, 2, 3], 4)); // Output: [2, 3, 1]
This method has a time complexity of O(n), where n is the length of the array.
Tags: intermediate, JavaScript, Arrays, Algorithm
To sort an array in ascending order, you can use the sort
method in JavaScript.
- Use the
sort
method with a comparison function to sort the array in ascending order. - The comparison function should return a negative, zero, or positive value based on the comparison of two elements.
- Return the sorted array.
function sortArray(arr) {
return arr.sort((a, b) => a - b);
}
// Example usage
console.log(sortArray([5, 2, 9, 1, 5, 6])); // Output: [1, 2, 5, 5, 6, 9]
console.log(sortArray([3, 1, 4, 2])); // Output: [1, 2, 3, 4]
This method has a time complexity of O(n log n), where n is the length of the array.
Tags: basic, JavaScript, Arrays, Algorithm
To find the sum of all even numbers in an array, iterate through the array and add the even numbers to a running total.
- Initialize a variable to store the sum of even numbers.
- Iterate through the array and check if each number is even (i.e., divisible by 2).
- If the number is even, add it to the sum.
- Return the final sum.
function sumEvenNumbers(arr) {
let sum = 0;
for (const num of arr) {
if (num % 2 === 0) {
sum += num;
}
}
return sum;
}
// Example usage
console.log(sumEvenNumbers([1, 2, 3, 4, 5, 6])); // Output: 12
console.log(sumEvenNumbers([10, 15, 20, 25])); // Output: 30
This method has a time complexity of O(n), where n is the length of the array.
Tags: basic, JavaScript, Arrays, Algorithm
To calculate the sum of all odd numbers in an array, iterate through the array and add up the odd numbers.
- Initialize a variable to store the sum.
- Iterate through the array, checking if each number is odd.
- If the number is odd, add it to the sum.
- Return the sum.
function sumOfOdds(arr) {
return arr.filter(num => num % 2 !== 0).reduce((sum, num) => sum + num, 0);
}
// Example usage
console.log(sumOfOdds([1, 2, 3, 4, 5])); // Output: 9
console.log(sumOfOdds([6, 7, 8, 9])); // Output: 16
This method has a time complexity of O(n), where n is the length of the array.
Tags: basic, JavaScript, Arrays, Algorithm
Asynchronous thunks are functions that return a function, which performs asynchronous operations. This allows you to delay the execution of a function, making it useful in scenarios such as API calls or working with promises.
Example:
const fetchData = (url) => (dispatch) => {
fetch(url)
.then(response => response.json())
.then(data => dispatch(data));
};
Tags: advanced, JavaScript, Functional Programming
break
is used to exit a loop prematurely.continue
is used to skip the current iteration and proceed to the next iteration of the loop.
Example:
for (let i = 0; i < 5; i++) {
if (i === 3) break;
console.log(i); // 0, 1, 2
}
Tags: basic, JavaScript, control flow
URL: https://www.tiktok.com/@jsmentoring/photo/7456440125774433569
Compose and pipe are utility functions used in functional programming to combine multiple functions.
-
Compose:
- Executes functions from right to left.
-
Pipe:
- Executes functions from left to right.
Example:
const add = x => x + 1;
const multiply = x => x * 2;
// Compose
const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x);
const composed = compose(multiply, add);
console.log(composed(5)); // 12
// Pipe
const pipe = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x);
const piped = pipe(add, multiply);
console.log(piped(5)); // 12
Tags: advanced, JavaScript, Functional Programming
Default parameters allow you to set default values for function parameters if no argument is provided when calling the function. This helps in avoiding undefined
values.
Example:
function greet(name = 'Guest') {
console.log('Hello, ' + name);
}
greet(); // Output: Hello, Guest
greet('John'); // Output: Hello, John
Tags: intermediate, JavaScript, Functions
URL: https://www.tiktok.com/@jsmentoring/photo/7470673054704635158
Default values in destructuring assignment allow you to assign a default value to a variable if the value being destructured is undefined
. This is useful when destructuring objects or arrays with missing values.
Example with array:
let [x = 10, y = 20] = [5];
console.log(x, y); // Output: 5 20
Example with object:
let { name = 'Guest', age = 25 } = { name: 'John' };
console.log(name, age); // Output: John 25
Tags: intermediate, JavaScript, Destructuring
URL: https://www.tiktok.com/@jsmentoring/photo/7471727005394930966
JavaScript typically uses a single event loop to manage all asynchronous tasks. However, in the context of multiple threads or environments, you might have different event loops, such as in Web Workers, which have their own event loops.
- Main Event Loop: Handles tasks in the main thread.
- Web Worker Event Loop: Handles tasks in background threads.
Tags: advanced, JavaScript, Event Loop
Dynamic imports allow you to load modules at runtime, rather than at the start of the script. This is useful for code splitting and loading modules on demand.
Example:
import('module').then(module => {
module.someFunction();
});
Tags: advanced, JavaScript, Modules
URL: https://www.tiktok.com/@jsmentoring/photo/7472877947460799766
Enhanced object literals simplify the creation of objects by allowing shorthand for property names and method definitions, as well as the ability to compute property names.
Example:
let name = 'John';
let person = {
name,
greet() {
console.log('Hello, ' + this.name);
}
};
person.greet(); // Output: Hello, John
Tags: intermediate, JavaScript, Objects
URL: https://www.tiktok.com/@jsmentoring/photo/7472498912625003798
In JavaScript, events are actions that occur in the browser, such as user interactions like clicks, keypresses, or page loading. JavaScript allows you to handle these events using event listeners.
Tags: basic, JavaScript, events
URL: https://www.tiktok.com/@jsmentoring/photo/7454560520000113952
What are hidden classes?
Hidden classes are an optimization technique used by JavaScript engines like V8 to enhance object property access performance. Instead of directly associating objects with their properties, the engine creates a hidden class to represent the object's structure.
-
Dynamic Nature of JavaScript Objects:
- JavaScript objects can have properties added or removed dynamically, making static optimization challenging.
-
Hidden Class Mechanism:
- When an object is created, a hidden class is assigned to it.
- Adding or removing properties results in the creation of a new hidden class.
-
Optimization:
- If objects share the same hidden class, the engine can use fast property lookups.
Example:
function Example() {
this.a = 1;
this.b = 2;
}
const obj1 = new Example();
const obj2 = new Example();
// Both obj1 and obj2 share the same hidden class.
Tags: advanced, JavaScript, V8 Engine
Accessors are methods that allow you to get or set the value of an object's property. In JavaScript, accessors are usually implemented using get
and set
methods.
Example:
const person = {
firstName: 'John',
lastName: 'Doe',
get fullName() { return this.firstName + ' ' + this.lastName; },
set fullName(name) { const parts = name.split(' '); this.firstName = parts[0]; this.lastName = parts[1]; }
};
console.log(person.fullName); // 'John Doe'
person.fullName = 'Jane Smith';
console.log(person.firstName); // 'Jane'
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7459533167528119585
A label in JavaScript is used to identify a loop or a block of code, allowing you to use break
or continue
to exit or skip to the labeled code.
Example:
outerLoop: for (let i = 0; i < 5; i++) {
for (let j = 0; j < 5; j++) {
if (i === 2 && j === 2) break outerLoop;
}
}
Tags: basic, JavaScript, control flow
URL: https://www.tiktok.com/@jsmentoring/photo/7456494402261798177
Modifiers are flags that alter the behavior of regular expressions. Common modifiers include:
g
(global): Matches all occurrences.i
(ignore case): Ignores case when matching.m
(multiline): Treats beginning and end characters (^ and $) as working across multiple lines.
Tags: basic, JavaScript, regular expressions
URL: https://www.tiktok.com/@jsmentoring/photo/7456586559056268576
Nesting templates allows you to embed template literals inside another template literal. This is useful for constructing more complex strings with dynamic content.
Example:
let name = 'John';
let message = `Hello, ${`Mr. ${name}`}!`;
console.log(message); // Output: Hello, Mr. John!
Tags: intermediate, JavaScript, Strings
URL: https://www.tiktok.com/@jsmentoring/photo/7469447667714690337
Primitive data types in JavaScript are the most basic types of data. They are immutable and include:
string
number
boolean
null
undefined
symbol
(ES6)bigint
(ES11)
Example:
const name = 'John'; // string
const age = 30; // number
const isActive = true; // boolean
Tags: basic, JavaScript, data types
URL: https://www.tiktok.com/@jsmentoring/photo/7459714568466484513
Progressive Web Apps (PWAs) are web applications that use modern web capabilities to deliver an app-like experience to users. They are reliable, fast, and engaging, offering offline capabilities, push notifications, and the ability to be installed on the user's device.
Tags: basic, JavaScript, web technologies
URL: https://www.tiktok.com/@jsmentoring/photo/7453553728059215136
Raw strings in JavaScript are used to access the raw string literals from template literals without escaping special characters like
or
.
Example:
let rawStr = String.raw`Hello
World`;
console.log(rawStr); // Output: Hello\nWorld
Tags: advanced, JavaScript, Strings
URL: https://www.tiktok.com/@jsmentoring/photo/7471026585861164310
Regular expression patterns are sequences of characters that form search patterns. They are used to match strings based on specific rules. Patterns can include literals, special characters, and character classes.
Example:
const regex = /\d+/; // Matches one or more digits
console.log('123abc'.match(regex)); // ['123']
Tags: basic, JavaScript, regular expressions
URL: https://www.tiktok.com/@jsmentoring/photo/7456908944020196641
Tagged templates allow you to parse a template literal with a function. The function is called with the string literals and interpolated expressions as arguments.
Example:
function tag(strings, ...values) {
console.log(strings, values);
}
let name = 'John';
tag`Hello, ${name}!`; // Output: ['Hello, ', '!'] ['John']
Tags: advanced, JavaScript, Strings
URL: https://www.tiktok.com/@jsmentoring/photo/7469507120082324768
In JavaScript, tasks (also called 'macrotasks') refer to operations in the event loop that are executed one by one. Each task is a block of code that is executed synchronously, like handling events, setTimeout
, setInterval
, etc.
Tasks are processed in the event loop, and when one task completes, the next one in the queue is executed.
Tags: advanced, JavaScript, Event Loop
Template literals are a way to define strings that can contain expressions, making string interpolation easier. They are enclosed by backticks (
) instead of quotes.
Example:
let name = 'John';
let greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, John!
Tags: intermediate, JavaScript, Strings
Getters and setters provide a controlled way to access and modify an object's properties. They allow you to define custom logic for setting or getting values and can help in encapsulating the internal state.
Example:
const person = {
_name: 'John',
get name() { return this._name; },
set name(value) { this._name = value.toUpperCase(); }
};
person.name = 'Jane';
console.log(person.name); // 'JANE'
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7459673228697554208
Minification provides several benefits:
- Reduced File Size: Smaller file sizes mean faster download and loading times for users.
- Improved Performance: Minified files are faster to download and execute, leading to better performance of the application.
- Reduced Bandwidth Usage: Smaller files consume less bandwidth, which is beneficial for users with limited internet speed.
Tools like UglifyJS, Terser, and Google Closure Compiler can be used for minification.
Tags: intermediate, JavaScript, optimization
URL: https://www.tiktok.com/@jsmentoring/photo/7463246833825991969
Module loaders allow you to load JavaScript files and dependencies asynchronously, reducing page load times and enabling code splitting. They help in managing dependencies, modularizing code, and improving maintainability.
Example: Tools like Webpack, RequireJS, and SystemJS are popular module loaders.
Tags: advanced, JavaScript, Modules
URL: https://www.tiktok.com/@jsmentoring/photo/7472504525740379414
TypeScript offers several advantages over JavaScript:
- Static typing helps catch errors early during development.
- Better tooling support with autocompletion and code refactoring.
- Type inference improves developer productivity and reduces errors.
- Support for modern JavaScript features like async/await, decorators, etc., even in older browsers when transpiled.
Example:
function greet(person: string) {
console.log(`Hello, ${person}`);
}
greet(42); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.
Tags: basic, TypeScript
URL: https://www.tiktok.com/@jsmentoring/photo/7462837290327395617
Object.assign()
is used to copy properties from one or more source objects to a target object. It can be used for cloning objects or merging multiple objects into one.
Example:
const target = { name: 'John' };
const source = { age: 30 };
const result = Object.assign(target, source);
console.log(result); // { name: 'John', age: 30 }
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7458036822975712544
Object.seal()
is commonly used to lock an object to prevent new properties from being added, while still allowing modifications to existing properties. It can be useful in situations where you want to ensure the structure of an object remains unchanged.
Example:
const person = { name: 'John' };
Object.seal(person);
person.name = 'Jane'; // Allowed
person.city = 'New York'; // Not allowed
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7458730878810770720
Array mutation methods directly modify the original array.
push
: Adds elements to the end.pop
: Removes the last element.shift
: Removes the first element.unshift
: Adds elements to the beginning.splice
: Adds/removes elements at a specific index.
Example:
const arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
arr.pop(); // [1, 2, 3]
Tags: basic, JavaScript, Arrays
A property descriptor in JavaScript is an object that describes the attributes of a property in an object. It contains the following attributes:
- value: The value of the property.
- writable: A boolean that indicates whether the value of the property can be changed.
- enumerable: A boolean that indicates whether the property shows up in a
for...in
loop orObject.keys()
. - configurable: A boolean that indicates whether the property can be deleted or modified.
Example:
const person = { name: 'John' };
const descriptor = Object.getOwnPropertyDescriptor(person, 'name');
console.log(descriptor);
// { value: 'John', writable: true, enumerable: true, configurable: true }
Tags: intermediate, JavaScript, objects
The following properties are available for constraint validation in the DOM:
- validity: An object that contains various validity states of the input element.
- valueMissing: Returns
true
if the input is required but empty. - typeMismatch: Returns
true
if the input value doesn't match the expected type. - tooLong: Returns
true
if the value is too long for the field. - rangeUnderflow: Returns
true
if the value is less than the minimum value.
Example:
const input = document.querySelector('input');
console.log(input.validity.rangeUnderflow); // true or false
Tags: intermediate, JavaScript, DOM, validation
URL: https://www.tiktok.com/@jsmentoring/photo/7464745553981672736
-
Code Reusability:
- Allows reusing logic by passing different functions.
-
Readability and Maintainability:
- Makes code more declarative and easier to understand.
-
Functional Programming Support:
- Encourages immutability and pure functions.
-
Abstraction:
- Hides low-level details and focuses on high-level operations.
Example:
function applyOperation(arr, operation) {
return arr.map(operation);
}
const numbers = [1, 2, 3];
const squared = applyOperation(numbers, num => num * num);
console.log(squared); // [1, 4, 9]
Tags: basic, JavaScript, Functional Programming
Initializing variables ensures that they have a defined value when accessed, which helps avoid bugs caused by undefined variables and improves code reliability.
Tags: basic, JavaScript, best practices
URL: https://www.tiktok.com/@jsmentoring/photo/7456552071349751073
Declaring variables at the top of the scope helps avoid confusion and ensures that the variables are hoisted properly. This practice can also improve code readability and debugging.
Tags: basic, JavaScript, best practices
URL: https://www.tiktok.com/@jsmentoring/photo/7456506923873996065
JavaScript supports several bitwise operators, including AND (&
), OR (|
), XOR (^
), NOT (~
), and shift operators (<<
, >>
, >>>
).
Example:
const a = 5; // 0101
const b = 3; // 0011
console.log(a & b); // 1 (0101 & 0011 = 0001)
Tags: basic, JavaScript, operators
URL: https://www.tiktok.com/@jsmentoring/video/7457690353714433312
Built-in iterables in JavaScript include:
-
Arrays:
for (let item of [1, 2, 3]) { console.log(item); }
-
Strings:
for (let char of 'hello') { console.log(char); }
-
Maps and Sets:
let map = new Map([['a', 1]]); for (let [key, value] of map) { console.log(key, value); }
-
Typed Arrays and NodeLists.
Tags: intermediate, JavaScript, Iterables
There are several tools available for minifying JavaScript code:
- UglifyJS: A popular JavaScript minifier that can be used via the command line or as a library.
- Terser: A JavaScript minifier that is a fork of UglifyJS, focused on modern JavaScript features.
- Google Closure Compiler: A JavaScript optimizer that can minify and optimize JavaScript code.
- Babel Minify: A minifier built specifically for Babel, targeting modern JavaScript features.
These tools remove unnecessary characters, such as spaces, comments, and newlines, to reduce the file size.
Tags: intermediate, JavaScript, optimization
URL: https://www.tiktok.com/@jsmentoring/photo/7463234648185916705
Observables are useful for handling asynchronous events and streams of data. Common use cases include:
- Handling multiple values over time (e.g., user inputs, WebSocket data, server responses)
- Managing asynchronous sequences, like HTTP requests or animations
- Implementing reactive programming patterns
Example using RxJS for handling HTTP requests:
import { of } from 'rxjs';
of('Data loaded').subscribe(data => console.log(data));
Tags: advanced, JavaScript, RxJS
Here are some best practices for using switch-case
in JavaScript:
- Always include a
default
case to handle unexpected values. - Ensure each
case
ends with abreak
statement to avoid falling through to the next case. - Avoid using
switch-case
for complex conditions that can be handled withif-else
statements.
Example:
const number = 2;
switch(number) {
case 1:
console.log('One');
break;
case 2:
console.log('Two');
break;
default:
console.log('Unknown number');
}
Tags: basic, JavaScript, control structures
URL: https://www.tiktok.com/@jsmentoring/photo/7459772144747105568
-
Arguments Object:
- Array-like object available in every non-arrow function.
- Does not work with arrow functions.
- Does not support array methods directly.
-
Rest Parameter:
- Collects arguments into a real array.
- Works with all functions, including arrow functions.
Example:
function oldStyleFunction() {
console.log(arguments); // Array-like
}
const newStyleFunction = (...args) => {
console.log(args); // Array
};
oldStyleFunction(1, 2, 3);
newStyleFunction(1, 2, 3);
Tags: intermediate, JavaScript, Functions
-
for...of
:- Iterates over values of an iterable (e.g., array, string, Map).
- Example:
for (let value of [10, 20, 30]) { console.log(value); // 10, 20, 30 }
-
for...in
:- Iterates over keys or properties of an object.
- Example:
for (let key in { a: 1, b: 2 }) { console.log(key); // 'a', 'b' }
Tags: basic, JavaScript, Loops
Both Object.freeze()
and Object.seal()
prevent modification of an object, but with different restrictions:
Object.freeze()
makes an object immutable, preventing changes to existing properties, and disallowing the addition or removal of properties.Object.seal()
allows modification of existing properties but prevents the addition of new properties.
Example:
const obj1 = { name: 'John' };
Object.freeze(obj1);
obj1.name = 'Jane'; // Not allowed
obj1.age = 30; // Not allowed
const obj2 = { name: 'John' };
Object.seal(obj2);
obj2.name = 'Jane'; // Allowed
obj2.age = 30; // Not allowed
Tags: basic, JavaScript, objects
The key differences between JavaScript and TypeScript include:
- TypeScript has optional static typing, while JavaScript is dynamically typed.
- TypeScript supports modern JavaScript features and compiles down to JavaScript, while JavaScript is interpreted directly by the browser or Node.js.
- TypeScript provides better tooling and editor support with features like type inference, autocompletion, and error checking during development.
Example:
let age: number = 30; // TypeScript
let name = 'John'; // JavaScript
Tags: basic, JavaScript, TypeScript
URL: https://www.tiktok.com/@jsmentoring/photo/7462815493494197536
Obfuscation and encryption both aim to protect data, but they serve different purposes:
- Obfuscation: The goal is to make the code or data difficult to understand for humans but does not prevent someone from reversing it with enough time or effort. It's used primarily for source code protection.
- Encryption: The goal is to transform data into a format that cannot be easily read or accessed without the proper decryption key. Encryption is more secure than obfuscation and is often used for securing sensitive information.
Example:
- Obfuscation might involve renaming variables in a script.
- Encryption involves transforming data into a coded format using an encryption algorithm.
Tags: intermediate, JavaScript, security
URL: https://www.tiktok.com/@jsmentoring/photo/7463193138585292065
Primitives:
- Immutable, basic data types (e.g.,
string
,number
,boolean
,null
,undefined
,Symbol
,BigInt
). - Stored directly in memory.
Non-primitives:
- Objects, arrays, and functions.
- Mutable and stored as references in memory.
Example:
let a = 10; // Primitive
let b = a;
b = 20;
console.log(a); // 10 (no change)
let obj = { key: 'value' }; // Non-primitive
let ref = obj;
ref.key = 'newValue';
console.log(obj.key); // 'newValue' (reference changed)
Tags: basic, JavaScript, Data Types
Promises and Observables are both used for handling asynchronous operations, but they have key differences:
- Promises: Represent a single value that will be resolved or rejected in the future.
- Observables: Represent a stream of values that can emit multiple values over time.
Example of Promise:
let promise = new Promise((resolve, reject) => { resolve('Resolved'); });
Tags: advanced, JavaScript, Promises, Observables
Pure Functions:
- Always return the same output for the same input.
- No side effects (e.g., modifying global variables or external state).
Impure Functions:
- Output depends on external factors or internal state.
- May produce side effects.
Example:
// Pure Function
function add(a, b) {
return a + b;
}
// Impure Function
let count = 0;
function increment() {
count++;
return count;
}
Tags: intermediate, JavaScript, Functional Programming
-
Spread Operator:
- Expands elements of an array or object into individual elements.
- Used in function calls, array literals, or object literals.
-
Rest Parameter:
- Collects all remaining arguments into a single array.
- Used in function definitions.
Example:
// Spread Operator
const numbers = [1, 2, 3];
console.log(...numbers); // Output: 1 2 3
// Rest Parameter
function sum(...args) {
return args.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
Tags: intermediate, JavaScript, Operators
- A
WeakMap
holds key-value pairs where the keys are objects and are held weakly, meaning they can be garbage collected if no other references exist. - A
Map
holds key-value pairs where the keys can be of any data type and are held strongly.
Example:
const obj = { name: 'John' };
const weakmap = new WeakMap();
const map = new Map();
weakmap.set(obj, 'value');
map.set(obj, 'value');
Tags: basic, JavaScript, collections
URL: https://www.tiktok.com/@jsmentoring/photo/7458189087422401825
- A
WeakSet
holds weak references to its objects, which allows garbage collection when the objects are no longer referenced elsewhere. - A
Set
holds strong references to its elements, preventing garbage collection until the set itself is garbage collected. WeakSet
can only store objects, whileSet
can store any type of value.
Example:
const obj1 = { name: 'John' };
const weakset = new WeakSet([obj1]);
const set = new Set([obj1]);
Tags: basic, JavaScript, collections
URL: https://www.tiktok.com/@jsmentoring/photo/7458240152905846048
JavaScript provides several types of error objects:
Error
– General errorsSyntaxError
– Syntax issues in codeReferenceError
– Reference to a non-existent variableTypeError
– Wrong data type usedRangeError
– A value is out of rangeEvalError
– Issues witheval()
function
Example:
try {
let x = y;
} catch (e) {
console.log(e instanceof ReferenceError); // true
}
Tags: basic, JavaScript, errors
URL: https://www.tiktok.com/@jsmentoring/photo/7460435743840718113
Generators can be categorized based on their usage:
-
Simple Generators: Yield a series of values.
function* simpleGenerator() { yield 1; yield 2; yield 3; }
-
Delegating Generators: Use
yield*
to delegate to another generator or iterable.function* delegatingGenerator() { yield* [1, 2, 3]; }
-
Asynchronous Generators: Use
async
andfor await...of
for asynchronous operations.async function* asyncGenerator() { yield await Promise.resolve(1); }
Tags: advanced, JavaScript, Generators
In JavaScript, you can find HTML elements in the DOM using various methods:
getElementById()
: Finds an element by itsid
attribute.getElementsByClassName()
: Finds elements by theirclass
attribute.getElementsByTagName()
: Finds elements by their tag name.querySelector()
: Finds the first element that matches a CSS selector.querySelectorAll()
: Finds all elements that match a CSS selector.
Example:
const element = document.getElementById('myElement');
const elements = document.getElementsByClassName('myClass');
Tags: basic, JavaScript, DOM manipulation
URL: https://www.tiktok.com/@jsmentoring/photo/7468425060965960993
There are three primary ways to access properties of an object in JavaScript:
- Dot notation:
object.property
- Bracket notation:
object['property']
- Using
Object.getOwnPropertyDescriptor()
Example:
const person = { name: 'John', age: 30 };
console.log(person.name); // Dot notation
console.log(person['age']); // Bracket notation
Tags: basic, JavaScript, objects
-
Using Array Constructor:
const sparseArray = new Array(3); // Creates [ <3 empty items> ]
-
Using Comma Syntax:
const sparseArray = [1, , 3]; // Creates [1, <1 empty item>, 3]
-
Deleting Elements:
const array = [1, 2, 3]; delete array[1]; // Creates [1, <1 empty item>, 3]
Tags: advanced, JavaScript, Arrays
JavaScript offers several ways to handle asynchronous code, including callbacks, promises, and async/await.
- Callbacks: A function passed as an argument to be executed later.
- Promises: A value that represents the eventual result of an asynchronous operation.
- Async/Await: A modern syntax for handling promises in a synchronous-like manner.
Example using async/await
:
async function fetchData() {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
}
fetchData();
Tags: advanced, JavaScript, Asynchronous Programming
-
Using
<script>
Tag:- Include the script in your HTML file.
<script src="script.js"></script>
-
Dynamically Injecting Scripts:
- Use JavaScript to add scripts to the DOM.
const script = document.createElement('script'); script.src = 'script.js'; document.body.appendChild(script);
-
Using
import
(ES Modules):- Load scripts as ES modules.
import { myFunction } from './script.js'; myFunction();
-
Using
require
(Node.js):- Load scripts in Node.js environments.
const module = require('./script.js'); module.myFunction();
Tags: basic, JavaScript, HTML
You can make an object non-extensible in JavaScript in several ways:
- Using
Object.preventExtensions()
makes an object non-extensible. - Using
Object.seal()
not only prevents extensions but also makes all existing properties non-configurable. - Using
Object.freeze()
prevents extensions and makes all properties immutable.
Example:
const obj = { name: 'John' };
Object.preventExtensions(obj);
console.log(Object.isExtensible(obj)); // false
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7462880139987209505
In JavaScript, constraint validation methods are used to check the validity of form inputs according to the constraints defined in the HTML form elements. The following DOM methods are available for constraint validation:
- checkValidity(): Checks if the element satisfies all constraints.
- reportValidity(): Checks validity and shows an error message if the element is invalid.
- setCustomValidity(): Allows you to define a custom error message for validation.
Example:
const input = document.querySelector('input');
if (!input.checkValidity()) {
console.log('Input is invalid');
}
Tags: intermediate, JavaScript, DOM, validation
URL: https://www.tiktok.com/@jsmentoring/photo/7466219893701053728
There are three main phases of event propagation in the browser:
-
Capturing Phase (Capture):
- Event travels from the root to the target element.
-
Target Phase:
- Event reaches the target element.
-
Bubbling Phase (Bubble):
- Event propagates back from the target to the root.
Example:
document.getElementById('myDiv').addEventListener('click', event => {
console.log('Capturing Phase');
}, true);
document.getElementById('myDiv').addEventListener('click', event => {
console.log('Bubbling Phase');
});
Tags: intermediate, JavaScript, Events
Higher-order functions are functions that can accept other functions as arguments or return functions. Examples of built-in higher-order functions in JavaScript include:
-
map
:const numbers = [1, 2, 3]; const doubled = numbers.map(num => num * 2); console.log(doubled); // [2, 4, 6]
-
filter
:const numbers = [1, 2, 3, 4]; const evens = numbers.filter(num => num % 2 === 0); console.log(evens); // [2, 4]
-
reduce
:const numbers = [1, 2, 3, 4]; const sum = numbers.reduce((total, num) => total + num, 0); console.log(sum); // 10
-
forEach
:const numbers = [1, 2, 3]; numbers.forEach(num => console.log(num));
-
sort
:const names = ['Charlie', 'Alice', 'Bob']; names.sort((a, b) => a.localeCompare(b)); console.log(names); // ['Alice', 'Bob', 'Charlie']
Tags: basic, JavaScript, Functional Programming
- Function parameters are the variables listed in a function's declaration.
- JavaScript functions can have default parameters.
- Parameters are passed in the order they are listed.
- A function can accept any number of arguments, but the excess arguments will be ignored unless using the
...rest
parameter.
Example:
function greet(name = 'Guest') {
console.log('Hello, ' + name);
}
greet(); // 'Hello, Guest'
greet('John'); // 'Hello, John'
Tags: basic, JavaScript, functions
URL: https://www.tiktok.com/@jsmentoring/photo/7459895386811976992
In strict mode, JavaScript imposes stricter parsing and error handling. Some common errors that occur when switching from non-strict to strict mode include:
- Assignment to undeclared variables
- Assigning to read-only properties
- Deleting undeletable properties
Example:
'use strict';
undeclaredVar = 10; // Throws ReferenceError
Tags: advanced, JavaScript, Strict Mode
Here is a list of validity properties that you can access through the validity
property of an input element:
- valueMissing: If the field is required but not filled in.
- typeMismatch: If the input value does not match the expected type.
- patternMismatch: If the value doesn't match the regular expression pattern defined.
- tooLong: If the value exceeds the
maxlength
constraint. - tooShort: If the value is too short according to the
minlength
constraint. - rangeUnderflow: If the value is less than the
min
attribute. - rangeOverflow: If the value is greater than the
max
attribute. - stepMismatch: If the value does not meet the step constraint.
- badInput: If the input value is not valid for the input type.
- customError: If a custom validation error has been set using
setCustomValidity
.
Tags: intermediate, JavaScript, DOM, validation
URL: https://www.tiktok.com/@jsmentoring/photo/7466576921191583008
-
Just-In-Time (JIT) Compilation:
- Converts JavaScript into machine code during runtime.
-
Hidden Classes:
- Creates optimized data structures for objects with the same properties.
-
Inline Caching:
- Speeds up property access by reusing previous lookups.
-
Garbage Collection:
- Automatically reclaims memory no longer in use.
Example:
const obj = { a: 1, b: 2 };
console.log(obj.a); // Inline caching used after first lookup
Tags: advanced, JavaScript, Engines
-
Creation Phase:
- Memory is allocated for variables and functions.
- Variables are initialized with
undefined
. - Functions are stored as-is.
-
Execution Phase:
- Code is executed line by line.
- Variables are assigned actual values.
Example:
function test() {
console.log(a); // undefined (creation phase)
var a = 10;
console.log(a); // 10 (execution phase)
}
test();
Tags: intermediate, JavaScript, Execution Context
The console
object in JavaScript supports placeholders like %s
, %d
, and %o
for formatted output. These placeholders allow you to format and display data in the console in a more readable way.
Example:
let name = 'Alice';
let age = 25;
console.log('Name: %s, Age: %d', name, age); // Output: 'Name: Alice, Age: 25'
Tags: intermediate, JavaScript, Console
-
Global Variables:
var leak = 'This is a memory leak';
-
Uncleared Intervals/Timeouts:
setInterval(() => console.log('Leaking memory'), 1000);
-
Detached DOM Nodes:
const element = document.getElementById('myElement'); element.parentNode.removeChild(element); // Still referenced in memory
-
Closures Holding References:
function leak() { let bigArray = new Array(1000000); return function() { console.log(bigArray); }; }
Tags: advanced, JavaScript, Performance
Side effects occur when a function interacts with or modifies something outside its scope. Examples include:
- Modifying global variables or objects.
- Logging to the console.
- Making network requests (e.g.,
fetch
). - DOM manipulation.
Example:
// Side Effect: Modifying a global variable
let count = 0;
function increment() {
count++;
}
// Side Effect: Logging to the console
function logMessage(message) {
console.log(message);
}
Tags: intermediate, JavaScript, Functional Programming
Using *
as the targetOrigin
in postMessage
allows any origin to receive the message, which can expose your data to malicious actors. Always specify the exact origin to ensure secure communication.
Example:
window.postMessage('message', '*'); // Insecure
Tags: advanced, JavaScript, Security
The Intl
object in JavaScript provides several properties and methods to help with internationalization. Some of the main properties include:
Intl.NumberFormat
Intl.DateTimeFormat
Intl.Collator
Intl.ListFormat
Intl.RelativeTimeFormat
These objects allow you to format numbers, dates, and compare strings based on different locales.
Example:
const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
console.log(formatter.format(1000)); // '$1,000.00'
Tags: basic, JavaScript, internationalization
URL: https://www.tiktok.com/@jsmentoring/photo/7461735308938235168
To get the size of the window, you can use window.innerWidth
and window.innerHeight
for the dimensions of the viewport.
Example:
console.log(window.innerWidth, window.innerHeight);
Tags: basic, JavaScript, window properties
URL: https://www.tiktok.com/@jsmentoring/photo/7456924943062715680
Pros: for
loops are simple, efficient, and widely supported. They provide complete control over the iteration.
Cons: Can be error-prone, especially with complex conditions or manual index management.
Tags: basic, JavaScript, loops
Promises provide cleaner, more readable code with .then()
and .catch()
methods. They avoid callback hell, but can introduce complexity with chaining and error handling.
Tags: advanced, JavaScript, promises
URL: https://www.tiktok.com/@jsmentoring/photo/7453226425227726112
-
Validation:
const validator = { set(obj, prop, value) { if (prop === 'age' && typeof value !== 'number') { throw new Error('Age must be a number'); } obj[prop] = value; return true; } }; const person = new Proxy({}, validator); person.age = 25; // Valid person.age = 'twenty'; // Throws Error
-
Property Access Control:
const handler = { get(target, prop) { return prop in target ? target[prop] : 'Property does not exist'; } }; const obj = new Proxy({}, handler); console.log(obj.name); // 'Property does not exist'
-
Performance Optimization:
- Proxy can be used to lazy-load properties or cache data dynamically.
Tags: advanced, JavaScript, Proxy
Use object literals {}
or Object.create()
to create objects in JavaScript. The object literal syntax is simple and efficient for most use cases.
Example:
const obj = { name: 'John', age: 30 };
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7456561892916563233
return false
is used to prevent both the default behavior and the event propagation in one step. It can be used in an event handler to stop the event from bubbling and cancel the default action.
Tags: intermediate, JavaScript, events
URL: https://www.tiktok.com/@jsmentoring/photo/7456163504303787297
String methods like match()
, replace()
, search()
, and split()
accept regular expressions to perform pattern matching and replacement in strings.
Tags: basic, JavaScript, regular expressions
JSON syntax rules include using double quotes for keys and string values, no trailing commas, and values can be strings, numbers, objects, arrays, true, false, or null.
Tags: basic, JavaScript, data formats
URL: https://www.tiktok.com/@jsmentoring/photo/7453777976652467489
Common debugging techniques include using console.log()
, browser developer tools (F12), breakpoints, and using debuggers like Chrome DevTools or Visual Studio Code.
Tags: intermediate, JavaScript, debugging
URL: https://www.tiktok.com/@jsmentoring/photo/7454541000824917281
There are two main types of loops in JavaScript:
- For loop – Repeats a block of code a certain number of times.
- While loop – Repeats a block of code while a specified condition is true.
Example:
for (let i = 0; i < 5; i++) {
console.log(i);
}
let j = 0;
while (j < 5) {
console.log(j);
j++;
}
Tags: basic, JavaScript, loops
URL: https://www.tiktok.com/@jsmentoring/photo/7460508135346687265
Dynamic imports are useful for lazy loading, where modules are loaded only when they are needed, improving the initial load time of a web application. They are also helpful in code splitting and on-demand loading of specific features or components.
Example:
if (userWantsFeature) {
import('./feature.js').then(feature => {
feature.init();
});
}
Tags: advanced, JavaScript, Modules
URL: https://www.tiktok.com/@jsmentoring/photo/7472500779358686486
Closures allow a function to retain access to its outer scope, even after the outer function has returned. Common uses include:
-
Data Encapsulation:
function counter() { let count = 0; return function() { return ++count; }; } const increment = counter(); console.log(increment()); // 1 console.log(increment()); // 2
-
Event Handlers:
function setupEventListener() { let name = 'ClickMe'; document.addEventListener('click', function() { console.log(`Button ${name} clicked`); }); } setupEventListener();
Tags: intermediate, JavaScript, Closures
In JavaScript, the main statements used for error handling are:
try
– Used to wrap the code that may throw an error.catch
– Used to handle errors that occur in thetry
block.finally
– A block of code that runs aftertry
andcatch
, regardless of whether an error was thrown.
Example:
try {
throw new Error('Something went wrong');
} catch (e) {
console.log(e.message);
} finally {
console.log('This will always run');
}
Tags: basic, JavaScript, errors
The location
object has several properties, including href
, protocol
, hostname
, pathname
, search
, and hash
, which allow you to get and manipulate different parts of the current URL.
Tags: basic, JavaScript, web navigation
URL: https://www.tiktok.com/@jsmentoring/photo/7455459948529487136
You can execute JavaScript after the page loads using the window.onload
event or by using DOMContentLoaded
event. Additionally, you can use setTimeout()
or setInterval()
to delay the execution.
Example:
window.onload = function() {
console.log('Page loaded');
};
Tags: basic, JavaScript, page load
URL: https://www.tiktok.com/@jsmentoring/photo/7457929884061469985
Typed arrays are arrays that allow you to work with binary data. They provide a mechanism for dealing with raw binary data buffers in JavaScript, offering various array-like objects that represent different binary data formats.
Example:
let buffer = new ArrayBuffer(16);
let int32View = new Int32Array(buffer);
int32View[0] = 42;
console.log(int32View[0]); // Output: 42
Tags: advanced, JavaScript, Arrays
URL: https://www.tiktok.com/@jsmentoring/photo/7473277864649968918
JavaScript supports several types of operators, including arithmetic operators, comparison operators, logical operators, and assignment operators.
Examples:
- Arithmetic:
+
,-
,*
,/
- Comparison:
==
,!=
,>
,<
- Logical:
&&
,||
- Assignment:
=
,+=
,-=
Tags: basic, JavaScript, operators
URL: https://www.tiktok.com/@jsmentoring/photo/7457453251810561313
Wrapper objects in JavaScript are objects that wrap primitive values (like String
, Number
, and Boolean
). They allow you to call methods on primitive types.
Example:
let str = 'hello';
let strObj = new String(str);
console.log(strObj.toUpperCase()); // Output: 'HELLO'
Tags: intermediate, JavaScript, Data Types
If you pass a string type to the Object.getPrototypeOf()
method, it will throw a TypeError
because the argument must be an object. The getPrototypeOf
method only works on objects, and passing a primitive value like a string is invalid.
Example:
const str = 'hello';
console.log(Object.getPrototypeOf(str)); // Works fine
console.log(Object.getPrototypeOf('hello')); // TypeError
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7463635925373947169
In JavaScript, adding two arrays does not perform element-wise addition. Instead, it concatenates them into a new array, but if you add them directly, it will convert them to strings and concatenate those.
Example:
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
console.log(arr1 + arr2); // Output: '1,2,34,5,6'
Tags: intermediate, JavaScript, Arrays
The rest parameter must always be the last argument in a function. If it is not, JavaScript will throw a syntax error.
Example:
function myFunction(a, ...rest, b) { // SyntaxError
}
Tags: basic, JavaScript, functions
In JavaScript, a class can only have one constructor method. If you define multiple constructors, it will result in a syntax error. However, you can simulate multiple constructors by using default parameters or using conditional logic within a single constructor.
Example:
class Person {
constructor(name = 'John', age = 30) {
this.name = name;
this.age = age;
}
}
const person = new Person();
console.log(person.name); // John
Tags: basic, JavaScript, classes
URL: https://www.tiktok.com/@jsmentoring/photo/7463617735281347873
When you negate an array in JavaScript, it is first converted to a primitive value, which is true
when the array is non-empty and false
when the array is empty. Negating it results in false
for non-empty arrays and true
for empty arrays.
Example:
let arr = [1, 2, 3];
console.log(!arr); // Output: false
arr = [];
console.log(!arr); // Output: true
Tags: intermediate, JavaScript, Arrays
The comma operator in JavaScript allows you to evaluate multiple expressions in a single statement, returning the value of the last expression. It is useful when you need to execute several operations within a single statement.
Example:
let a = (1, 2, 3);
console.log(a); // 3
Tags: basic, JavaScript, operators
URL: https://www.tiktok.com/@jsmentoring/photo/7462513246734535969
The conditional (ternary) operator is a shorthand for an if-else
statement. It evaluates a condition and returns one of two values based on whether the condition is true or false.
Example:
const result = (age >= 18) ? 'Adult' : 'Minor';
Tags: basic, JavaScript, operators
URL: https://www.tiktok.com/@jsmentoring/photo/7457925912974216481
A constructor method in JavaScript is a special function within a class that is called when an instance of the class is created. It is used to initialize the object’s properties.
Example:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const person = new Person('John', 30);
console.log(person.name); // John
Tags: basic, JavaScript, classes
URL: https://www.tiktok.com/@jsmentoring/photo/7462819474555653408
The debugger
statement is used to stop the execution of JavaScript and invoke the debugging functionality of the browser. It can be used to set breakpoints during development.
Example:
debugger;
console.log('This will pause execution');
Tags: basic, JavaScript, debugging
URL: https://www.tiktok.com/@jsmentoring/photo/7457945315644165408
A decorator is a function that takes another function or method and adds additional functionality to it without modifying the original function. Decorators are commonly used in JavaScript to modify or enhance behavior in a reusable way.
Example:
function log(target, key, descriptor) {
const original = descriptor.value;
descriptor.value = function(...args) {
console.log('Calling ' + key);
return original.apply(this, args);
};
return descriptor;
}
class MyClass {
@log
myMethod() {
console.log('Method executed');
}
}
const obj = new MyClass();
obj.myMethod(); // Logs: 'Calling myMethod' and 'Method executed'
Tags: basic, JavaScript, design patterns
URL: https://www.tiktok.com/@jsmentoring/photo/7460446342461099296
The Object.freeze()
method freezes an object, preventing new properties from being added, existing properties from being removed, or their values from being changed.
Example:
const obj = { name: 'John' };
Object.freeze(obj);
obj.name = 'Jane'; // This won't change the name
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7457554518977285408
A microtask queue is a queue in JavaScript that handles microtasks, which are small asynchronous tasks. These tasks are executed after the current script finishes executing, but before any other tasks in the event loop (macrotasks) are processed.
Microtasks typically include promise handlers (.then()
, .catch()
) and tasks queued by queueMicrotask()
.
Example:
Promise.resolve().then(() => console.log('Microtask executed'));
**Tags**: [advanced](./level/advanced), [JavaScript](./theme/javascript), [Event Loop](./theme/event_loop)
---
### What is a polyfill?
A polyfill is a piece of code that implements a feature in a browser that does not support it natively. It ensures compatibility with older browsers.
Example: A polyfill for `Array.prototype.includes`:
```javascript
if (!Array.prototype.includes) {
Array.prototype.includes = function(element) {
return this.indexOf(element) !== -1;
};
}
Tags: basic, JavaScript, web development
URL: https://www.tiktok.com/@jsmentoring/photo/7456405893618437409
A Proper Tail Call (PTC) is a feature where the last action of a function is a call to another function, and the current function's stack frame is removed before executing the called function. This optimization prevents stack overflow errors for recursive calls.
Example:
function factorial(n, acc = 1) {
if (n === 0) return acc;
return factorial(n - 1, acc * n); // Tail call
}
console.log(factorial(5)); // Output: 120
Tags: advanced, JavaScript, Optimization
A Proxy object is used to define custom behavior for fundamental operations (e.g., property lookup, assignment, function invocation) on another object. It is used for tasks like validation, logging, or access control.
Example:
const person = {
name: 'John'
};
const handler = {
get: function(target, prop) {
if (prop === 'name') {
return 'Jane';
}
return prop;
}
};
const proxyPerson = new Proxy(person, handler);
console.log(proxyPerson.name); // 'Jane'
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7458050469735320865
A RegExp
object in JavaScript is used to work with regular expressions. It provides methods like exec()
and test()
to search for patterns in strings.
Example:
const regex = new RegExp('\d+');
console.log(regex.test('123')); // true
Tags: basic, JavaScript, regular expressions
URL: https://www.tiktok.com/@jsmentoring/photo/7456579932475362592
A regular expression (regex) is a pattern used to match character combinations in strings. It is commonly used for validating input or searching for patterns.
Example:
const regex = /\d+/;
console.log(regex.test('123')); // true
Tags: basic, JavaScript, regular expressions
URL: https://www.tiktok.com/@jsmentoring/photo/7456774238825925920
A rest parameter allows a function to accept an indefinite number of arguments as an array. It is denoted by ...
.
Example:
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
Tags: basic, JavaScript, functions
URL: https://www.tiktok.com/@jsmentoring/photo/7457471528330988832
A short-circuit condition occurs when the evaluation of a logical expression stops as soon as the result is determined. This is common with logical AND
(&&
) and OR
(||
) operators.
- In an
AND
condition, if the first operand is falsy, the second operand is not evaluated. - In an
OR
condition, if the first operand is truthy, the second operand is not evaluated.
Example:
let a = false;
let b = true;
console.log(a && b); // 'false', 'b' is not evaluated
**Tags**: [intermediate](./level/intermediate), [JavaScript](./theme/javascript), [Logical Operators](./theme/logical_operators)
---
### What is a spread operator?
The spread operator (`...`) is used to expand elements of an array or object. It can be used to create shallow copies or merge multiple arrays or objects.
Example with arrays:
```javascript
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // [1, 2, 3, 4, 5]
Example with objects:
const obj1 = { name: 'John', age: 30 };
const obj2 = { ...obj1, city: 'New York' };
console.log(obj2); // { name: 'John', age: 30, city: 'New York' }
Tags: basic, JavaScript, operators
A thunk function is a function that wraps another function or expression, typically used to delay the execution of the original function. It is often used in functional programming to manage side effects or control execution order.
Example:
const add = (a, b) => a + b;
const thunk = (a, b) => () => add(a, b);
const result = thunk(2, 3)(); // Output: 5
Tags: advanced, JavaScript, Functional Programming
The void
operator is used to evaluate an expression and return undefined
. It is often used in situations where you want to execute a function or expression but do not care about its result.
Example:
void(0); // Returns undefined
void(console.log('Hello')); // Logs 'Hello' and returns undefined
Tags: intermediate, JavaScript, Operators
A WeakMap
is a collection of key-value pairs where the keys are objects and the values can be any type. The keys in a WeakMap
are held weakly, meaning they can be garbage collected when there are no other references to the key object.
Example:
const obj1 = { name: 'John' };
const weakmap = new WeakMap();
weakmap.set(obj1, 'value');
console.log(weakmap.get(obj1)); // 'value'
Tags: basic, JavaScript, collections
URL: https://www.tiktok.com/@jsmentoring/photo/7458221758114516256
A WeakSet
is a collection of objects where each object is held weakly. This means the objects in a WeakSet
are not prevented from being garbage-collected when there are no other references to them. It only accepts objects, and it does not allow duplicates.
Example:
const obj1 = { name: 'John' };
const obj2 = { name: 'Jane' };
const weakset = new WeakSet([obj1, obj2]);
console.log(weakset.has(obj1)); // true
Tags: basic, JavaScript, collections
URL: https://www.tiktok.com/@jsmentoring/photo/7461719258490211617
AJAX (Asynchronous JavaScript and XML) is a technique for creating dynamic web pages. It allows web pages to update asynchronously by exchanging small amounts of data with the server behind the scenes.
Example using fetch
:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));
Tags: intermediate, JavaScript, AJAX
An anonymous function is a function that is declared without a name. It is often used as a callback or in situations where the function does not need to be referenced elsewhere.
Example:
const greet = function() { console.log('Hello'); };
greet(); // 'Hello'
Tags: basic, JavaScript, functions
URL: https://www.tiktok.com/@jsmentoring/photo/7459468048118861089
The app shell model is a design approach where the static structure of a web app (such as HTML, CSS, and JavaScript) is cached and loaded first, followed by dynamic content. This approach is used in Progressive Web Apps (PWAs).
Tags: basic, JavaScript, web development
URL: https://www.tiktok.com/@jsmentoring/photo/7456136059966049568
The arguments
object is an array-like object available within all non-arrow functions. It contains the values of all arguments passed to the function.
function test() {
console.log(arguments);
}
test(1, 2, 3); // { '0': 1, '1': 2, '2': 3 }
Tags: basic, JavaScript, functions
URL: https://www.tiktok.com/@jsmentoring/photo/7455473337897061664
An async
function is a function that always returns a Promise
. It allows you to write asynchronous code using the await
keyword, which pauses the execution until the Promise
resolves or rejects.
Example:
async function fetchData() {
let response = await fetch('https://api.example.com');
let data = await response.json();
console.log(data);
}
fetchData();
Tags: basic, JavaScript, Asynchronous Programming
An empty statement in JavaScript is a statement that does nothing. It is represented by a semicolon (;
) on its own. Although it does not perform any action, it can be used in loops, conditionals, or in places where a statement is syntactically required.
Example:
for (let i = 0; i < 5; i++) { ; }
// No operation happens in the loop, but the loop is still valid
Tags: basic, JavaScript, statements
URL: https://www.tiktok.com/@jsmentoring/photo/7462028520613547296
An enum
(short for 'enumeration') is a feature in programming languages like TypeScript, which allows you to define a set of named constants. Enums help in making code more readable and maintainable by giving meaningful names to values.
Example in TypeScript:
enum Color {
Red = 'RED',
Green = 'GREEN',
Blue = 'BLUE'
}
let color: Color = Color.Red;
console.log(color); // 'RED'
Tags: intermediate, JavaScript, TypeScript
URL: https://www.tiktok.com/@jsmentoring/photo/7465480690658725152
An environment record is an internal data structure that holds variables and function declarations in a particular scope. It is part of the execution context and includes:
-
Declarative Environment Record:
- Stores variables and functions declared with
var
,let
, andconst
.
- Stores variables and functions declared with
-
Object Environment Record:
- Stores bindings for global objects or
with
statements.
- Stores bindings for global objects or
Example:
function example() {
let a = 10; // Stored in Declarative Environment Record
var b = 20; // Stored in Declarative Environment Record
}
Tags: advanced, JavaScript, Execution Context
The Error
object in JavaScript is used to represent runtime errors. It provides information about the error, such as its name, message, and stack trace.
Example:
try {
throw new Error('Something went wrong');
} catch (e) {
console.log(e.name); // 'Error'
console.log(e.message); // 'Something went wrong'
}
Tags: basic, JavaScript, errors
URL: https://www.tiktok.com/@jsmentoring/photo/7460422441794391329
Event delegation is a technique where you attach a single event listener to a parent element, which handles events for its child elements. This is more efficient than adding event listeners to each child element individually.
Tags: intermediate, JavaScript, events
URL: https://www.tiktok.com/@jsmentoring/photo/7455085016050060576
The event loop is a fundamental concept in JavaScript's concurrency model. It is responsible for executing code, handling events, and executing queued messages (tasks). The event loop continuously checks the call stack and event queue, ensuring that asynchronous tasks are executed when the call stack is empty.
Example:
console.log('Start');
setTimeout(() => console.log('Timeout'), 0);
console.log('End');
// Output: 'Start', 'End', 'Timeout'
Tags: basic, JavaScript, concurrency model
The event queue (or message queue) is a data structure that holds tasks (or events) that are waiting to be processed. When the call stack is empty, the event loop pushes the first task from the event queue onto the stack for execution.
Example:
setTimeout(() => console.log('Event'), 0);
console.log('Start');
// Output: 'Start', 'Event'
Tags: basic, JavaScript, concurrency model
URL: https://www.tiktok.com/@jsmentoring/photo/7461560136851639585
An event table is a structure used by the JavaScript engine to manage event handling. It tracks which event listeners are registered for specific events, ensuring that when an event occurs, the appropriate listener is invoked.
Tags: advanced, JavaScript, Event Loop
The Intl
object in JavaScript provides functionality for internationalization, including methods for formatting numbers, dates, and currencies, and for comparing strings according to a specific locale.
Example:
const number = 123456.789;
const formatter = new Intl.NumberFormat('en-US');
console.log(formatter.format(number)); // '123,456.789'
Tags: basic, JavaScript, internationalization
URL: https://www.tiktok.com/@jsmentoring/photo/7461350028158815521
An iterator is an object that provides a way to access elements of a collection (such as arrays or maps) one at a time. It conforms to the Iterator
protocol, which includes methods like next()
, return()
, and throw()
.
Example:
const arr = [1, 2, 3];
const iterator = arr[Symbol.iterator]();
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
Tags: basic, JavaScript, iterators
URL: https://www.tiktok.com/@jsmentoring/photo/7460104729561992481
An object initializer (or object literal) is a way to create and initialize an object in JavaScript. It uses curly braces {}
and defines key-value pairs for the properties of the object.
Example:
const person = { name: 'John', age: 30 };
console.log(person.name); // John
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7463237018944916769
An Observable is a representation of a stream of values or events that can be observed over time. Observables are the core concept in reactive programming and are widely used in libraries like RxJS to manage asynchronous operations.
An observable can emit values, complete, or throw errors.
Example:
import { Observable } from 'rxjs';
let observable = new Observable(observer => {
observer.next('Hello');
observer.complete();
});
observable.subscribe(value => console.log(value));
**Tags**: [advanced](./level/advanced), [JavaScript](./theme/javascript), [RxJS](./theme/rxjs)
---
### What is an Unary operator?
An unary operator is an operator that operates on a single operand. It performs operations like negation, increment, and decrement.
Examples of unary operators include:
- `+` (Unary plus)
- `-` (Unary minus)
- `++` (Increment)
- `--` (Decrement)
- `!` (Logical NOT)
Example:
```javascript
let a = 5;
console.log(++a); // 6
console.log(a++); // 6
console.log(a); // 7
Tags: basic, JavaScript, operators
URL: https://www.tiktok.com/@jsmentoring/photo/7461747077505109281
ArrayBuffer
is a JavaScript object used to represent a generic, fixed-length raw binary data buffer. It is typically used when working with binary data, such as file processing, network requests, or Web APIs like WebSockets.
Example:
let buffer = new ArrayBuffer(16); // 16 bytes buffer
let view = new Uint8Array(buffer); // Typed array view
view[0] = 255;
console.log(view[0]); // Output: 255
Tags: intermediate, JavaScript, Binary Data
Babel is a JavaScript compiler that allows you to write next-generation JavaScript code (ES6/ES7+) and transform it into code that can run on older browsers or environments. Babel can also be used to compile JSX for React applications.
Example of a Babel transformation:
let greet = () => console.log('Hello'); // ES6 arrow function
Tags: intermediate, JavaScript, Tools
The Browser Object Model (BOM) allows JavaScript to interact with the browser outside of the DOM. It includes objects like window
, navigator
, screen
, and location
, enabling you to control browser-related functions.
Tags: intermediate, JavaScript, browser
URL: https://www.tiktok.com/@jsmentoring/photo/7454626475623468320
The call stack is a stack data structure that stores information about the active execution context of a program. When a function is called, it is added to the stack, and when it finishes executing, it is removed from the stack.
Example:
function a() {
b();
}
function b() {
console.log('Hello');
}
a();
// Call stack will be: [a(), b()]
Tags: basic, JavaScript, execution context
URL: https://www.tiktok.com/@jsmentoring/photo/7460132409997069601
Collation refers to the rules for comparing and sorting strings based on locale-specific conventions. In JavaScript, the Intl.Collator
object is used to perform locale-sensitive string comparison and sorting.
Example:
let collator = new Intl.Collator('en', { sensitivity: 'base' });
let result = collator.compare('apple', 'banana');
console.log(result); // Output: -1
Tags: advanced, JavaScript, Internationalization
Debouncing ensures that a function is called only after a specified time has passed since the last invocation. It is useful for optimizing performance in scenarios like input fields or resizing events.
Example:
function debounce(func, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, args), delay);
};
}
const log = debounce(() => console.log('Debounced!'), 300);
window.addEventListener('resize', log);
Tags: intermediate, JavaScript, Performance
Deno is a modern, secure runtime for JavaScript and TypeScript, built on V8 and written in Rust. It was created by Ryan Dahl, the original creator of Node.js, to address some of Node.js's design limitations.
Features:
- Secure by default (no file, network, or environment access without explicit permission).
- Supports TypeScript out of the box.
- Uses ES modules instead of CommonJS.
Example:
// Example Deno script
console.log('Hello, Deno!');
Tags: intermediate, JavaScript, Runtime
Destructuring aliases allow you to rename variables when destructuring an object or array. This is useful when the variable names in the object/array do not match your desired variable names.
Example:
let person = { name: 'Alice', age: 25 };
let { name: fullName, age: yearsOld } = person;
console.log(fullName); // Output: 'Alice'
console.log(yearsOld); // Output: 25
Tags: intermediate, JavaScript, Destructuring
Destructuring assignment is a convenient way to extract values from arrays or objects and assign them to variables. It can be used with arrays, objects, and even nested structures.
Example with array:
let [x, y] = [1, 2];
console.log(x, y); // Output: 1 2
Example with object:
let { name, age } = { name: 'John', age: 30 };
console.log(name, age); // Output: John 30
Tags: intermediate, JavaScript, Destructuring
URL: https://www.tiktok.com/@jsmentoring/photo/7470674451730910486
ECMAScript is the standard specification that JavaScript is based on. It defines the core features and behavior of JavaScript, and different versions of ECMAScript introduce new features to the language.
Tags: basic, JavaScript, standards
URL: https://www.tiktok.com/@jsmentoring/photo/7453531864133815584
ES6 (ECMAScript 2015) is the sixth version of the ECMAScript standard, which defines the scripting language that JavaScript is based on. ES6 introduced many new features, such as let
, const
, arrow functions, promises, and modules, making JavaScript more powerful and easier to work with.
Tags: intermediate, JavaScript, ES6
URL: https://www.tiktok.com/@jsmentoring/photo/7469442691240185121
Event capturing is the process where an event is first captured by the outermost element before it reaches the target element. This is the opposite of event bubbling.
Tags: intermediate, JavaScript, events
URL: https://www.tiktok.com/@jsmentoring/photo/7451534594895056160
The for...of
statement is used to iterate over the values of iterable objects (like arrays, strings, maps, etc.) in JavaScript. It provides a simpler syntax than traditional loops and works well with iterables.
Example:
let arr = [10, 20, 30];
for (let value of arr) {
console.log(value);
}
// Output: 10 20 30
Tags: intermediate, JavaScript, Loops
Function composition is the process of combining two or more functions to produce a new function. The output of one function becomes the input of the next.
Example:
const add = x => x + 1;
const multiply = x => x * 2;
const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x);
const composed = compose(multiply, add);
console.log(composed(5)); // 12
Tags: advanced, JavaScript, Functional Programming
A function execution context is created when a function is invoked. It contains:
-
this
Binding:- Depends on how the function is called.
-
Scope Chain:
- Includes variables from the function's scope and its outer lexical environments.
-
Variable Environment:
- Stores function variables and parameters.
Example:
function example() {
var a = 10; // Stored in variable environment
console.log(this); // Depends on invocation
}
example();
Tags: intermediate, JavaScript, Execution Context
The global execution context is the default context in which JavaScript code runs. It is created when a JavaScript file is executed and contains:
-
Global Object:
- In browsers, this is the
window
object.
- In browsers, this is the
-
this
Keyword:- Refers to the global object in non-strict mode.
-
Global Variables and Functions:
- All declared variables and functions at the top level.
Example:
console.log(this); // window in browsers
var a = 10; // Part of global execution context
Tags: intermediate, JavaScript, Execution Context
globalThis
provides a standard way to access the global object across different environments (browser, Node.js, etc.).
-
Universal Access:
- Replaces environment-specific global objects like
window
,global
, orself
.
- Replaces environment-specific global objects like
-
Example:
console.log(globalThis); // In browsers, equivalent to window.
Tags: basic, JavaScript, Global Objects
The heap is a region of memory used for dynamic memory allocation in JavaScript. It is used for storing objects and arrays, and its size can grow or shrink during program execution.
When an object is created, it is stored in the heap, while primitive types are stored in the stack.
Tags: intermediate, JavaScript, Memory
Inline caching is a JavaScript engine optimization technique that speeds up property access by caching the results of previous lookups.
-
Purpose:
- Reduce the overhead of repeatedly resolving the same property or method on an object.
-
How It Works:
- During the first lookup, the engine determines the property location and caches it.
- On subsequent accesses, the engine uses the cached result, bypassing the need for lookup.
Example:
function add(a, b) {
return a.value + b.value;
}
const obj1 = { value: 10 };
const obj2 = { value: 20 };
console.log(add(obj1, obj2)); // Inline caching optimizes property access.
Tags: advanced, JavaScript, V8 Engine
jQuery is a fast, small, and feature-rich JavaScript library. It simplifies tasks such as DOM manipulation, event handling, animation, and Ajax requests. It provides a simple API that works across all browsers.
Example:
$(document).ready(function() {
$('#myElement').hide();
});
Tags: basic, JavaScript, libraries
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is often used to exchange data between a client and server.
Tags: basic, JavaScript, data formats
URL: https://www.tiktok.com/@jsmentoring/photo/7456025885263629601
Lexical scope refers to the scope determined by the physical structure of the code. It is defined at compile time and based on where variables and functions are declared.
-
Inner Functions:
- Inner functions can access variables declared in their outer scope.
-
Compile-Time Binding:
- Scope is determined when the code is written, not during execution.
Example:
function outer() {
const outerVar = 'I am outer';
function inner() {
console.log(outerVar); // Accessible due to lexical scope.
}
inner();
}
outer();
Tags: basic, JavaScript, Scope
MEAN is an acronym for a stack of technologies used for building web applications:
- MongoDB: A NoSQL database.
- Express.js: A web application framework for Node.js.
- Angular: A front-end framework for building single-page applications.
- Node.js: A runtime environment for executing JavaScript on the server-side.
The MEAN stack provides a full-stack JavaScript solution for both client-side and server-side development.
Tags: basic, JavaScript, frameworks
URL: https://www.tiktok.com/@jsmentoring/photo/7463877222730911008
A microtask is a type of task that is executed after the currently executing script, but before the next task is processed. Microtasks are typically used for promises and other asynchronous operations.
Microtasks are executed after the current task completes, but before the rendering or other macrotasks are handled.
Example of a microtask:
Promise.resolve().then(() => console.log('Microtask executed'));
**Tags**: [advanced](./level/advanced), [JavaScript](./theme/javascript), [Event Loop](./theme/event_loop)
**URL**: [https://www.tiktok.com/@jsmentoring/photo/7459906574425902368](https://www.tiktok.com/@jsmentoring/photo/7459906574425902368)
---
### What is Minification?
Minification is the process of removing unnecessary characters from JavaScript code, such as whitespace, comments, and newline characters, without affecting the functionality of the code. This is done to reduce the file size and improve the performance of web applications by decreasing load times.
Example:
```javascript
// Original Code
function sum(a, b) {
return a + b;
}
// Minified Code
function sum(a,b){return a+b;}
Tags: intermediate, JavaScript, optimization
URL: https://www.tiktok.com/@jsmentoring/photo/7462868427363994913
Minimum timeout throttling refers to the browser's behavior of enforcing a minimum delay for setTimeout
and setInterval
calls. This is done to avoid excessive resource consumption, especially in high-frequency scenarios like animations or polling.
For example, in modern browsers, the minimum delay is typically 4ms for background tabs and 0ms for the active tab.
setTimeout(() => console.log('Executed after delay'), 0);
Tags: advanced, JavaScript, Performance
The Module Pattern is a design pattern used to encapsulate private and public variables and methods. It provides a way to create a namespace and control access to certain parts of code.
Example:
const myModule = (function() {
let privateVar = 'I am private';
function privateMethod() {
console.log(privateVar);
}
return {
publicMethod: function() {
privateMethod();
}
};
})();
myModule.publicMethod(); // 'I am private'
console.log(myModule.privateVar); // undefined
Tags: intermediate, JavaScript, Design Patterns
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It allows developers to run JavaScript code outside of a browser, typically for building server-side applications.
Example:
// A simple Node.js server
const http = require('http');
const server = http.createServer((req, res) => {
res.write('Hello, world!');
res.end();
});
server.listen(3000);
Tags: basic, JavaScript, runtime
The ??
operator returns the right-hand operand if the left-hand operand is null
or undefined
. It is useful for providing default values.
Example:
const value = null;
console.log(value ?? 'default'); // Output: 'default'
const number = 0;
console.log(number ?? 42); // Output: 0
Tags: basic, JavaScript, Operators
Obfuscation in JavaScript refers to the process of making code difficult to understand or read by humans. This is typically done to protect the code from reverse engineering or tampering. It involves techniques like renaming variables and functions to meaningless names, removing whitespace, and making the code less readable.
Example:
// Original Code
function add(a, b) { return a + b; }
// Obfuscated Code
var _0x1234 = function(_0x5678, _0x9abc) { return _0x5678 + _0x9abc; };
Tags: intermediate, JavaScript, security
URL: https://www.tiktok.com/@jsmentoring/photo/7462863313496509729
The optional chaining operator (?.
) allows safe access to deeply nested object properties without worrying about null
or undefined
errors.
Example:
const user = { profile: { name: 'Alice' } };
console.log(user.profile?.name); // 'Alice'
console.log(user.address?.street); // undefined
Tags: basic, JavaScript, Operators
URL: https://www.tiktok.com/@jsmentoring/photo/7459817458866687264
In JavaScript:
-
Pass by Value:
- For primitives (e.g., numbers, strings), the value is copied.
- Changes to the copied variable do not affect the original.
-
Pass by Reference:
- For objects and arrays, a reference to the memory location is passed.
- Changes to the reference affect the original object.
Example:
let x = 10; // Primitive
let y = x;
y = 20;
console.log(x); // 10 (pass by value)
let obj1 = { key: 'value' }; // Non-primitive
let obj2 = obj1;
obj2.key = 'newValue';
console.log(obj1.key); // 'newValue' (pass by reference)
Tags: intermediate, JavaScript, Memory Management
A function is referentially transparent if it can be replaced with its output value without changing the program's behavior. It is a key property of pure functions.
Example:
// Referentially Transparent
function add(a, b) {
return a + b;
}
const result = add(2, 3); // Can replace 'add(2, 3)' with 5
console.log(result); // 5
// Not Referentially Transparent
let count = 0;
function increment() {
return ++count;
}
Tags: advanced, JavaScript, Functional Programming
RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using Observables. It enables you to compose asynchronous and event-based programs using operators like map
, filter
, merge
, and more.
RxJS allows you to work with streams of data in a declarative manner, making it easier to manage complex asynchronous flows.
Example:
import { from } from 'rxjs';
from([1, 2, 3]).subscribe(x => console.log(x));
Tags: advanced, JavaScript, RxJS
The same-origin policy is a security measure that restricts how a document or script loaded from one origin can interact with resources from another origin.
Tags: intermediate, JavaScript, security
URL: https://www.tiktok.com/@jsmentoring/photo/7454519704300948768
The comma operator allows you to evaluate multiple expressions and return the result of the last one, all within a single statement. This can help in certain cases where you want to write concise code, especially in loops or complex expressions.
Example:
let x = (a = 1, b = 2, a + b);
console.log(x); // 3
Tags: basic, JavaScript, operators
URL: https://www.tiktok.com/@jsmentoring/photo/7462499238195236128
A parameter is a variable defined in the function definition, while an argument is the actual value passed to the function when it is called.
Example:
function greet(name) { // 'name' is the parameter
console.log('Hello ' + name);
}
greet('John'); // 'John' is the argument
Tags: basic, JavaScript, Functions
An attribute is a value set in the HTML (e.g., src
in an img
tag), while a property is a value associated with the element in JavaScript (e.g., element.src
).
Tags: basic, JavaScript, DOM
URL: https://www.tiktok.com/@jsmentoring/photo/7453198212661382432
-
Dense Arrays:
- All indices have elements assigned.
- Example:
const denseArray = [1, 2, 3]; console.log(denseArray.length); // 3
-
Sparse Arrays:
- Some indices are missing (unassigned).
- Example:
const sparseArray = [1, , 3]; console.log(sparseArray.length); // 3 console.log(sparseArray[1]); // undefined
Tags: intermediate, JavaScript, Arrays
The DOMContentLoaded
event fires when the HTML is completely loaded and parsed, while the load
event waits for all resources (including images and stylesheets) to load.
Tags: intermediate, JavaScript, events
URL: https://www.tiktok.com/@jsmentoring/photo/7451559472939437344
-
Function Declarations:
- Can be hoisted, meaning they can be used before they are declared in the code.
- Syntax:
function functionName() {}
-
Class Declarations:
- Cannot be hoisted, so they must be declared before use.
- Syntax:
class ClassName {}
Example:
console.log(foo()); // Works because of hoisting
function foo() { return 'Hello'; }
// console.log(new Bar()); // Error: Bar is not defined
class Bar { constructor() { console.log('Bar created'); } }
Tags: intermediate, JavaScript, Declarations
- Function Declaration: A function declared using the
function
keyword and is hoisted, meaning it is available throughout the scope.
function greet() { console.log('Hello'); }
- Function Constructor: A function created using the
Function
constructor. This approach is less commonly used and has a few limitations, such as not allowing for closures.
let greet = new Function('console.log("Hello")');
Tags: intermediate, JavaScript, Functions
get
is used to define a getter method that returns the value of a property when accessed.Object.defineProperty()
allows you to define or modify a property directly on an object, including setting getters, setters, or other property attributes.
Example:
const person = {
firstName: 'John',
lastName: 'Doe',
get fullName() { return this.firstName + ' ' + this.lastName; }
};
console.log(person.fullName); // 'John Doe'
Tags: basic, JavaScript, objects
Internal JavaScript is written directly inside the <script>
tag within an HTML document, while external JavaScript is placed in a separate .js
file that is linked to the HTML using the src
attribute.
Example of internal JavaScript:
<script>
console.log('Internal JS');
</script>
Example of external JavaScript:
<script src='script.js'></script>
Tags: basic, JavaScript, Script Tag
-
isNaN
:- Converts the input to a number and checks if it's
NaN
. - May give misleading results for non-number inputs.
- Converts the input to a number and checks if it's
-
Number.isNaN
:- Checks strictly if the value is
NaN
. - Doesn't coerce the input.
- Checks strictly if the value is
Example:
console.log(isNaN('hello')); // true (coerced to NaN)
console.log(Number.isNaN('hello')); // false (strict check)
Tags: basic, JavaScript, Numbers
Java and JavaScript are two distinct programming languages with different use cases:
- Java: A statically typed, object-oriented language mainly used for backend development, mobile apps (Android), and enterprise-level applications.
- JavaScript: A dynamically typed, interpreted language used for frontend development to create interactive web pages and dynamic content.
Despite the similar names, they are unrelated in terms of syntax and functionality.
Tags: basic, JavaScript, comparison
URL: https://www.tiktok.com/@jsmentoring/photo/7468299270974754081
-
Return Value:
map
returns a new array with the results of the callback function.forEach
does not return anything (undefined).
-
Purpose:
map
is used when you want to transform each element in an array.forEach
is used when you want to perform side effects like logging or updating an external variable.
Example:
const numbers = [1, 2, 3];
// map
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
// forEach
numbers.forEach(num => console.log(num * 2)); // Logs: 2, 4, 6
Tags: basic, JavaScript, Array Methods
Native objects are built-in objects like Object
and Array
. Host objects are provided by the environment (e.g., browser or Node.js), like window
or document
. User objects are those defined by the developer.
Tags: advanced, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7451546871723576608
proto
is an internal property (or link) to the object's prototype, while prototype
is a property of functions (used to create new objects) that defines methods and properties shared by all instances.
Example:
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log('Hello ' + this.name);
};
Tags: basic, JavaScript, objects
Reflow is the process where the browser recalculates the layout of the page, whereas repaint only redraws elements that have changed visually, without affecting the layout.
Example:
// Reflow happens when you modify layout-affecting properties like width/height
document.body.style.width = '500px'; // Triggers reflow
// Repaint happens when you modify visual properties like background-color
document.body.style.backgroundColor = 'red'; // Triggers repaint
Tags: advanced, JavaScript, Performance
-
setTimeout
:- Executes code after a minimum delay.
- Example:
setTimeout(() => console.log('Timeout'), 0);
-
setImmediate
:- Executes code after the current event loop cycle.
- Example:
setImmediate(() => console.log('Immediate'));
-
process.nextTick
:- Executes code before the next event loop iteration.
- Example:
process.nextTick(() => console.log('Next Tick'));
Tags: advanced, Node.js, Timers
A shallow copy copies only the top-level properties of an object or array, meaning nested objects or arrays are shared. A deep copy copies all properties, including nested ones, so that no references to the original object exist.
Example of shallow copy:
let arr = [1, [2, 3]];
let shallowCopy = arr.slice();
shallowCopy[1][0] = 99;
console.log(arr); // Output: [1, [99, 3]]
Example of deep copy (using JSON.parse()
and JSON.stringify()
):
let deepCopy = JSON.parse(JSON.stringify(arr));
deepCopy[1][0] = 100;
console.log(arr); // Output: [1, [99, 3]]
console.log(deepCopy); // Output: [1, [100, 3]]
Tags: intermediate, JavaScript, Objects
-
Shim: A shim is a piece of code that provides functionality that is not natively supported in certain environments. It can add support for missing features, but does not necessarily match the specification exactly.
-
Polyfill: A polyfill is a more complete implementation of a feature that mimics the behavior of a native feature. It aims to fill in the gaps where the feature is not supported by older browsers or environments.
Example of a polyfill for Array.prototype.includes
:
if (!Array.prototype.includes) {
Array.prototype.includes = function(value) {
return this.indexOf(value) !== -1;
};
}
Tags: intermediate, JavaScript, Compatibility
-
substring(start, end)
:- Extracts characters between
start
andend
(exclusive).
- Extracts characters between
-
substr(start, length)
:- Extracts characters starting at
start
and spanninglength
characters.
- Extracts characters starting at
Example:
const str = 'JavaScript';
console.log(str.substring(0, 4)); // 'Java'
console.log(str.substr(0, 4)); // 'Java'
Tags: basic, JavaScript, String Methods
eval()
executes a string of JavaScript code as if it were a part of the script.uneval()
(deprecated) was used to return a string representation of an object, similar toJSON.stringify()
.
Example:
const code = 'console.log("Hello")';
eval(code); // Executes code
Tags: basic, JavaScript, eval
URL: https://www.tiktok.com/@jsmentoring/photo/7459446884436905249
The easiest way to check multiple conditions is by using logical operators like &&
(AND) or ||
(OR).
Example using &&
(AND):
let x = 5, y = 10;
if (x > 0 && y > 5) {
console.log('Both conditions are true');
}
Example using ||
(OR):
let x = 5, y = 2;
if (x > 0 || y > 5) {
console.log('At least one condition is true');
}
Tags: basic, JavaScript, Conditionals
You can use reduce()
to convert an array into an object, where each element becomes a key-value pair.
Example:
let arr = ['apple', 'banana', 'cherry'];
let obj = arr.reduce((acc, curr, index) => {
acc[index] = curr;
return acc;
}, {});
console.log(obj); // Output: { 0: 'apple', 1: 'banana', 2: 'cherry' }
Tags: intermediate, JavaScript, Arrays
To ignore promise errors, you can attach an empty catch
block to the promise chain:
fetch('invalid-url')
.then(response => response.json())
.catch(() => {}); // Errors are ignored here
Alternatively, use try...catch
in an async
function and leave the catch
block empty:
async function fetchData() {
try {
const response = await fetch('invalid-url');
} catch {}
}
Tags: basic, JavaScript, Promises
The easiest way to resize an array is by using the length
property. You can truncate the array or expand it by setting its length.
Example:
let arr = [1, 2, 3];
arr.length = 2; // Truncate the array
console.log(arr); // Output: [1, 2]
arr.length = 5; // Expand the array
console.log(arr); // Output: [1, 2, <3 empty slots>]
**Tags**: [intermediate](./level/intermediate), [JavaScript](./theme/javascript), [Arrays](./theme/arrays)
---
### What is the main difference between Object.values and Object.entries method?
- `Object.values()` returns an array of the object's values.
- `Object.entries()` returns an array of key-value pairs.
Example:
```javascript
const person = { name: 'John', age: 30 };
console.log(Object.values(person)); // ['John', 30]
console.log(Object.entries(person)); // [['name', 'John'], ['age', 30]]
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7458282098579737889
Tree shaking is necessary to eliminate dead code, improve the performance of web applications, and reduce the size of JavaScript bundles, leading to faster load times and better user experiences.
Tags: basic, JavaScript, optimization
URL: https://www.tiktok.com/@jsmentoring/photo/7456574498947599648
The unary operator can perform various operations such as negation, increment, and others. It operates on a single operand.
Example:
let num = '5';
console.log(+num); // Output: 5
Tags: intermediate, JavaScript, Operators
This type of question tests your understanding of function execution, scope, and closures in JavaScript.
Example:
function foo() {
return 'Hello, World!';
}
console.log(foo()); // Output: 'Hello, World!'
Tags: intermediate, JavaScript, Functions
The spread operator (...
) allows you to expand elements of an array into individual elements. It can be used to clone an array, combine arrays, or pass array elements as function arguments.
Example:
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5];
console.log(arr2); // Output: [1, 2, 3, 4, 5]
Tags: intermediate, JavaScript, Spread Operator
URL: https://www.tiktok.com/@jsmentoring/photo/7457941742650789152
The output of a string expression depends on the specific operation being performed. For example, concatenation, trimming, or other string manipulations will yield different results.
Example:
let str = 'Hello' + ' ' + 'World';
console.log(str); // Output: 'Hello World'
Tags: intermediate, JavaScript, String Manipulation
The +
operator is used to convert values to strings. When you use it with falsy values like false
, 0
, null
, undefined
, or NaN
, the result will be their string representation.
Example:
console.log(+false); // Output: 0
console.log(+0); // Output: 0
console.log(+null); // Output: 0
console.log(+undefined); // Output: NaN
console.log(+NaN); // Output: NaN
Tags: intermediate, JavaScript, Operators
Here’s an example of a loop in JavaScript and its output:
for (let i = 0; i < 3; i++) {
console.log(i);
}
Output:
0
1
2
Tags: basic, JavaScript, Loops
URL: https://www.tiktok.com/@jsmentoring/photo/7469419711726488865
In JavaScript, when a variable is declared both globally and locally, the local variable takes precedence over the global variable within the function scope.
Example:
let name = 'Global';
function greet() {
let name = 'Local';
console.log(name); // 'Local'
}
greet();
console.log(name); // 'Global'
Tags: basic, JavaScript, variables
URL: https://www.tiktok.com/@jsmentoring/photo/7459521760090787105
JSON.stringify()
is used to convert a JavaScript object into a JSON string, which can be sent to a server or stored for later use.
Tags: basic, JavaScript, data formats
URL: https://www.tiktok.com/@jsmentoring/photo/7458382016141200673
Breakpoints are used in debugging to pause the execution of JavaScript at a specific point. This allows you to inspect variables, control flow, and diagnose issues.
Example: You can set a breakpoint in the browser's developer tools to pause execution at a specific line.
Tags: basic, JavaScript, debugging
URL: https://www.tiktok.com/@jsmentoring/photo/7457249779840486688
The clearInterval()
method is used to cancel a timeout set by setInterval()
. It stops the function from being called repeatedly after the specified interval.
Tags: basic, JavaScript, timing
URL: https://www.tiktok.com/@jsmentoring/photo/7457687525340089633
The clearTimeout()
method is used to cancel a timeout that was previously established by calling setTimeout()
. It prevents the function from being executed after the specified delay.
Tags: basic, JavaScript, timing
URL: https://www.tiktok.com/@jsmentoring/photo/7453583130859949344
The compareFunction
in the sort()
method allows you to define custom sorting logic. By default, sort()
converts elements to strings and sorts them lexicographically. The compareFunction
allows you to specify how the elements should be compared, typically using numerical comparison.
Example:
const arr = [3, 1, 2];
arr.sort((a, b) => a - b);
console.log(arr); // [1, 2, 3]
Tags: basic, JavaScript, arrays
URL: https://www.tiktok.com/@jsmentoring/photo/7461759054034128161
The console.dir()
method is used to display an interactive list of the properties of a specified JavaScript object. It is especially useful for inspecting DOM elements or complex objects.
Example:
let obj = { name: 'Alice', age: 25 };
console.dir(obj);
Tags: intermediate, JavaScript, Console
The double tilde (~~
) is a shorthand for converting a number to an integer by applying a bitwise NOT operation twice. It works by discarding the decimal part of the number, effectively performing a floor operation for positive numbers and ceiling for negative numbers.
Example:
let num = 4.7;
console.log(~~num); // Output: 4
Tags: intermediate, JavaScript, Operators
The Error
object in JavaScript is used to represent runtime errors in the application. It provides a stack trace and error message, helping developers diagnose issues. You can create custom error objects by extending the Error
class.
Example:
try {
throw new Error('Something went wrong');
} catch (e) {
console.log(e.message); // Output: Something went wrong
}
Tags: basic, JavaScript, Error Handling
EvalError
is an error object that is thrown when an issue occurs with the eval()
function. It is rarely used today as eval()
is generally avoided due to security concerns. The EvalError
object provides information about errors related to code evaluation.
Example:
try {
throw new EvalError('Eval error');
} catch (e) {
console.log(e.message); // Output: Eval error
}
Tags: intermediate, JavaScript, Error Handling
The exec()
method executes a search for a match in a string. It returns an array of matches, or null
if no match is found.
Example:
const regex = /\d+/;
console.log(regex.exec('abc123')); // ['123']
Tags: basic, JavaScript, regular expressions
URL: https://www.tiktok.com/@jsmentoring/photo/7456816176019082529
The purpose of Object.freeze()
is to make an object immutable. Once an object is frozen, you cannot alter its properties or add new ones, ensuring the integrity of the data.
Example:
const obj = { key: 'value' };
Object.freeze(obj);
obj.key = 'new value'; // Won't work
Tags: basic, JavaScript, objects
The queueMicrotask()
method is used to add a microtask to the event loop queue. It is similar to using a promise but ensures that the task will be executed as soon as the current task completes, before any rendering or other tasks.
Example:
queueMicrotask(() => console.log('Microtask executed'));
**Tags**: [advanced](./level/advanced), [JavaScript](./theme/javascript), [Event Loop](./theme/event_loop)
---
### What is the purpose of `requestAnimationFrame` method?
`requestAnimationFrame` is used to schedule animations in the browser for optimal performance.
#### Key Points:
1. **Synchronizes with Refresh Rate:**
- Ensures smooth animations by aligning with the screen refresh rate.
2. **Efficient Rendering:**
- Avoids unnecessary frame rendering when the tab is inactive.
Example:
```javascript
function animate() {
// Animation logic here
console.log('Animating...');
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
Tags: intermediate, JavaScript, Web APIs
The Object.seal()
method seals an object, preventing new properties from being added, but allowing modification of existing properties. The object is still mutable.
Example:
const person = { name: 'John' };
Object.seal(person);
person.name = 'Jane';
console.log(person.name); // 'Jane'
person.age = 30; // This won't work
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7458057057950895392
The some
method tests whether at least one element in the array passes the provided test function. It returns true
if any element meets the condition, otherwise false
.
Example:
let numbers = [1, 2, 3, 4, 5];
let hasEven = numbers.some(num => num % 2 === 0);
console.log(hasEven); // Output: true
Tags: basic, JavaScript, Arrays
The switch-case
statement is used to perform different actions based on different conditions. It is an alternative to multiple if-else
statements and is more readable when there are many conditions to check.
Example:
const fruit = 'apple';
switch(fruit) {
case 'apple':
console.log('Apple is selected');
break;
case 'banana':
console.log('Banana is selected');
break;
default:
console.log('Unknown fruit');
}
Tags: basic, JavaScript, control structures
URL: https://www.tiktok.com/@jsmentoring/photo/7459766080223841569
The this
keyword refers to the object that is executing the current function. Its value depends on how the function is called:
- In a Method: Refers to the object the method belongs to.
- In a Function (non-strict mode): Refers to the global object (
window
in browsers). - In a Function (strict mode): Undefined.
- In Arrow Functions: Inherits
this
from the enclosing scope.
Example:
const obj = {
name: 'Alice',
greet() {
console.log(`Hello, ${this.name}`);
}
};
obj.greet(); // 'Hello, Alice'
Tags: basic, JavaScript, Scope
uneval()
was used to return a string representation of an object or expression, similar to how eval()
works. However, uneval()
is deprecated and not supported in all environments.
Example:
const obj = { name: 'John' };
console.log(uneval(obj)); // '({ name: "John" })'
Tags: basic, JavaScript, eval
URL: https://www.tiktok.com/@jsmentoring/photo/7459148995630337313
Object.is()
is used to compare two values to check if they are the same. It is similar to ===
but handles special cases like NaN
and -0
differently.
Example:
console.log(Object.is(-0, +0)); // false
console.log(Object.is(NaN, NaN)); // true
Tags: basic, JavaScript, objects
void 0
is used to return undefined
in JavaScript. It's a more reliable method than using undefined
directly, which can be overwritten in some cases.
Tags: advanced, JavaScript, operators
URL: https://www.tiktok.com/@jsmentoring/video/7454350834697080096
In JavaScript, you can get the current timestamp (in milliseconds) using the Date.now()
method or new Date().getTime()
.
Example:
let timestamp = Date.now();
console.log(timestamp); // Output: current timestamp in milliseconds
Tags: basic, JavaScript, Date
The preventDefault()
method is used to cancel the default behavior of an event. For example, you can prevent the form from submitting or a link from navigating to a new page.
Tags: basic, JavaScript, events
URL: https://www.tiktok.com/@jsmentoring/photo/7454611976598113568
The setInterval()
method calls a function or code snippet repeatedly, with a fixed time delay between each call. It's useful for creating repeating actions.
setInterval(function(){ console.log('Hello!'); }, 1000);
Tags: basic, JavaScript, timing
URL: https://www.tiktok.com/@jsmentoring/photo/7455059689315896609
The setTimeout()
method is used to execute a function or code snippet after a specified delay in milliseconds. It's useful for delaying the execution of a task.
setTimeout(function(){ alert('Hello!'); }, 2000);
Tags: basic, JavaScript, timing
URL: https://www.tiktok.com/@jsmentoring/photo/7453766380433722656
The stopPropagation()
method prevents the event from propagating (bubbling) up or down the DOM tree. This is useful for preventing parent elements from handling events triggered by child elements.
Tags: basic, JavaScript, events
URL: https://www.tiktok.com/@jsmentoring/photo/7454613743649951008
You can use the length
property of a function to find the number of parameters it expects.
function test(a, b, c) {}
console.log(test.length); // 3
Tags: basic, JavaScript, functions
URL: https://www.tiktok.com/@jsmentoring/photo/7456397129393704224
Throttling ensures that a function is called at most once in a specified time interval. It is useful for rate-limiting events like scrolling or resizing.
Example:
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}
const log = throttle(() => console.log('Throttled!'), 1000);
window.addEventListener('scroll', log);
Tags: intermediate, JavaScript, Performance
Tree shaking is a process used in JavaScript bundlers (like Webpack) to remove unused code from the final bundle. It helps reduce the size of the final output and improves performance.
Tags: basic, JavaScript, optimization
URL: https://www.tiktok.com/@jsmentoring/photo/7456569241815354657
TypeScript is a superset of JavaScript that adds static types and modern features to the language. It allows you to write code with type annotations, which helps with early error detection, better tooling, and improved code maintainability. TypeScript code is transpiled to regular JavaScript.
Example:
let num: number = 10;
let str: string = 'Hello';
Tags: basic, TypeScript
V8 is an open-source JavaScript engine developed by Google. It is used in Chrome and Node.js. V8 compiles JavaScript directly to native machine code for fast execution.
V8 optimizes JavaScript performance through techniques like Just-In-Time (JIT) compilation and garbage collection.
Tags: intermediate, JavaScript, engines
URL: https://www.tiktok.com/@jsmentoring/photo/7468430768063122721
The Web Speech API provides the ability to recognize and synthesize speech in web applications. It consists of two parts: the Speech Recognition API and the Speech Synthesis API.
- Speech Recognition API: Allows the recognition of speech and converts it into text.
- Speech Synthesis API: Allows the synthesis of speech from text.
Example of Speech Synthesis:
let utterance = new SpeechSynthesisUtterance('Hello, World!');
speechSynthesis.speak(utterance);
Tags: advanced, JavaScript, Web APIs
JavaScript is a multi-paradigm language, supporting functional, object-oriented, and imperative programming styles. It allows you to write code in a variety of styles depending on the needs of the application.
Example of functional style:
let add = (a, b) => a + b;
console.log(add(2, 3)); // Output: 5
Tags: intermediate, JavaScript, Programming Paradigms
In JavaScript, 1 + 2 + '3'
results in '33'
because the +
operator first adds the numbers (1 + 2 = 3
) and then concatenates the result with the string '3'
.
Example:
console.log(1 + 2 + '3'); // '33'
Tags: basic, JavaScript, type coercion
URL: https://www.tiktok.com/@jsmentoring/photo/7456799873505987873
A SyntaxError
occurs when the JavaScript engine encounters code that doesn't conform to the syntax rules of the language. Common causes include missing brackets, semicolons, or incorrect use of keywords.
Example:
// Missing closing bracket
if (true) {
console.log('Hello');
Tags: basic, JavaScript, errors
URL: https://www.tiktok.com/@jsmentoring/photo/7460430178938834209
JavaScript was created by Brendan Eich in 1995 while working at Netscape Communications Corporation. It was originally called Mocha, then renamed to LiveScript, and finally to JavaScript.
Tags: basic, JavaScript, history
URL: https://www.tiktok.com/@jsmentoring/photo/7454609808038153504
Using Object.freeze()
is useful when you want to ensure that the object’s properties cannot be changed, helping to prevent bugs caused by unintended modifications.
Example:
const config = { maxLimit: 100 };
Object.freeze(config);
config.maxLimit = 200; // Won't work
Tags: basic, JavaScript, objects
URL: https://www.tiktok.com/@jsmentoring/photo/7457632028364737825
JavaScript is considered a dynamic language because it supports dynamic typing, meaning that variables do not have a fixed type. You can assign any type of value to a variable at runtime, and it can change its type during execution.
Example:
let dynamicVar = 10; // Number
dynamicVar = 'Hello'; // String
Tags: basic, JavaScript, Language features
URL: https://www.tiktok.com/@jsmentoring/photo/7468752457196162337
JSON is used for exchanging data between a client and server, especially in web applications. It is lightweight, easy to parse, and widely supported by many programming languages.
Tags: basic, JavaScript, data formats
URL: https://www.tiktok.com/@jsmentoring/photo/7453770486993014049
Obfuscation is used to protect JavaScript code from being easily read, understood, or modified by unauthorized parties. This is particularly important in scenarios where the source code is exposed in the client-side, such as in web applications. By obfuscating the code, developers can help prevent reverse engineering and intellectual property theft.
Example uses of obfuscation:
- Protecting proprietary algorithms
- Hiding sensitive information like API keys (though not recommended as a primary security measure)
- Preventing unauthorized modifications
Tags: intermediate, JavaScript, security
The with
statement is considered problematic because it makes the code harder to understand and maintain. It adds variables from an object to the scope, which can lead to confusion and unexpected behavior, especially in larger programs.
It is recommended to avoid using with
in modern JavaScript.
Example:
with (Math) {
console.log(sqrt(16)); // Works, but avoid it
}
Tags: intermediate, JavaScript, Best Practices
URL: https://www.tiktok.com/@jsmentoring/photo/7469541897426586913
JavaScript is single-threaded because it executes code in one thread, meaning only one operation can be performed at a time. This simplifies development, but asynchronous programming techniques like callbacks, promises, and async/await are used to handle concurrency.
Tags: intermediate, JavaScript, concurrency
URL: https://www.tiktok.com/@jsmentoring/photo/7455079370881879329
Jest is a JavaScript testing framework developed by Facebook. It is used for writing unit tests and provides a simple and easy-to-use API for writing tests for JavaScript code, particularly React applications.
To write a simple Jest test, use the test
function, which accepts a description of the test and a callback function that contains the code to test.
Example:
test('adds 1 + 2 to equal 3', () => {
expect(1 + 2).toBe(3);
});
The expect
function is used to create an assertion. It takes a value and returns an object that allows you to make assertions on that value, such as checking if it equals another value or if it meets certain conditions.
Example:
expect(2 + 2).toBe(4);
Tags: basic, Jest, Assertions
Jest provides two special functions: beforeAll
and afterAll
for global setup and teardown, and beforeEach
and afterEach
for setup and teardown before/after each test.
Example:
beforeEach(() => {
// Setup before each test
});
afterEach(() => {
// Teardown after each test
});
Tags: intermediate, Jest, Setup and Teardown
Mocks in Jest are used to simulate the behavior of real objects or functions. They are useful for isolating tests and avoiding dependencies on external systems, such as APIs or databases.
Example:
const myFunction = jest.fn();
myFunction.mockReturnValue(10);
expect(myFunction()).toBe(10);
Tags: intermediate, Jest, Mocks
Snapshot tests in Jest allow you to test whether a component's output changes over time. It generates a snapshot of the component’s output and stores it. On subsequent runs, Jest compares the output to the stored snapshot to detect changes.
Example:
import MyComponent from './MyComponent';
import { render } from '@testing-library/react';
import { toMatchSnapshot } from 'jest-snapshot';
it('matches snapshot', () => {
const { container } = render(<MyComponent />);
expect(container).toMatchSnapshot();
});
Tags: intermediate, Jest, Snapshot Testing
Jest provides async
and await
to test asynchronous code. You can return a promise from the test function or use done
for callback-based code.
Example with async
/await
:
test('fetches data asynchronously', async () => {
const data = await fetchData();
expect(data).toBeDefined();
});
Tags: intermediate, Jest, Async Testing
In Jest, you can use .skip
to skip a test and .only
to run a specific test.
Example:
test.skip('this test will be skipped', () => {
// test code
});
test.only('this test will run exclusively', () => {
// test code
});
Tags: intermediate, Jest, Test management
You can run Jest tests from the command line using the jest
command. Make sure Jest is installed, and you can run npx jest
or npm test
to run all the tests.
Example:
npx jest
Tags: basic, Jest, Command Line
Jest provides a variety of assertion methods, such as toBe()
, toEqual()
, toContain()
, toHaveBeenCalled()
, and more. These methods are used to check if values meet certain conditions.
Example:
expect(10).toBe(10);
expect([1, 2, 3]).toContain(2);
Tags: intermediate, Jest, Assertions
A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle. Elements are added at the rear (enqueue operation) and removed from the front (dequeue operation). It is similar to a line at a checkout counter.
Tags: basic, JavaScript, Data Structures
The main operations for a queue include:
enqueue
: Adds an element to the rear of the queue.dequeue
: Removes an element from the front of the queue.peek
: Returns the element at the front without removing it.isEmpty
: Checks if the queue is empty.
Tags: basic, JavaScript, Data Structures
A queue can be implemented using an array or linked list. For simplicity, let's use an array.
Example of a queue implementation using an array:
class Queue {
constructor() {
this.items = [];
}
enqueue(element) {
this.items.push(element);
}
dequeue() {
return this.items.shift();
}
peek() {
return this.items[0];
}
isEmpty() {
return this.items.length === 0;
}
}
Tags: basic, JavaScript, Implementation
A stack follows the Last-In-First-Out (LIFO) principle, while a queue follows the First-In-First-Out (FIFO) principle. In a stack, elements are added and removed from the same end (top), whereas in a queue, elements are added at the rear and removed from the front.
Tags: basic, JavaScript, Data Structures
A circular queue is a variation of a queue where the last position is connected back to the first position. It allows efficient use of space by avoiding the need to shift elements when elements are dequeued.
Tags: intermediate, JavaScript, Data Structures
To check if a queue is empty, you can verify if the queue's length is zero.
Example:
let queue = new Queue();
console.log(queue.isEmpty()); // true
Tags: basic, JavaScript, Operations
The dequeue operation removes an element from the front of the queue. In JavaScript, you can use the shift()
method on an array to achieve this.
Example:
let queue = [1, 2, 3];
let dequeued = queue.shift();
console.log(dequeued); // 1
console.log(queue); // [2, 3]
Tags: basic, JavaScript, Operations
The time complexity for queue operations is as follows:
enqueue
: O(1)dequeue
: O(1)peek
: O(1)isEmpty
: O(1)
This means all primary operations are performed in constant time.
Tags: intermediate, JavaScript, Time Complexity
A priority queue is a special type of queue where each element is assigned a priority. The element with the highest priority is dequeued first.
Example implementation using an array:
class PriorityQueue {
constructor() {
this.items = [];
}
enqueue(element, priority) {
const queueElement = { element, priority };
let added = false;
for (let i = 0; i < this.items.length; i++) {
if (queueElement.priority < this.items[i].priority) {
this.items.splice(i, 0, queueElement);
added = true;
break;
}
}
if (!added) {
this.items.push(queueElement);
}
}
dequeue() {
return this.items.shift();
}
peek() {
return this.items[0];
}
isEmpty() {
return this.items.length === 0;
}
}
Tags: intermediate, JavaScript, Data Structures
A circular queue implementation requires maintaining two pointers (front and rear) and using modulo arithmetic to handle wraparound.
Example:
class CircularQueue {
constructor(size) {
this.size = size;
this.queue = new Array(size);
this.front = 0;
this.rear = 0;
}
enqueue(element) {
if ((this.rear + 1) % this.size === this.front) {
console.log('Queue is full');
} else {
this.queue[this.rear] = element;
this.rear = (this.rear + 1) % this.size;
}
}
dequeue() {
if (this.front === this.rear) {
console.log('Queue is empty');
} else {
this.front = (this.front + 1) % this.size;
}
}
peek() {
return this.queue[this.front];
}
isEmpty() {
return this.front === this.rear;
}
}
Tags: intermediate, JavaScript, Data Structures
Protractor is an end-to-end testing framework for Angular and AngularJS applications. It is built on top of WebDriverJS and allows for easy automation of browser testing, providing functionality for testing user interactions with web applications.
Tags: basic, Protractor, UI Testing
To set up Protractor, you need to install Node.js, install Protractor via npm, and configure the protractor.conf.js
file. After the setup, you can use Protractor commands to interact with web pages in your tests.
Tags: basic, Protractor, Setup
Some of the basic Protractor commands include:
browser.get()
: Navigate to a URL.element()
: Locate an element on the page.element(by.css())
: Locate an element using a CSS selector.browser.sleep()
: Pause execution for a specified time.
Example:
browser.get('http://example.com');
let elem = element(by.id('username'));
Tags: basic, Protractor, Commands
In Protractor, you can locate elements using various locators such as CSS selectors, XPath, and Angular-specific locators.
by.id()
: Locate by ID.by.css()
: Locate by CSS selectors.by.xpath()
: Locate by XPath.
Example:
let button = element(by.css('.submit-button'));
Tags: basic, Protractor, Locators
A simple Protractor test can be written by creating a .spec.js
file that contains test cases using Jasmine or Mocha. You can then use it()
to define the test case and expect()
to assert conditions.
Example:
describe('Example test', () => {
it('should have a title', () => {
browser.get('http://example.com');
expect(browser.getTitle()).toEqual('Example Domain');
});
});
Tags: basic, Protractor, Testing
In Protractor, you can handle waiting using browser.wait()
and ExpectedConditions
. This helps wait for elements to appear, disappear, or change state before interacting with them.
Example:
let EC = protractor.ExpectedConditions;
browser.wait(EC.visibilityOf(element(by.id('submit-button'))), 5000);
Tags: intermediate, Protractor, Waiting
In Protractor, forms can be handled by interacting with form fields (input, select, etc.), filling them out, and submitting the form.
Example:
let nameField = element(by.id('name'));
nameField.sendKeys('John Doe');
let submitButton = element(by.id('submit'));
submitButton.click();
Tags: intermediate, Protractor, Forms
In Protractor, you can verify UI elements using expect()
assertions, such as verifying text, attributes, visibility, and presence of elements.
Example:
let heading = element(by.tagName('h1'));
expect(heading.getText()).toEqual('Welcome to Protractor');
Tags: intermediate, Protractor, Verification
Protractor provides methods to handle JavaScript alerts, confirms, and prompts. You can use browser.switchTo().alert()
to switch to the alert and perform actions like accepting or dismissing it.
Example:
let alert = browser.switchTo().alert();
alert.accept();
Tags: intermediate, Protractor, Alerts
To run Protractor tests in headless mode, you can configure the protractor.conf.js
file to use a headless browser like Chrome.
Example configuration:
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
args: ['--headless', '--disable-gpu', '--window-size=800x600']
}
},
Tags: advanced, Protractor, Headless Testing
You can handle errors in promises by appending a .catch()
method to the promise chain.
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Tags: beginner, JavaScript, Promises, Error Handling
Wrap your async code in a try/catch block to handle errors gracefully.
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();
Tags: intermediate, JavaScript, Async/Await, Error Handling
For synchronous operations, use a try/catch block to handle errors.
try {
const result = riskyOperation();
console.log(result);
} catch (error) {
console.error('Caught an error:', error);
}
Tags: beginner, JavaScript, Error Handling
Wrap event handler code in a try/catch block to ensure errors do not crash the application.
document.getElementById('myButton').addEventListener('click', () => {
try {
// Code that might throw an error
performAction();
} catch (error) {
console.error('Error during click event:', error);
}
});
Tags: intermediate, JavaScript, Error Handling, Events
Use .catch()
to handle errors when making HTTP requests with the Fetch API.
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
Tags: beginner, JavaScript, Fetch API, Error Handling
In Node.js, use try/catch for synchronous code and attach error listeners for asynchronous code.
// Synchronous error handling
try {
const data = fs.readFileSync('/path/to/file');
console.log(data);
} catch (error) {
console.error('Error reading file:', error);
}
// Asynchronous error handling
fs.readFile('/path/to/file', (error, data) => {
if (error) {
return console.error('Error reading file:', error);
}
console.log(data);
});
Tags: intermediate, JavaScript, Node.js, Error Handling
When working with callbacks, ensure that errors are passed as the first argument to the callback function.
function performAsyncOperation(callback) {
// Simulate error
const error = new Error('Something went wrong');
callback(error, null);
}
performAsyncOperation((error, result) => {
if (error) {
return console.error('Callback error:', error);
}
console.log(result);
});
Tags: intermediate, JavaScript, Callbacks, Error Handling
URL: https://www.tiktok.com/@jsmentoring/photo/7458362542088277281
For comprehensive error handling, set up global error listeners in your application.
window.onerror = function(message, source, lineno, colno, error) {
console.error('Global error caught:', message, 'at', source + ':' + lineno + ':' + colno);
};
// Example triggering a global error
nonExistentFunction();
Tags: advanced, JavaScript, Error Handling
Use middleware to catch and handle errors in your Express applications.
const express = require('express');
const app = express();
// Your routes here
app.get('/', (req, res) => {
throw new Error('Oops!');
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
app.listen(3000, () => console.log('Server running on port 3000'));
Tags: intermediate, JavaScript, Express.js, Error Handling
Listen for unhandled promise rejections to prevent unexpected application crashes.
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
// Example of an unhandled rejection
Promise.reject(new Error('Unhandled error'));
Tags: advanced, JavaScript, Promises, Error Handling
Garbage collection is an automatic memory management feature in JavaScript that frees memory occupied by objects no longer in use.
Tags: beginner, JavaScript, Memory Management
Garbage collection in JavaScript is performed by the JavaScript engine, which identifies and removes objects that are no longer reachable from the root (e.g., global object or stack).
Tags: intermediate, JavaScript, Memory Management, Algorithms
Common garbage collection algorithms include reference counting, mark-and-sweep, and generational garbage collection.
Tags: advanced, JavaScript, Memory Management, Performance
The mark-and-sweep algorithm identifies active objects (mark phase) and removes unreferenced objects (sweep phase), freeing up memory.
Tags: intermediate, JavaScript, Memory Management
Avoid circular references, remove event listeners, clear intervals, and use weak references where appropriate to prevent memory leaks.
Tags: advanced, JavaScript, Performance, Optimization
Weak references, such as those used in WeakMap
and WeakSet
, allow garbage collection of objects when they are no longer reachable elsewhere.
Tags: advanced, JavaScript, Memory Management, WeakMap
URL: https://www.tiktok.com/@jsmentoring/photo/7458291433980579105
No, JavaScript relies on automatic garbage collection managed by the engine, such as V8 in Chrome and Node.js.
Tags: beginner, JavaScript, Memory Management
Garbage collection can cause performance hiccups due to unpredictable pauses. Proper memory management can help minimize these interruptions.
Tags: intermediate, JavaScript, Performance
In most cases, you cannot manually trigger garbage collection. However, in some environments like Node.js, you can use global.gc()
if the --expose-gc
flag is enabled.
Tags: advanced, JavaScript, Memory Management, V8
Tools like Chrome DevTools, Node.js heap snapshots, and profiling tools can help identify memory leaks in JavaScript applications.
Tags: advanced, JavaScript, Debugging, Performance
Performance debugging involves identifying and fixing bottlenecks in JavaScript code to improve execution speed and efficiency.
Tags: beginner, JavaScript, Debugging, Performance
Use tools like console.time()
, performance.now()
, and Chrome DevTools Performance tab to analyze execution time.
Tags: beginner, JavaScript, Performance, Optimization
Use the Performance tab to record and analyze JavaScript execution, rendering, and paint times.
Tags: intermediate, JavaScript, Debugging, DevTools
Memory leaks occur due to circular references, forgotten timers, event listeners, and global variables.
Tags: intermediate, JavaScript, Memory Management, Debugging
Use Chrome DevTools' Memory tab to analyze heap snapshots and track memory usage over time.
Tags: advanced, JavaScript, Debugging, Performance
Remove unused event listeners, clear timers, use weak references, and avoid global variable accumulation.
Tags: advanced, JavaScript, Optimization, Debugging
Minimize reflows and repaints by batching updates, using document fragments, and avoiding direct style modifications.
Tags: intermediate, JavaScript, Performance, DOM
JavaScript runs on a single thread to simplify concurrency, using the event loop and asynchronous callbacks to handle tasks.
Tags: beginner, JavaScript, Event Loop, Performance
Use requestAnimationFrame()
instead of setTimeout()
for smoother animations synchronized with the browser's refresh rate.
Tags: intermediate, JavaScript, Animation, Optimization
Debouncing limits how often a function runs, while throttling ensures a function executes at a fixed interval to improve performance.
Tags: intermediate, JavaScript, Optimization, Performance
Use forEach()
for readability, for
loops for speed, and minimize redundant calculations inside loops.
Tags: intermediate, JavaScript, Performance, Optimization
Web Workers allow running scripts in background threads, offloading CPU-heavy tasks from the main thread.
Tags: advanced, JavaScript, Multithreading, Performance
Use modern formats (WebP, AVIF), lazy loading, and responsive images to reduce load time.
Tags: beginner, JavaScript, Optimization, Performance
Excessive event listeners can slow down performance. Use event delegation to minimize listeners.
Tags: advanced, JavaScript, Event Handling, Performance
Use the Intersection Observer API to load images and components only when they enter the viewport.
Tags: intermediate, JavaScript, Performance, Optimization
Blocking operations delay execution. Optimize async tasks and avoid long synchronous code.
Tags: advanced, JavaScript, Async, Performance
Defer JavaScript execution, use async scripts, and minimize CSS blocking resources.
Tags: advanced, JavaScript, Performance, Optimization
The Performance API provides precise timing data, including performance.now()
and performance.mark()
for measuring execution time.
Tags: advanced, JavaScript, Performance, Debugging
Long tasks (>50ms) block the main thread, causing UI lag. Split tasks into smaller chunks with setTimeout()
or requestIdleCallback()
.
Tags: intermediate, JavaScript, Performance, Optimization