Skip to content

Commit 18ab0d4

Browse files
added 479
1 parent 3a02232 commit 18ab0d4

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

README.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9554,6 +9554,37 @@ Common use cases and benefits:
95549554

95559555
**[⬆ Back to Top](#table-of-contents)**
95569556

9557+
479. ### What is the purpose of the at() method
9558+
9559+
The `at()` method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array or string.
9560+
9561+
Prior to this method, accessing the last element of an array required using array[array.length - 1]. The at() method makes this much cleaner and supports both **Arrays** and **Strings**.
9562+
9563+
*Key Features:*
9564+
1. *Positive Index:* Works the same as square bracket notation [].
9565+
2. *Negative Index:* Counts from the end of the array (e.g., -1 is the last element).
9566+
9567+
**Example:**
9568+
9569+
```javascript
9570+
const colors = ["Red", "Green", "Blue"];
9571+
// Old way to get the last element
9572+
console.log(colors[colors.length - 1]); // "Blue"
9573+
9574+
// Using at()
9575+
console.log(colors.at(-1)); // "Blue"
9576+
console.log(colors.at(-2)); // "Green"
9577+
9578+
// It also works on Strings
9579+
const sentence = "Hello";
9580+
console.log(sentence.at(-1)); // "o"
9581+
9582+
// Comparing with bracket notation for negative index
9583+
console.log(colors[-1]); // undefined (Bracket notation looks for a property named "-1")
9584+
9585+
9586+
**[⬆ Back to Top](#table-of-contents)**
9587+
95579588
<!-- QUESTIONS_END -->
95589589
### Coding Exercise
95599590

0 commit comments

Comments
 (0)