JavaScript
Modern JavaScript Commands And Elements
JavaScript Commands, Elements, and Techniques
These commands and elements demonstrate the advanced capabilities that modern JavaScript offers. They play a crucial role in building responsive, interactive, and feature-rich web applications. Modern projects combine these APIs and features to deliver experiences that are fast, secure, and increasingly more powerful .
Here’s a list of JavaScript commands, elements, and techniques commonly used in modern and advanced projects, along with brief descriptions and examples (without code):
1. let, const, and var:
Description: Used for declaring variables.
let: Block-scoped, used for variables that may change.
const: Block-scoped, used for variables that won’t change.
var: Function-scoped, older declaration method (not recommended in modern projects).
2. Arrow Functions (=>):
Description: A shorthand syntax for writing functions. It allows more concise function expressions and binds the this keyword lexically.
Example: (a, b) => a + b.
3. Template Literals (``)
Description: Used for embedding variables inside strings and creating multi-line strings.
Example: `Hello, ${name}`.
4. Promises (Promise):
Description: Used for handling asynchronous operations, avoiding callback hell. Promises have three states: pending, resolved, and rejected.
Example: fetch or async and await functions are based on promises.
5. async and await:
Description: Allows asynchronous code to be written in a more synchronous style. await is used inside async functions to wait for the promise.
Example: async function getData() { const result = await fetchData(); }.
6. Modules (import / export):
Description: Used for separating and importing/exporting code into different files for better organization and reusability.
Example: import { functionName } from './module.js'.
7. Destructuring Assignment:
Description: Extracting values from arrays or objects into variables easily.
Example: const { name, age } = person.
8. Spread Operator (...):
Description: Used to expand arrays or objects and pass multiple arguments.
Example: const newArray = [...array1, ...array2].
9. Rest Parameter (...):
Description: Collects multiple arguments into an array.
Example: function sum(...numbers) { return numbers.reduce((acc, num) => acc + num); }.
10. Classes (class):
Description: JavaScript's syntactic sugar for constructor functions and prototypes, used in object-oriented programming.
Example: class Car { constructor(name) { this.name = name; } }.
11. Event Listeners (addEventListener):
Description: Used to respond to various user interactions like clicks, scrolls, or key presses.
Example: element.addEventListener('click', function).
12. DOM Manipulation:
Description: Methods for interacting with and modifying HTML elements dynamically.
document.querySelector: Selects an element by CSS selectors.
document.createElement: Creates a new element.
element.appendChild: Adds an element as a child of another.
element.classList.add/remove: Adds or removes a CSS class.
13. Local Storage & Session Storage (localStorage, sessionStorage):
Description: Used for storing data in the browser. localStorage persists until explicitly deleted, while sessionStorage is cleared when the page session ends.
Example: localStorage.setItem('key', 'value').
14. Form Data Handling (FormData):
Description: Used for constructing key/value pairs representing form fields and their values, useful in submitting forms with fetch.
Example: const formData = new FormData(formElement).
15. Fetch API:
Description: A modern method to make HTTP requests (GET, POST, etc.) to interact with APIs. Supports promises for handling asynchronous requests.
Example: fetch('https://api.example.com/data').
16. JSON (JSON.parse, JSON.stringify):
Description: Methods to parse a JSON string into an object (JSON.parse) and to convert an object to a JSON string (JSON.stringify).
Example: JSON.parse(response).
17. Map, Filter, Reduce:
Description: Array methods used for iterating, transforming, and reducing arrays in a functional programming style.
map: Creates a new array by transforming each element.
filter: Filters elements based on a condition.
reduce: Reduces an array to a single value.
18. Set and Map Objects:
Description: New collections introduced in ES6.
Set: A collection of unique values.
Map: A collection of key-value pairs.
Example: const mySet = new Set([1, 2, 3]).
19. Symbol:
Description: A new primitive type in ES6, used for creating unique, immutable identifiers.
Example: const sym = Symbol('description').
20. Iterators and Generators:
Description: Custom iteration behavior using the Symbol.iterator method or generator functions (function*).
Example: function* generator() { yield 1; yield 2; }.
21. Promise.all / Promise.race:
Description: Methods to handle multiple promises.
Promise.all: Waits for all promises to resolve.
Promise.race: Returns the first resolved or rejected promise.
Example: Promise.all([promise1, promise2]).
22. Nullish Coalescing Operator (??):
Description: Returns the right-hand operand when the left-hand operand is null or undefined.
Example: let name = userInput ?? 'Guest'.
23. Optional Chaining (?.):
Description: Allows accessing deeply nested object properties without checking for null/undefined at every level.
Example: const street = user?.address?.street.
24. Custom Events:
Description: Allows developers to define and dispatch their own events.
Example: const event = new CustomEvent('myEvent', { detail: { key: 'value' } }).
25. Service Workers:
Description: Scripts that run in the background, enabling offline capabilities, background sync, and push notifications for Progressive Web Apps (PWAs).
Example: navigator.serviceWorker.register('/sw.js').
26. Intersection Observer:
Description: Used to efficiently detect when an element enters or leaves the viewport, useful for lazy-loading images or infinite scrolling.
Example: const observer = new IntersectionObserver(callback).
27. WebSockets:
Description: Enables real-time, two-way communication between a client and a server.
Example: const socket = new WebSocket('ws://example.com').
28. Canvas API:
Description: Allows for drawing 2D shapes, animations, and graphics in the browser.
Example: const canvas = document.getElementById('myCanvas').
29. Shadow DOM and Web Components:
Description: Enables encapsulation of HTML, CSS, and JavaScript for reusable components.
Example: class MyComponent extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }) } }.
30. Proxy:
Description: Used to create a custom behavior for fundamental operations (e.g., property lookup, assignment, function invocation).
Example: const handler = { get: (obj, prop) => prop in obj ? obj[prop] : 'default' }.
31. Intl (Internationalization API):
Description: Provides language-sensitive string comparison, number formatting, and date and time formatting. It is useful for applications with international audiences.
Example: new Intl.DateTimeFormat('en-US', { month: 'long', day: 'numeric', year: 'numeric' }).format(date).
32. MutationObserver:
Description: Allows you to watch for changes in the DOM, like when elements are added, removed, or modified. Useful for building reactive UIs.
Example: const observer = new MutationObserver(callback); observer.observe(targetNode, config).
33. Geolocation API:
Description: Provides methods to get the user's location (latitude and longitude).
Example: navigator.geolocation.getCurrentPosition(successCallback).
34. History API:
Description: Allows manipulation of the browser session history, including pushing new entries or changing the current entry.
Example: history.pushState(stateObject, title, url).
35. Drag and Drop API:
Description: Provides functionality for dragging and dropping elements within the browser.
Example: element.addEventListener('dragstart', dragStartHandler).
36. Clipboard API:
Description: Allows you to interact with the clipboard, like copying and pasting content programmatically.
Example: navigator.clipboard.writeText('Copied Text').
37. Touch Events:
Description: Used for handling touch-based interactions on mobile and tablet devices.
Example: element.addEventListener('touchstart', handleTouchStart).
38. Pointer Events:
Description: Provides a unified way to handle mouse, touch, and pen events across different devices.
Example: element.addEventListener('pointerdown', handlePointerEvent).
39. Resize Observer:
Description: Observes changes to the size of an element and triggers a callback when it resizes.
Example: const resizeObserver = new ResizeObserver(callback); resizeObserver.observe(element).
40. Notification API:
Description: Enables web apps to display notifications to the user, even when the app is not in focus.
Example: new Notification('Hello!').
41. Vibration API:
Description: Allows web applications to trigger vibrations on devices that support it (mainly mobile).
Example: navigator.vibrate([200, 100, 200]).
42. Device Orientation & Motion API:
Description: Provides access to the orientation and motion data from the device’s accelerometer and gyroscope, useful for gaming and motion-based controls.
Example: window.addEventListener('deviceorientation', handleOrientation).
43. Web Workers:
Description: Allows running scripts in the background on separate threads without affecting the UI performance, useful for intensive computations.
Example: const worker = new Worker('worker.js').
44. Shared Workers:
Description: Similar to Web Workers, but can be shared between multiple scripts or tabs, enabling communication between them.
Example: const sharedWorker = new SharedWorker('sharedWorker.js').
45. WebAssembly (Wasm):
Description: A binary format allowing execution of code written in languages other than JavaScript (like C/C++), providing near-native performance in the browser.
Example: WebAssembly.instantiate(buffer, imports).then(({ instance }) => instance.exports.func()).
46. IndexedDB:
Description: A low-level API for client-side storage of large amounts of structured data, including files and blobs.
Example: const request = indexedDB.open('myDatabase').
47. Push API:
Description: Enables web applications to receive push notifications from a server, even when the application is not active.
Example: serviceWorkerRegistration.pushManager.subscribe(options).
48. Media Devices API:
Description: Provides access to media input devices like cameras and microphones.
Example: navigator.mediaDevices.getUserMedia({ video: true, audio: true }).
49. AudioContext & Web Audio API:
Description: Allows developers to generate, manipulate, and play sounds in the browser.
Example: const audioCtx = new AudioContext(); const oscillator = audioCtx.createOscillator().
50. Canvas API (Advanced):
Description: Allows developers to render complex graphics, such as games and interactive visualizations.
Example: const ctx = canvas.getContext('2d'); ctx.drawImage(image, x, y).
51. SVG Manipulation:
Description: Provides methods to manipulate Scalable Vector Graphics (SVG) directly with JavaScript.
Example: document.querySelector('svg').setAttribute('fill', '#000').
52. Streams API:
Description: Allows handling streaming data, such as reading or writing files or processing real-time media.
Example: const reader = stream.getReader(); reader.read().then(({ value, done }) => { ... }).
53. Pointer Lock API:
Description: Allows locking the pointer to a specific target, useful for immersive web experiences like 3D games.
Example: element.requestPointerLock().
54. Gamepad API:
Description: Provides access to game controllers, enabling users to interact with web applications using gaming controllers.
Example: window.addEventListener('gamepadconnected', handleGamepad).
55. Battery Status API:
Description: Provides information about the device's battery status.
Example: navigator.getBattery().then(battery => console.log(battery.level)).
56. Fullscreen API:
Description: Allows elements or applications to be presented in full-screen mode.
Example: element.requestFullscreen().
57. Content Security Policy (CSP):
Description: Used for controlling what resources can be loaded by your web page, enhancing security.
Example: Defined via HTTP headers or <meta> tags.
58. CSS Custom Properties with JavaScript:
Description: Modifying CSS variables from JavaScript to dynamically adjust styles.
Example: document.documentElement.style.setProperty('--main-color', 'blue').
59. Web Animations API:
Description: Allows for the creation of complex animations, giving fine control over their playback, without the need for CSS or third-party libraries.
Example: element.animate([{ transform: 'translateX(0)' }, { transform: 'translateX(100px)' }], { duration: 1000 }).
60. Bluetooth API (Web Bluetooth):
Description: Enables communication with Bluetooth devices directly from a web application.
Example: navigator.bluetooth.requestDevice({ acceptAllDevices: true }).
61. Sensors API:
Description: Provides access to sensors like accelerometers, gyroscopes, and magnetometers.
Example: const accelerometer = new Accelerometer({ frequency: 60 }).
62. Beacon API:
Description: Allows sending small data payloads to the server asynchronously without delaying the unloading of a page.
Example: navigator.sendBeacon(url, data).
63. Credential Management API:
Description: Simplifies the process of handling login credentials by integrating with password managers.
Example: navigator.credentials.store(new PasswordCredential({ id, password })).
64. Web NFC (Near Field Communication) API:
Description: Enables reading and writing of NFC tags from web applications.
Example: const nfcReader = new NFCReader(); nfcReader.scan().
65. AbortController API:
Description: Provides a way to abort ongoing fetch requests or other asynchronous operations.
Example: const controller = new AbortController(); fetch(url, { signal: controller.signal }).
66. Content Indexing API:
Description: Allows progressive web apps to register content that can be indexed and displayed by the browser when offline.
Example: contentIndex.add({ id, title, description, icon }).