CCA Prep

Lesson 1.3Lesson 3 of 24

Type coercion

Given a scenario or example, demonstrate awareness of type coercion and its effects.

Type coercionConvertobjects toprimitivesarrays andobjects becomestringsIs either sidea string?then + joins thetwo as textOtherwiseconvert tonumberstrue is 1, nullis 0, undefinedis NaNCalculate-, *, / alwaystake this pathThis is the path for +. Use Number() or String() when the type matters.

Key points

  1. 1With a string on either side, + joins text. The operators -, *, / and % always convert to numbers.
  2. 2Objects and arrays become strings first: an array joins its items with commas, a plain object becomes [object Object].
  3. 3== converts types before comparing, but null equals only null and undefined, and NaN equals nothing. Prefer ===.
  4. 4< and > compare two strings character by character, so '10' < '9' is true. With one number, the string is converted.
  5. 5Explicit conversion makes intent clear: Number('') is 0 and Number('7kg') is NaN, while parseInt('7kg') reads 7.
What the exam guide checks here

Objective wording from the exam guide (English).

  • 1.3.K1Implicit coercion in +, ==, relational operators and template literals
  • 1.3.K2Explicit conversion: String(), Number(), Boolean(), unary +, parseInt
  • 1.3.S1Predict the result of an expression that mixes types

Lock it in

Answer scenario questions on this topic. Every option comes with an explanation.

Practise 1.3 · 12 questions