Skip to content

Commit

Permalink
docs(blog): update slice post (#6452)
Browse files Browse the repository at this point in the history
  • Loading branch information
necatiozmen authored Nov 5, 2024
1 parent 20a0904 commit 216f01b
Show file tree
Hide file tree
Showing 3 changed files with 101 additions and 3 deletions.
2 changes: 1 addition & 1 deletion documentation/blog/2023-05-21-typescript-enums.md
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ This IIFE propels the following object to runtime:
}
```

Unidrectional mapping of a string member sets only the constant names as keys and therefore limits access to the enum only via constant names only, not by the value:
Unidirectional mapping of a string member sets only the constant names as keys and therefore limits access to the enum only via constant names only, not by the value:

```tsx
console.log(AccountType.PERSONAL); // "Personal"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ Steps we'll cover:

## Business Process & Workflow Automation: Traditional Internal Tools

Historically, internal tools such as Finance, Accounting and HR software were run offline on desktop based business computers. Major providers of enterprise software are SAP, Oracle, Microsoft, Salesforce, HubSpot and Zoho. They offer comprehesive suites of on-premise solutions that include ERP software, CRM systems, CMSs and host of other domain specific tools. Since the dot-com boom of 2000s, these off-the-shelf solutions are also available via cloud hosted web applications.
Historically, internal tools such as Finance, Accounting and HR software were run offline on desktop based business computers. Major providers of enterprise software are SAP, Oracle, Microsoft, Salesforce, HubSpot and Zoho. They offer comprehensive suites of on-premise solutions that include ERP software, CRM systems, CMSs and host of other domain specific tools. Since the dot-com boom of 2000s, these off-the-shelf solutions are also available via cloud hosted web applications.

### Enterprise Internal Tools: Their Types and Features

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ image: https://refine.ams3.cdn.digitaloceanspaces.com/blog/2022-10-17-js-slice/s
hide_table_of_contents: false
---

**_This article was last updated on January 31, 2024 to add new sections and organize content for better understanding of JS slice method._**
**This article was last updated on November 4, 2024 to include advanced use cases and improve the organization for a clearer understanding of the JavaScript slice() method.**

## Introduction

Expand All @@ -18,8 +18,10 @@ The JavaScript Iteration Methods Series covers posts on iteration methods that a

Steps we'll cover:

- [Introduction](#introduction)
- [What is Iteration ?](#what-is-iteration-)
- [JavaScript Iteration Methods: Complete vs Partial Iteration](#javascript-iteration-methods-complete-vs-partial-iteration)
- [Overview](#overview)
- [JS Slice - `Array.prototype.slice`](#js-slice---arrayprototypeslice)
- [What is JavaScript Array `slice` ?](#what-is-javascript-array-slice-)
- [Slicing an Array: How to Use JavaScript `slice`](#slicing-an-array-how-to-use-javascript-slice)
Expand All @@ -29,7 +31,16 @@ Steps we'll cover:
- [When to use JavaScript slice method?](#when-to-use-javascript-slice-method)
- [JS String Slice - `String.prototype.slice`](#js-string-slice---stringprototypeslice)
- [Slicing a JavaScript String: How to Use `String.prototype.slice`](#slicing-a-javascript-string-how-to-use-stringprototypeslice)
- [Advanced Use Cases for `slice()` - JavaScript](#advanced-use-cases-for-slice---javascript)
- [**Array Flattening**](#array-flattening)
- [**Working with Array-like Objects**](#working-with-array-like-objects)
- [**Using `slice()` with Immutability**](#using-slice-with-immutability)
- [JavaScript String Slice Nuances](#javascript-string-slice-nuances)
- [Best Practices Using JavaScript `slice()`](#best-practices-using-javascript-slice)
- [**Use `slice()` for Immutability**](#use-slice-for-immutability)
- [**Combine `slice()` with Other Array Methods**](#combine-slice-with-other-array-methods)
- [**Handle Sparse Arrays with Care**](#handle-sparse-arrays-with-care)
- [Summary](#summary)

## What is Iteration ?

Expand Down Expand Up @@ -299,6 +310,51 @@ console.log(fromThirdToFifthChars); // "eas"

Again, both arguments represent zero-based index numbers or offset values. Here too, the first argument -- `0` in the `firstThree` assignment -- stands for the starting index or offset in the source array. And the second argument (`3`) denotes the index or offset **before** which extraction should stop.

## Advanced Use Cases for `slice()` - JavaScript

I wanted to share a few interesting ways one might apply the `slice()` method in JavaScript, other than how it's usually used. These examples might turn out handy, especially when working with more complex data.

### **Array Flattening**

When one deals with a nested array and wants to extract a certain subarray, `slice()` works without touching the original structure. Say you are working with just a few items at each nested level; `slice()` can be used in a selectivity manner, to keep all things tidy and restrict the unwarranted changes to the main array.

```javascript
const nestedArray = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
const slicedSubarray = nestedArray
.slice(0, 2)
.map((innerArr) => innerArr.slice(1));
console.log(slicedSubarray); // [[2, 3], [5, 6]]
```

### **Working with Array-like Objects**

Array-like objects, such as the arguments in a function or NodeLists within a DOM, do not have all the various methods of arrays by default. Using the slice() method upon these can change them into real arrays, thereby opening many more functionalities. This is a neat way to deal with such structures without extra loops or conversions.

```javascript
function getArgumentsArray() {
return Array.prototype.slice.call(arguments);
}
const argsArray = getArgumentsArray(1, 2, 3);
console.log(argsArray); // [1, 2, 3]
```

### **Using `slice()` with Immutability**

If you are working with libraries like Redux that rely on immutability, then it's a good use case for shallow copying arrays with `slice()`, so you can update or do whatever you want with the data copy, leaving the original copy unchanged. This is the easy way out to keep your code predictable and functional programming principles conformant.

```javascript
const originalArray = [1, 2, 3, 4, 5];
const modifiedArray = originalArray.slice(0, 3).concat([10, 11]);
console.log(modifiedArray); // [1, 2, 3, 10, 11]
console.log(originalArray); // [1, 2, 3, 4, 5]
```

Using `slice()` in these methods has helped clean up code and make it more trustworthy, as well as offering far more control over the data.

### JavaScript String Slice Nuances

**Using JavaScript String `slice` With No Arguments**
Expand Down Expand Up @@ -352,6 +408,48 @@ console.log(inAnotherDimension); // ""
console.log(doingStringTheory); // ""
```

## Best Practices Using JavaScript `slice()`

Here's a quick look at how to avoid some common mistakes with JavaScript `slice()` and get the most out of it. Best practices like these will help you keep your code clean and predictable, especially in projects where immutability and data integrity are valued.

### **Use `slice()` for Immutability**

`slice()` is perfect when one needs to make a copy of an array without touching the original. If, for instance, you have state in some sort of Redux store or similar environment, `slice()` will allow you to keep the original:

```javascript
const originalArr = [1, 2, 3];
const copyArr = originalArr.slice();
copyArr.push(4);
console.log(originalArr); // [1, 2, 3]
console.log(copyArr); // [1, 2, 3, 4]
```

### **Combine `slice()` with Other Array Methods**

The `slice()` method works well with methods like `map()` or `filter()` when you want to modify or extract part of an array without touching the whole thing. Here's an example:

```javascript
const arr = [1, 2, 3, 4, 5];
const modifiedSubset = arr.slice(1, 4).map((num) => num * 2);
console.log(modifiedSubset); // [4, 6, 8]
```

Such an approach is especially convenient for creating views or paginated data sets from larger arrays.

### **Handle Sparse Arrays with Care**

One thing to notice: `slice()` keeps empty (sparse) array slots, and this can create some surprising behavior if you're dealing with incomplete data sets. If you want to lose those blank items, you can compose `slice()` with `filter(Boolean)`:

```javascript
const sparseArr = [1, , 3, , 5];
const cleanArr = sparseArr.slice().filter(Boolean);
console.log(cleanArr); // [1, 3, 5]
```

This keeps the array clean without gaps, making it easier to process or display consistently.

Using these techniques with `slice()` can make your code more readable and help avoid some of the widely occurring array problems.

## Summary

In this post, we expounded the `slice()` method in JavaScript. We saw that JavaScript implements `slice()` in two flavors: one for `Array`s with `Array.prototype.slice` and one for `String`s with `String.prototype.slice`. We found out through examples that both methods produce a copy of the source object and they are used to extract a target contiguous slice from it.
Expand Down

0 comments on commit 216f01b

Please sign in to comment.