JavaScript Quiz #03 — JavaScript String

Topics: JavaScript Strings and literals

Follow us on

Quick summary of string in JavaScript:

  • The String object in JavaScript is used to represent and manipulate sequences of characters.

  • Strings can be created as primitives using string literals or as objects using the String() constructor.

    const string1 = "A string primitive";
    const stringObject = new String("A String object");
    const emptyString= new String(); // Empty string object
  • String literals can be specified using single quotes, double quotes, or backticks (template literals).

  • String literals and strings created without the new keyword are primitives, while String objects are created with the new keyword.

    let name = "John";
    let country = 'UK';
    let greeting = `Hello, my name is ${name} and I'm from ${country}.`;
  • Character access in a string can be done using the charAt() method or by treating the string as an array-like object.
    const str = "Hello, World!";
    console.log(str.charAt(0)); // Output: "H"
    console.log(str[7]); // Output: "W"
  • JavaScript, string comparison operators are used to compare two strings and determine their relative order based on their Unicode values. Here are the string comparison operators in JavaScript:

Equality operator: (==), Inequality operator: (!=), Strict equality operator: (===), Strict inequality operator: (!==), Greater than operator: >, Less than operator: <, Greater than or equal to operator: >=, Less than or equal to operator: <=

  • Equality Operator (==): The equality operator compares the values of two operands and performs type coercion if necessary. Strict equality operator(===) compares the values and types of the operands.
    console.log(1 == "1");   // Output: true
    console.log(1 === "1");   // Output: false
  • Character access in a string can be done using the charAt() method or by treating the string as an array-like object.
    const str = "Hello, World!";
    console.log(str.charAt(0)); // Output: "H"
  • String coercion in JavaScript occurs when performing operations involving strings and other data types. It involves converting those non-string values into strings.
    let str = "Hello";
    let num = 42;
    
    let result1 = str + num;
    console.log(result1);  // Output: "Hello42"
    
    let result2 = "The answer is: " + 42;
    console.log(result2);  // Output: "The answer is: 42"
    
    let result3 = 10 + "20";
    console.log(result3);  // Output: "1020
  • String object has various methods for manipulating and extracting information from strings, such as concat(), endsWith(), includes(), indexOf(), match(), replace(), split(), and more

Quizzes

1. What is the output of the following code snippet?

let str = "Hello";
console.log(str.split(""));

a) [“H”, “e”, “l”, “l”, “o”]

b) [“Hello”]

c) [“olleH”]

d) “Hello”

Answer: a) [“H”, “e”, “l”, “l”, “o”]

The split() method is used to split a string into an array of substrings. In this case, an empty string as the separator splits the string at every character, resulting in an array containing each character as an element. Therefore, the output will be ["H", "e", "l", "l", "o"].

2. What is the output?

let x = “John”;
let y = new String(“John”);
console.log(x === y);

a) true

b) false

Ans: False

The reason for the false result is that x is a string primitive, while y is a String object created using the new keyword.

The strict equality operator (===) not only compares the values but also checks for the types of operands. In this case, x is a string primitive, and y is an object of the String type.

3. What is the output of the following code snippet?

let str =5+ 2;
console.log(str);

a) “7”

b) “52”

c) 7

d) 52

Answer: b) “52”

When the + operator is used with a string and a number, it performs string concatenation. In this case, the string "5" is concatenated with the number 2, resulting in the string "52". Therefore, the output will be "52".

4. What is the output of the following code snippet?

let str = “Hello” — 2;
console.log(str);

a) NaN

b) “Hello2”

c) “Hello-2”

Answer: a) NaN

When a string that cannot be coerced into a number is used in an arithmetic operation, JavaScript returns NaN (Not a Number). In this case, the string "Hello" cannot be converted into a number, so the result of the subtraction operation is NaN

5. Which method is used to remove whitespace from both ends of a string ?

a) string.trim();

b) string.strip();

c) string.removeWhitespace();

d) string.trimWhitespace();

Answer: a) string.trim();

The trim() method is used to remove whitespace from both ends of a string. It returns a new string with the leading and trailing whitespace removed.

6. What is the output of the following code snippet?

let str = “Hello, World!;
console.log(str.slice(0, 5))

a) “Hello”

b) “Hello,”

c) “Hell”

d) “World”

Answer: a) “Hello”

The slice() method extracts a portion of the string starting from index 0 and ending at index 5 (exclusive). In this case, it will extract the substring "Hello" from the original string "Hello, World!".

7. What is the output?

const str = null;
str.toString();

a) null

b)undefined

c) TypeError

Ans: TypeError

When attempting to call the toString() method on a null value, a TypeError will be thrown. This is because null does not have any properties or methods associated with it, including the toString() method. Therefore, trying to invoke a method on null will result in a TypeError being thrown.

8. What is the output of the following code snippet?

let str = “Hello, World!;
console.log(str.substr(-3))

a) “Hello”

b) “Hello,”

c) “or!”

d) “ld!”

Answer: d) “ld!”

The substr() method with a negative first argument starts the extraction from the 3rd character from the end and extracts until the end of the string. Thus, it will extract the substring "ld!" from the original string "Hello, World!".

9. Which code snippet checks if a string is empty in JavaScript?

a) str.isEmpty();

b) str.checkEmpty();

c) str.length === 0;

d) str.checkLength();

Answer: c) str.length === 0;

To check if a string is empty in JavaScript, you can compare its length to 0 using the === operator. If the length is 0, the string is empty.

10. What is the difference between using single quotes (') and double quotes (") to create a string literal in JavaScript?

a) There is no difference, both can be used interchangeably.

b) Single quotes should be used for short strings and double quotes for longer strings.

c) Single quotes are preferred for string literals, while double quotes are used for template literals.

Answer: a) There is no difference, both can be used interchangeably.

There is no functional difference between using single quotes (') and double quotes (") to create a string literal. Both types of quotes can be used interchangeably to define a string.

11. Which of the following is an example of a multiline string literal?

a) “Hello\nWorld”

b) ‘Hello\nWorld’

c) Hello\nWorld

Answer: c) Hello\nWorld

To create a multiline string literal in JavaScript, you can use template literals, which are enclosed in backticks (`). Option c) Hello\nWorld represents a multiline string literal with a line break character (\n) in between.