Let's look at examples and use cases for each of the Set, Map, and WeakMap data structures in JavaScript. These structures each serve unique purposes in managing collections of data.
Set Data Structure
Example:
Use Cases:
- Unique Value Storage: Since a Set only allows unique values, it's great for storing items where duplication is not allowed.
- Array Deduplication: Converting an array to a set and back to an array is a quick way to remove duplicate elements from the array.
- Set Operations: Sets can be used to perform mathematical set operations like union, intersection, and difference.
Map Data Structure
Example:
Use Cases:
- Key-Value Associations: Maps are ideal for cases where you need to associate unique keys with values.
- Caching/Memoization: Maps can be used to cache data where the retrieval key is not limited to strings (unlike objects).
- Data Relationships: Where there's a clear one-to-one mapping between two pieces of data, maps provide an efficient way to store and retrieve them.
To update a value in a JavaScript `Map` object, you use the same `set` method that you would use to add a new key-value pair. If the key already exists in the `Map`, its value will be updated; if the key does not exist, a new key-value pair will be added.
Here's an example where a value in a `Map` is updated after a loop:
In this example, after the loop (where you might be performing some operations), the value associated with `key2` is updated to `100` using `map.set('key2', 100)`
. This will overwrite the previous value of `key2` in the map.
WeakMap
Use Cases:
- Storing Private Data for Objects: WeakMaps provide a way of associating data with an object without preventing the object from being garbage-collected.
- Caching Computed Results for Objects: They are useful for caching results that are expensive to compute and that only need to be stored as long as the object exists.
- Managing Listeners: Useful in scenarios like attaching event listeners to DOM elements, where you don't want the listener references to prevent the DOM elements from being collected.
Each of these data structures offers different capabilities and is suitable for specific scenarios in JavaScript programming, enhancing the efficiency and manageability of your code.
The reduce()
method in JavaScript is a powerful function used to transform an array into a single value. This method executes a provided function for each value of the array (from left to right), accumulating the result as it goes along. The final result of running the reducer across all elements of the array is a single value.
Example: Sum of Array Elements
const array = [1, 2, 3, 4];
const sum = array.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // Output: 10
const sum = array.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // Output: 10
In this example, reduce()
is used to sum all the elements of an array. The accumulator
starts with the value 0
Advanced Usage
reduce()
can be used for more than just numbers. It's often used for transforming arrays into objects, aggregating data, or even composing functions.
Example: Grouping Objects by a Property
Typed Array
Typed Arrays:
example: Int8Array
are arrays whose elements are all of a single data type. Unlike regular JavaScript arrays, which can contain elements of different types and can dynamically grow in size, Typed Arrays are fixed in length and their content is strictly typed. They are useful for efficient data manipulation, especially when dealing with large quantities of numerical data or binary data, such as in WebGL applications, audio processing, and so on.
8-bit Signed Integers: Each element in an Int8Array
is a tiny integer that uses 8 bits (1 byte) of memory.
ArrayBuffer
is a low-level data structure used to represent a generic, fixed-length binary data buffer. You can think of it as a raw binary data buffer in memory, with no specific format.
Example
let buffer = new ArrayBuffer(10); // a buffer of 10 bytes
let int8View = new Int8Array(buffer); // a view of this buffer as 8-bit integers
In this example, buffer
is a raw 10-byte binary buffer, and int8View
is a view that lets you work with this buffer as an array of 8-bit integers. You can read and write to int8View
as you would with a regular array, and it will reflect in the underlying binary data stored in buffer
.
Position in
ArrayBuffer
: If you are creating a typed array view on anArrayBuffer
, the position could refer to the starting point in theArrayBuffer
from where the typed array view begins to read or write data.
let buffer = new ArrayBuffer(10);
// a buffer of 10 bytes
let int8View = new Int8Array(buffer, 2);
// a view starts from position 2 in the buffer
DataView: DataView
offers a more flexible approach than Int8Array
for reading and writing data in an ArrayBuffer
. It allows you to read and write multiple data types in the ArrayBuffer
, irrespective of the platform's endianness (byte order).
Notes in practice:
`
every()
` and `forEach()
` are both array methods in JavaScript, but they serve different purposes:
1.every():
Checks if every element in an array passes a test (provided as a function) and returns a Boolean value (`true` if all pass the test, `false` if not). It stops processing as soon as it encounters an element that does not pass the test.
2. forEach()
: Executes a provided function once for each array element, purely for side effects (like logging or updating values). It does not return a value and always processes all elements in the array, regardless of the results.
In short, use `every()` for checking conditions and `forEach()` for applying a function to each element without expecting a return value.
Resources :