Challenge - 5 Problems
String Mastery in JavaScript
Get all challenges correct to earn this badge!
Test your skills under time pressure!
ā Predict Output
intermediateWhat is the output of this JavaScript string operation?
Consider the following JavaScript code snippet. What will be printed to the console?
DSA Javascript
const str = 'hello'; const result = str[0] + str.length + str[str.length - 1]; console.log(result);
Attempts:
2 left
š” Hint
Remember that str.length is a number and adding it to strings concatenates as string.
ā Incorrect
str[0] is 'h', str.length is 5, and str[str.length - 1] is 'o'. Adding them as strings results in 'h5o'.
ā Predict Output
intermediateWhat does this code print regarding string immutability?
Look at this JavaScript code. What is the output after running it?
DSA Javascript
let s = 'abc'; s[0] = 'z'; console.log(s);
Attempts:
2 left
š” Hint
Strings in JavaScript cannot be changed by assigning to an index.
ā Incorrect
Strings are immutable in JavaScript, so s[0] = 'z' does nothing. The original string remains 'abc'.
ā Predict Output
advancedWhat is the output of this string comparison in JavaScript?
What will this code print to the console?
DSA Javascript
console.log('a' < 'b'); console.log('a' < 'A'); console.log('abc' < 'abd');
Attempts:
2 left
š” Hint
JavaScript compares strings lexicographically using Unicode values.
ā Incorrect
'a' < 'b' is true because 'a' comes before 'b'. 'a' < 'A' is false because lowercase 'a' has higher Unicode than uppercase 'A'. 'abc' < 'abd' is true because 'c' < 'd'.
ā Predict Output
advancedWhat is the output of this code involving Unicode characters?
What will this JavaScript code print?
DSA Javascript
const s = 'ššš'; console.log(s.length); console.log(s[0]);
Attempts:
2 left
š” Hint
Some Unicode characters use two code units in JavaScript strings.
ā Incorrect
Each character 'š', 'š', 'š' is represented by two UTF-16 code units, so length is 6. s[0] returns the first code unit, which is a half of the character, shown as \uD835.
š§ Conceptual
expertWhy do some languages treat strings as arrays of characters while others do not?
Which of the following best explains why JavaScript strings behave differently from languages like C when accessing characters by index?
Attempts:
2 left
š” Hint
Think about string encoding and mutability in JavaScript.
ā Incorrect
JavaScript strings are immutable sequences of UTF-16 code units. Indexing returns code units, which may be half of a Unicode character. This differs from languages like C where strings are mutable arrays of bytes.
