Could there be an issue with JavaScript's array indexing?

Hi all, I’m just getting started with JavaScript and encountered something puzzling. I ran the following code snippet:

let beverage = "Marvelous";
let excerpt = beverage.substring(0, 4);
console.log(excerpt);

When executed in the console, it outputs ‘Marv’. I was under the impression that, since counting starts at 0, it should return ‘Marve’. Has anyone experienced this or can explain why the result isn’t what I expected?

hey, js substring excludes the end idx so substring(0,4) stops before the fourth. it’s not a bug, just how the method was desgned

I encountered a similar confusion early on when starting with JavaScript. The key point to understand is that the substring function takes a starting index and an ending index, but the ending index is not included in the output. This means that if you call substring(0, 4), you get the characters at indices 0, 1, 2, and 3, which in this case forms ‘Marv’. It is not an error with array indexing but rather how the substring method is designed to work. Once I grasped this behavior, working with string methods became much clearer.

The behavior you’re witnessing is due to the design of the substring method. It extracts characters starting from your specified index and stops just before the ending index. When you use substring(0, 4), it returns the characters at positions 0, 1, 2, and 3. This method is consistent in its approach across JavaScript, which can be initially confusing but is standard practice in many programming languages. Testing examples further helped me internalize how these functions work.

Having worked with JavaScript for some time now, I can say that the substring method behaves exactly as intended by the language designers. The method takes a starting index which is inclusive and an ending index which is exclusive, meaning it does not pick the character at that index. It’s important to understand that while indexes in arrays follow the 0-based approach, substring’s design follows the common convention of ending just before the index specified. Over time, this behavior has actually proved beneficial as it lets you precisely control the output without having to adjust for an extra index.

The behavior of substring in JavaScript is by design. It takes a starting index and an ending index, where the ending index is not included in the output. This means that when you execute substring(0, 4), it returns characters at indices 0, 1, 2, and 3. I found this behavior slightly confusing at first, especially coming from other programming languages, but it eventually proved useful by reducing off-by-one errors. Adapting to this method has helped me write clearer code and better manage string manipulation in various projects.