All sample questions / JavaScript
What does console.log('Hello'.at(-1)) print? JavaScript Numbers, Strings and Regular Expressions
Block 7, Numbers, Strings and Regular Expressions, question 20 of the JavaScript sample
console.log('Hello'.at(-1))
What does this print?
Show the answer and why each option is right or wrong
Answer, A. o
- A. o
- Correct. The at method supports negative indices, and -1 refers to the last character of the string.
- B. H
- Assumes a negative index to at counts from the start of the string instead of from the end.
- C. undefined
- Assumes a negative index is out of range and produces undefined, but at is specifically designed to support negative indices counting from the end.
- D. olleH
- Confuses at with reversing the whole string instead of indexing a single character from the end.
The at method was added to let negative indices count backward from the end of a string or array, unlike bracket indexing, which only accepts non negative positions. Index -1 with at always refers to the very last character.
The answer above is what the Node interpreter printed when the snippet was run, not what someone expected it to do.
This question comes from a bank of 600 JavaScript interview questions, all built the same way, sold as one PDF with the full answer key.
Get the 600 JavaScript questions, 9 euros
Or play the free JavaScript sample, twenty questions in the browser, also as a free PDF.
Did this save you a lookup? Buy me a coffee on Ko-fi.