JavaScript Strings - Questions

Pack 3 65 questions

Things to know

  1. JavaScript Strings unit required

Basics

  1. If a string is denoted using a pair of double quotes (""), can the double quote character be used itself inside the string as it is?

    No, that's NOT possible. For instance, the string "Hello "World"" is invalid since the " character comes inside it, where it's denoted using the same character. Learn more in JavaScript Strings - Basics.

  2. In the string 'Hello\nWorld!', what is the special character sequence \n?

    \n represents an escape sequence which denotes a newline character. Learn more in JavaScript Strings - Basics.

  3. What is a template literal in JavaScript?

    A template literal, given as a pair of backticks (``), represents a template string in JavaScript. Such a string can span multiple lines in the code and even contain embedded JavaScript expressions inside of it. Learn more in JavaScript Strings - Basics: Template literals.

  4. How to denote JavaScript code inside a template string?

    Using ${exp}, where exp is a JavaScript expression. Remember that template strings, since they are expressions themselves, can only contain JavaScript expressions inside of them. Learn more in JavaScript Strings - Basics: Template literals.

  5. A template literal in JavaScript can span multiple lines in code. True or false?

    Absolutely true. Here's an example:

    var str = `This is line 1.
    And this is line 2.`;

    str here contains two separate lines of text. Most importantly, this distinction is visible right there in the code, all thanks to the template literal in JavaScript. We can't do so using a pair of single quotes ('') or double quotes ("") in JavaScript.

    Learn more in JavaScript Strings - Basics: Template literals.

  6. When using a template literal, it's a requirement to escape both the single quote (') and the double quote (") character. True or false?

    No, there's no such requirement. In fact, why would there be one, since the backtick character (`) used to denote a template literal does not conflict with a single quote (') or a double quote ("). Learn more in JavaScript Strings - Basics: Template literal.

  7. Why is a template literal called a 'template literal'?

    It's called so because it can be used to create 'templates' in JavaScript that have to be filled in with actual data at run time. Note that this only makes sense when a template literal contains JavaScript code in it. Learn more in JavaScript Strings - Basics: Template literals.

  8. The string concatenation (+) operator (which is also the arithmetic addition operator) is left-associative in JavaScript. What does this mean? Explain using an example which would otherwise produce a different result had the operator been right-associative.

    The + operator in JavaScript, used for both string concatenation and arithmetic addition, is left-associative in nature. This means that a sequence of consecutive + expressions get resolved starting from the left side.

    Consider the following code:

    var str = '$' + 10 + 20;

    str here resolves down to '$1020' and that's because first '$' + 10 is resolved and then the later + 20 expression. Had + been right-associative (like =), first 10 + 20 would've been resolved.

    Learn more in JavaScript Strings - Basics: String concatenation.

  9. How does + decide when to perform string concatenation and when to perform arithmetic addition?

    If either of the operands of + is a value with a non-numeric corresponding primitive representation, string concatenation is performed. Otherwise, arithmetic addition is performed. Learn more in JavaScript Strings - Basics: String concatenation.

  10. What is meant when we say that strings in JavaScript are immutable?

    It means that a string value, once created, can't be mutated (i.e. changed). If we wish to mutate a string, we have to create a new one with those mutations. Learn more in JavaScript Strings - Basics: Immutability.

  11. Suppose that str holds the value 'Bare'. What would happen if we run str[0] = 'C'?

    Nothing; the string str would remain 'Bare'. This is because strings in JavaScript are immutable. Learn more in JavaScript Strings - Basics: Immutability.

  12. How can we replace a particular character, at index i, from a string str with another character c?

    Via str.slice(0, i) + c + str.slice(i + 1). Learn more in JavaScript Strings - Basics: Immutability.

  13. Should we use new String() manually to create strings in a JavaScript program? Explain your answer.

    No. Never. The String() constructor is used internally by the JavaScript engine when autoboxing values. Learn more in JavaScript Strings - Basics: The String() constructor.

  14. String() is the same as calling new String(). True or false?

    False. String() (without new) converts a given value into a string primitive. On the other hand, new String() converts a given value into a string object. Learn more in JavaScript Strings - Basics: The String() constructor.

Unicode

  1. What is a character set?

    A character set can be thought of as a table containing character names along with their associated numbers, i.e. their character codes. Learn more in JavaScript Strings — Unicode.

  2. What is a character encoding scheme?

    It is a system of encoding and decoding characters on a computer. Learn more in JavaScript Strings — Unicode.

  3. Name the character encoding scheme used by JavaScript internally for its string data type.

    JavaScript uses the UTF-16 character encoding scheme internally for its string data type. Learn more in JavaScript Strings — Unicode.

  4. In Unicode, what is a code unit?

    In Unicode, a code unit is a unitary block of memory used to represent the code point of a character, either as a whole or together with one or multiple following code units. Learn more in JavaScript Strings — Unicode.

  5. In Unicode, what is a code point?

    In Unicode, a character's code point is the precise number representing the character. It is unaffected by the concrete encoding scheme used (e.g. UTF-8, UTF-16). Learn more in JavaScript Strings — Unicode.

  6. A string in JavaScript is a sequence of 16-bit unsigned integers. True or false?

    True. JavaScript internally uses the UTF-16 encoding scheme for its string data type which represents every character as a sequence of one or two 16-bit unsigned integers, i.e. code units for UTF-16. Learn more in JavaScript Strings — Unicode.

  7. A JavaScript string is a sequence of Unicode code units. True or false?

    True. In fact, that's what the length property of a string returns — the number of code units therein. Learn more in JavaScript Strings — Unicode.

  8. What does the string charCodeAt() method return?

    Given an index argument, charCodeAt() returns the code unit at the given index. Learn more in JavaScript Strings — Unicode: charCodeAt().

  9. How does the charCodeAt() method work?

    The charCodeAt() method takes an index argument and simply returns back the code unit residing at that very position in the calling string. Learn more in JavaScript Strings — Unicode: charCodeAt().

  10. '🙂'.charCodeAt(0) returns the code point associated with the '🙂' character. True or false?

    False. '🙂' is comprised of two code units, not one. Hence, '🙂'.charCodeAt(0) only returns the first code unit of the character (as encoded in UTF-16). It does NOT return the code point of '🙂' which is larger than what one code unit in UTF-16 can hold. Learn more in JavaScript Strings — Unicode: charCodeAt().

  11. What does the string codePointAt() method return?

    Given an index argument, codePointAt() returns the code point of the character at the given index. Learn more in JavaScript Strings — Unicode: codePointAt().

  12. How does the codePointAt() method work?

    The codePointAt() methods reads the code unit at the given index argument and if it turns out to be a high surrogate (in UTF-16), amalgamates it with the following code unit in order to produce a complete code point for the respective character; else, it simply returns back the code unit. Learn more in JavaScript Strings — Unicode: codePointAt().

  13. What does 'abc'.length return? Explain why in terms of the character encoding format used by JavaScript.

    'abc'.length returns 3. That's because each of the given characters, a, b and c, spans exactly one code unit in UTF-16 (the character encoding format used by JavaScript) and because length returns back the total number of code units in a string. Learn more in JavaScript Strings — Unicode: The length property.

  14. What does '🙂'.length return? Why?

    '🙂'.length returns 2 because the '🙂' character is comprised of two code units in UTF-16. Learn more in JavaScript Strings — Unicode: The length property.

  15. What is a Unicode escape sequence in JavaScript?

    A Unicode escape sequence is an escape sequence that can be used to represent a character in a JavaScript string based on its individual code units or its single code point. Learn more in JavaScript Strings — Unicode: Unicode escape sequences.

  16. Give the two variants of denoting a Unicode escape sequence in JavaScript.

    The first one is \uXXXX, where XXXX represents the hexadecimal value of a code unit. The second one is \u{codePoint} where codePoint is a hexadecimal value of a character's code point. Learn more in JavaScript Strings — Unicode: Unicode escape sequences.

  17. Consider the escape sequence \u60. Is this correct?

    No, it's NOT correct. That's because when using \u without following braces ({}), the JavaScript parser expects precisely 4 hexadecimal digits. In \u60, there are only two of them and so we get an error thrown. Learn more in JavaScript Strings — Unicode: Unicode escape sequences.

  18. Consider the escape sequence \u{60}. Is this correct?

    Yes, this is absolutely correct, for the hexadecimal value of a character's code point is nicely encapsulated inside the curly braces ({}). Learn more in JavaScript Strings — Unicode: Unicode escape sequences.

  19. In the escape sequence \u{60}, what does 60 represent?

    60 represents the code point of a character in Unicode in hexadecimal representation. Learn more in JavaScript Strings — Unicode: Unicode escape sequences.

  20. In the escape sequence \u{60}, we can add as many 0s before 60 as we want to. For example, \u{060}, \u{0060}, \u{00060}, \u{000060}, ..., \u{0000000060}. True or false?

    False. We can NOT add as many 0s as we want to. Rather, we can only add as many 0s that are needed to make the entire number no longer than 6 digits. Learn more in JavaScript Strings — Unicode: Unicode escape sequences.

  21. What is meant by lexicographic comparison?

  22. What does 'a' < 'b' return? Why?

    'a' < 'b' returns true because the code unit of 'a', i.e. 97 (in decimal), is less than the code unit of 'b', i.e. 98 (in decimal). Learn more in JavaScript Strings — Unicode: Lexicographic comparison.

  23. What does 'abc' < 'ab' return? Why?

    Since the starting two characters in both 'abc' and 'ab' are the same, comparison boils down to the length of the given strings. In this case, since 'abc' has a larger length, it is lexicographically larger than 'ab'. Hence, 'abc' < 'ab' returns false. Learn more in JavaScript Strings — Unicode: Lexicographic comparison.

  24. Given an arbitrary string str in JavaScript, is there any way to determine the total number of characters (NOT code units) in it? If yes, then how does it work?

    Yes there is: [...str].length. Learn more in JavaScript Strings — Unicode: The string iterator.

  25. How can we reliably retrieve the last character of a string str that is known to contain special characters such as '🙂' at any position in it?

    As follows:

    // Suppose str is an arbitrary string
    var chars = [...str];
    var lastChar = chars[chars.length - 1];

    Here, lastChar holds the last character of the arbitrary string str.

    Learn more in JavaScript Strings — Unicode: The string iterator.

String Methods

  1. How to lowercase and uppercase a string str in JavaScript?

    Using str.toLowerCase() and str.toUpperCase() respectively. (Keep in mind that calling either of these methods (in fact, any string method) returns back a new string; it doesn't modify the original string.)

    Learn more in JavaScript Strings — String Methods: Changing casing.

  2. How can we trim off whitespace characters from both ends of a string?

    Using the trim() string method. Learn more in JavaScript Strings — String Methods: trim().

  3. How can we trim off whitespace characters only from the left or right end of a string?

    Using the string methods trimStart() (or trimLeft() equivalently) and trimEnd() (or trimRight() equivalently), respectively. Learn more in JavaScript Strings — String Methods: trimStart() and trimEnd().

  4. What's the difference between trimStart() and trimLeft()?

    There's absolutely no single difference; they are both aliases of one another.

  5. The trim() method can be provided an optional argument specifying a set of characters to trim off from a given string. True or false?

    False; the trim() string method in JavaScript (unlike trimming utilities in some other languages) doesn't accept any arguments to specify a set of characters to trim. Learn more in JavaScript Strings — String Methods: trim().

  6. Given two strings, str and substr, how could we determine the first index at which substr occurs in str?

    Using str.indexOf(substr). Learn more in JavaScript Strings — String Methods: indexOf().

  7. Given two strings, str and substr, how could we determine the last index at which substr occurs in str?

    Using str.lastIndexOf(substr).

  8. What does the second argument to indexOf() specify?

    It specifies the index where the method should begin the search from. By default, it's set to 0, i.e. beginning the search from the very first character. Learn more in JavaScript Strings — String Methods: indexOf().

  9. What is the split() string method used for?

    As per the name, split() is used to split a string apart into individual substrings at a given separator. For instance, if we have the string '10, 20, 30', we can obtain individual strings containing the numbers via calling split(', ') on this string.

    Learn more in JavaScript Strings — String Methods: split().

  10. Given an arbitrary string str, what does str.split() return?

    In JavaScript, the split() string method when called without any arguments, returns an single-element array containing the entire given string. Learn more in JavaScript Strings — String Methods: split().

  11. How to convert a string str into an array of its characters?

    Using str.split(''). Learn more in JavaScript Strings — String Methods: split().

  12. What does the second parameter of split() specify?

    The second limit parameter of split() specifies the limit of elements in the returned array. By default, it's a very huge number (precisely, 232 - 1). Learn more in JavaScript Strings — String Methods: split().

  13. What is the slice() method used to do?

    As per its name, slice() is used to slice out a substring from a main string. This is done by specifying the starting position of the slice and its ending position. Learn more in JavaScript Strings — String Methods: slice().

  14. What does 'Hello'.slice() return?

    It returns 'Hello' since calling slice() without any arguments returns the given string back.

  15. What does 'Hello'.slice(2, 1) return?

    It returns '' since the starting position, 2, is greater than the ending position, 1. Learn more in JavaScript Strings — String Methods: slice().

  16. The slice() method can accept negative indexes as well. True or false? If true, how does it treat those negative indexes?

    slice() can indeed accept negative indexes as well in which case those indexes are internally coerced into non-negative indexes relative to the end of the string. For instance, -1 becomes the index of the first character from the end of the string; -2 becomes the index of the second-last character; and so on.

    Learn more in JavaScript Strings — String Methods: slice().

  17. What is the substring() method used to do?

    substring() is used to slice strings in JavaScript, akin to slice(). It is similar to slice() in every aspect except for the way it treats its arguments. Learn more in JavaScript Strings — String Methods: substring().

  18. What is the difference between slice() and substring()?

    There are two differences:

    • substring() coerces negative index arguments into 0.
    • substring() swaps the two given arguments in case the first one is larger.

    Learn more in JavaScript Strings — String Methods: Difference between slice() and substring().

  19. What does 'Hello'.substring(1, 2) return?

    It returns 'e'.

  20. What does 'Hello'.substring(2, 1) return?

    It returns 'e' as the method swaps the given arguments.

  21. The substring() method can accept negative indexes as well. True or false? If true, how does it treat those negative indexes?

    True. It simple converts them to 0. Learn more in JavaScript Strings — String Methods: substring().

  22. Name the two string methods in JavaScript that allow us to perform replacements inside a string.

    replace() and replaceAll().

  23. The first argument of replace() specifies the replacement string while the second argument specifies the string to search for in the main string. True or false?

    False; the statement has mixed up the order of the arguments. The first argument to replace() is the string to search for while the second one is the replacement string. Learn more in JavaScript Strings — String Methods: replace().

  24. What does '100'.replace('0', '1') return?

    '110', since replace() exits as soon as the first replacement is made. Learn more in JavaScript Strings — String Methods: replace().

  25. What is the purpose of the replaceAll() method?

    replaceAll() is used when we wish to replace all occurrences of a given substring from a string (replace() can't be used in this case since it only replaces the first match). Learn more in JavaScript Strings — String Methods: replaceAll().

  26. What does '100'.replaceAll('0', '1') return?

    '111', since replaceAll() replaces all the '0' characters with '1'. Learn more in JavaScript Strings — String Methods: replaceAll().