Prepare for the Salesforce JavaScript Developer Exam. Utilize comprehensive quizzes, flashcards, and multiple choice questions with hints and explanations. Boost your exam readiness!

Practice this question and more.


How does JavaScript handle type coercion when adding a number and a string?

  1. It returns a TypeError.

  2. It performs implicit conversion to a number.

  3. It concatenates them as strings.

  4. It returns NaN.

The correct answer is: It concatenates them as strings.

When adding a number and a string in JavaScript, the language performs type coercion, which means it implicitly converts one of the values to accommodate the operation. In this case, when a number is added to a string, JavaScript converts the number to a string and then concatenates the two string values together. This concatenation happens because JavaScript prioritizes handling the operation as a string addition when one of the operands is a string. For example, if you have the number `5` and the string `"3"`, the operation `5 + "3"` would result in the string `"53"` rather than performing mathematical addition. This behavior arises from JavaScript’s flexible typing system and is a key characteristic of how it handles mixed data types in operations. The other choices do not accurately describe what occurs in this situation. There is no TypeError since the operation is valid, and NaN (Not a Number) would only arise from operations that are not mathematically valid, such as adding non-numeric strings. Implicit conversion to a number does not occur here because the presence of a string in the operation dictates that the result will be a string through concatenation.