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.


What will be the output of sum(1, '2') in JavaScript?

  1. NaN

  2. TypeError

  3. "12"

  4. 3

The correct answer is: "12"

In JavaScript, when you use the `sum` function, which is likely performing addition here, it will evaluate the operands based on their types according to the rules of type coercion. In the case of `sum(1, '2')`, you have a number (`1`) and a string (`'2'`). When JavaScript encounters the addition operation with these mixed types, it converts the number to a string before performing the operation. This is because the presence of a string in an arithmetic operation triggers a conversion of other operands to string types. As a result, the number `1` is converted to the string `'1'`, and then concatenated with the string `'2'`. This concatenation results in the string `'12'`. This behavior is a fundamental aspect of JavaScript, which allows for flexible type conversions. Therefore, the output of `sum(1, '2')` will be the string `"12"`.