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

Prepare for the Salesforce JavaScript Developer I Certification Exam. Utilize interactive quizzes, flashcards, and detailed explanations for each question. Boost your confidence and ace your exam effortlessly!

In JavaScript, the output of the expression sum(1, '2') is "12" due to the way JavaScript handles type coercion during operations. When the + operator is used, it can serve both as an arithmetic operator for numbers and as a string concatenation operator.

In this case, when you call a function like sum with arguments 1 (a number) and '2' (a string), JavaScript automatically converts the number into a string to perform concatenation. This type coercion happens because the presence of a string in the operation prompts JavaScript to treat it as a string operation rather than a numerical addition.

As a result, the number 1 is converted to the string "1", and when it is concatenated with '2', the resulting output is the string "12". This demonstrates an important aspect of JavaScript's dynamic typing and how it resolves operations involving different data types. So the answer being "12" correctly reflects this behavior.

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy