𝗙𝗿𝗼𝗻𝘁𝗲𝗻𝗱 𝗟𝗶𝗻𝗲𝗮𝗿 𝗗𝗮𝘁𝗮 𝗦𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗲𝘀
Linear data structures arrange elements in a sequence. Each element has one predecessor and one successor.
Arrays Arrays are the main tool in JavaScript. They use contiguous memory. This allows you to access any element by its index instantly.
- push: Adds an element to the end.
- unshift: Adds an element to the start. This is slow because every other element must move one position to the right.
- splice: Adds or removes elements at any position. This method changes the original array. It is not a pure function.
Note: When an array grows too large, JavaScript must allocate a bigger memory block and copy everything over. This costs performance.
Stacks A stack follows the LIFO rule: Last In, First Out. Think of a stack of plates. You only add or remove from the top.
- push: Add to the top.
- pop: Remove from the top.
- peek: Look at the top element without removing it.
Queues A queue follows the FIFO rule: First In, First Out. Think of a line at a store.
- push: Add to the back.
- shift: Remove from the front.
Warning: Using shift on an array is slow for large datasets. Every element must move left to fill the gap. For high volume data, use a linked list instead.
Linked Lists A linked list consists of nodes. Each node holds data and a pointer to the next node.
- Advantages: Adding or removing nodes is fast once you find the spot. You only change pointers.
- Disadvantages: You cannot jump to an index. You must start at the head and follow pointers one by one. This is slow.
Comparison Summary:
- Arrays: Best for frequent reads and small data. Access is O(1).
- Linked Lists: Best for frequent writes and large data. Insertion is O(1) if you have the node.
Pro Tips for JavaScript:
- Do not mix data types in an array. Keeping types uniform helps the engine use contiguous memory.
- Always use a comparator function when sorting numbers. [10, 2].sort() results in [10, 2] because it sorts as strings.
- Remember that most native array methods mutate the original array.