Javascript Developer JSE 40 01 · Free Practice Question Medium
Question 4
Q442 - Data Types
Which of the following statements
are examples of String conversion to Number?
(Select two correct answers)
-
A
- let n = String(2048);
-
B
- let n = "2048" + 0;
-
C
- let n = Number("2048");
-
D
- let n = "2048" * 1;
Reveal correct answers
Correct answers: C, D
Explanation
Topics: Number() multiplication operator
Try it yourself:
- let n1 = "2048" * 1;
- console.log(n1); // 2048
- console.log(typeof n1); // number
- let n2 = Number("2048");
- console.log(n2); // 2048
- console.log(typeof n2); // number
- let n3 = "2048" + 0;
- console.log(n3); // 20480
- console.log(typeof n3); // string
- let n4 = String(2048);
- console.log(n4); // 2048
- console.log(typeof n4); // string
Explanation:
To be able to calculate with a string, JavaScript converts it to a number.
"2048" will be converted to the number 2048
And 2048 * 1 is again 2048
The Number() constructor creates a Number object.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/Number
The multiplication operator produces the product of the operands,
but attempts to convert them into numbers, if they aren't already.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Multiplication
(There is a similar question Q515.)
Q442 (Please refer to this number, if you want to write me about this question.)
A. The String() function converts the number 2048 to a string. This is the opposite operation of what the question is asking for, which is converting a string to a number.
B. The expression "2048" + 0 concatenates the string "2048" with the number 0, resulting in a string value. This does not convert the string to a number as requested in the question.
C. The Number() function explicitly converts the string "2048" to a number. This is a straightforward and recommended way to convert a string to a number in JavaScript.
D. The expression "2048" * 1 converts the string "2048" to a number by using the multiplication operator. This is a common way to convert a string to a number in JavaScript.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
