Skip to content

Latest commit

 

History

History
161 lines (123 loc) · 2.55 KB

56.to-primitive.md

File metadata and controls

161 lines (123 loc) · 2.55 KB

56. to primitive

Problem

https://bigfrontend.dev/quiz/primitive

Problem Description

What does the code snippet below output by console.log?

// case 1
const obj1 = {
  valueOf() {
    return 1;
  },
  toString() {
    return '100';
  },
};

console.log(obj1 + 1);
console.log(parseInt(obj1));

// case 2
const obj2 = {
  [Symbol.toPrimitive]() {
    return 200;
  },

  valueOf() {
    return 1;
  },
  toString() {
    return '100';
  },
};

console.log(obj2 + 1);
console.log(parseInt(obj2));

// case 3
const obj3 = {
  toString() {
    return '100';
  },
};

console.log(+obj3);
console.log(obj3 + 1);
console.log(parseInt(obj3));

// case 4
const obj4 = {
  valueOf() {
    return 1;
  },
};

console.log(obj4 + 1);
console.log(parseInt(obj4));

// case 5
const obj5 = {
  [Symbol.toPrimitive](hint) {
    return hint === 'string' ? '100' : 1;
  },
};

console.log(obj5 + 1);
console.log(parseInt(obj5));

Answer

/* ------- case 1 ------- */

const obj1 = {
  valueOf() {
    return 1;
  },
  toString() {
    return '100';
  },
};

console.log(obj1 + 1); // 2
// JavaScript uses `obj1`'s `valueOf()` to convert the object to a primitive.

console.log(parseInt(obj1)); // 100
// `parseInt()` expects a string value. If the argument is not a string,
// then it is converted to one.

/* ------- case 2 ------- */

const obj2 = {
  [Symbol.toPrimitive]() {
    return 200;
  },

  valueOf() {
    return 1;
  },
  toString() {
    return '100';
  },
};

console.log(obj2 + 1); // 201
console.log(parseInt(obj2)); // 200
// When converting an object to a primitive value, JavaScript will first
// call the method `Symbol.toPrimitive` if it is present.
// The `Symbol.toPrimitive` takes in a string argument `hint`, which
// gives us fine-grained control over the result primitive value.

/* ------- case 3 ------- */

const obj3 = {
  toString() {
    return '100';
  },
};

console.log(+obj3); // 100
console.log(obj3 + 1); // '1001'
console.log(parseInt(obj3)); // 100

/* ------- case 4 ------- */

const obj4 = {
  valueOf() {
    return 1;
  },
};

console.log(obj4 + 1); // 2
console.log(parseInt(obj4)); // NaN

/* ------- case 5 ------- */

const obj5 = {
  [Symbol.toPrimitive](hint) {
    return hint === 'string' ? '100' : 1;
  },
};

console.log(obj5 + 1); // 2
console.log(parseInt(obj5)); // 100

Reference