Javascript Developer JSE 40 01 · Free Practice Question Easy
Question 2
Q115 - Data Types
We want to convert the number 1024 to a String type
and store the result in a variable s
Point out the correct statement:
-
A
- let s = NumberToString(1024);
-
B
- let s = 1024 + "0";
-
C
- let s = String(1024);
-
D
- let s = Number(1024);
Reveal correct answer
Correct answer: C
Explanation
Topic: String()
Try it yourself:
- let s1 = String(1024);
- console.log(s1); // 1024
- console.log(typeof s1); // string
- let s2 = 1024 + "0";
- console.log(s2); // 10240
- console.log(typeof s2); // string
- let s3 = Number(1024);
- console.log(s3); // 1024
- console.log(typeof s3); // number
- // let s4 = NumberToString(1024);
- // Uncaught ReferenceError: NumberToString is not defined
Explanation:
The String() constructor converts a value to a string.
https://www.w3schools.com/jsref/jsref_string.asp
(There is a similar question Q515.)
Q115 (Please refer to this number, if you want to write me about this question.)
A. There is no built-in function called NumberToString() in JavaScript. Using this function will result in an error, as it is not a valid method for converting a number to a string. The correct method is to use the String() function for this conversion.
B. Adding a number to a string in JavaScript will result in concatenation, not conversion. In this case, the number 1024 will be concatenated with the string "0", resulting in "10240", not a proper conversion to a string.
C. Using the String() function is the correct way to convert a number to a string in JavaScript. This function explicitly converts the number 1024 to a string and stores it in the variable s.
D. Using the Number() function will not convert the number 1024 to a string; instead, it will keep it as a number type. This is not the correct approach for converting a number to a string in JavaScript.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
