FAQ
5. Frequently Asked Questions About Slice
Still have questions about `slice()`? Don't worry, you're not alone! Here are some of the most frequently asked questions:
Q: Does `slice()` modify the original array or string?
A: No! `slice()` creates a new array or string containing the extracted portion. The original data remains unchanged. It's like making a photocopy, not tearing a page out of a book.
Q: What happens if I don't provide an end index to `slice()`?
A: If you only provide a start index, `slice()` will extract everything from that index to the end of the array or string. It's a convenient way to grab the tail end of your data.
Q: Can I use negative indices with `slice()`?
A: Yes! Negative indices count from the end of the array or string. For example, `slice(-1)` will grab the last element or character.
Q: What's the difference between `slice()` and `splice()`?
A: This is a very common source of confusion! While both methods deal with arrays, they have very different purposes. `slice()` creates a new array without modifying the original. `splice()`, on the other hand, modifies the original array by adding or removing elements. If you want to extract a portion of an array without changing the original, use `slice()`. If you want to change the original array, use `splice()` (but be careful!).
Q: What happens if my start or end index is out of bounds?
A: If the start index is out of bounds (less than 0 or greater than the length of the array/string), it will be treated as 0 or the length of the array/string, respectively. If the end index is out of bounds, `slice()` will simply extract up to the end of the array/string.