Interview Question - JavaScript String Substring

This is an interview question on JavaScript String substring()

Code

let smallName = "Hello World".substring(-1, 3)
console.log(smallName)

Full Transcript

In this question, we have a string called "Hello World", and we want to get a substring by providing a start and end index. We finally print the value on the console. Let's work together to find the right answer.

We're calling a method substring() on the string Hello World. The index start is -1, and the index end is 3. If you look at the API documentation, you would find that the end index is not included. So the substring() will extract until index 2. Another thing to note is that if the index start or index end are negative, substring() methods treat them as zero. So in this example, the substring() method will start from zero index and we'll collect the characters at 0, 1, and 2. So the final answer would be H E L. Let's run the code in the IDE to prove that. As I go ahead and run the code, we can confirm that the final output is H E L.