String Basics Quiz
Three short prompts on JavaScript string immutability, slicing, and char codes. Good warm-up before tackling sliding-window or palindrome problems.
Question Bank
Easy
JavaScript
3 questions
strings
data-structures
quiz
fundamentals
287 views
2
What does this snippet print and why? Explain whether s[0] = 'X' would mutate s.
Examples
Example 1:
Input: s = 'hello'; then s[0] = 'X'; print s, s.length, s.toUpperCase(), s
Output: hello, 5, HELLO, hello
Explanation: Strings are immutable in JavaScript, so s[0] = 'X' is silently ignored (or throws in strict mode). toUpperCase returns a new string without mutating s.const s = 'hello';
s[0] = 'X';
console.log(s);
console.log(s.length);
console.log(s.toUpperCase());
console.log(s);Implement reverseString(s) that returns the reversed string in O(n) time without using .reverse() on a temporary array. Use a manual character loop.
Examples
Example 1:
Input: s = 'hello'
Output: 'olleh'
Explanation: Walk from right to left appending each character to a buffer. Modern engines use rope strings, so += stays amortized O(n).function reverseString(s) {
// TODO: return s reversed, no Array.prototype.reverse
}Spot the bug. This function should check if every character in s is a lowercase ASCII letter. It returns true for inputs that contain digits.
Examples
Example 1:
Input: s = 'abc1'
Output (buggy version): true
Output (fixed version): false
Explanation: The bug uses || instead of &&, so code >= 97 || code <= 122 is true for every character (122 >= 97 alone covers everything). Replacing with && code <= 122 (and >= 97) correctly rejects digits like '1'.function isAllLowerLetters(s) {
for (const c of s) {
const code = c.charCodeAt(0);
if (code >= 97 || code <= 122) {
continue;
}
return false;
}
return true;
}