String at

2 snippets in JavaScript

JSJavaScript

Repeat and Character Access

JS · Strings
syntax
str.repeat(count)
str.at(index)
example
const border = "=".repeat(30);
console.log(border);

const word = "JavaScript";
console.log(word.at(0));   // "J"
console.log(word.at(-1));  // "t"

Note at() supports negative indices to count from the end. Bracket notation str[-1] returns undefined, not the last character.

Array/String .at() Method

JS · Modern Features
syntax
arr.at(index)
str.at(index)
example
const stack = ["first", "second", "third", "last"];
console.log(stack.at(0));   // "first"
console.log(stack.at(-1));  // "last"
console.log(stack.at(-2));  // "third"

console.log("hello".at(-1)); // "o"

Note Works on Arrays, Strings, and TypedArrays. The main advantage over bracket notation is support for negative indices.