Skip to content

Hey everyone! πŸ‘‹ I'm diving headfirst into a 100-day JavaScript adventure, and I couldn't be more thrilled to share it with you all! πŸŽ‰ Over the next three months, I'll be immersing myself in everything JavaScript has to offer, from the very basics to some seriously advanced concepts.

Notifications You must be signed in to change notification settings

lassiecoder/100daysofjs

Β 
Β 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

23 Commits
Β 
Β 

Repository files navigation

Object to primitive conversion

πŸ₯‘ Conversion rules

πŸ₯‘ Hints

πŸ₯‘ Symbol.toPrimitive

πŸ₯‘ toString/valueOf

πŸ₯‘ Further conversions


Conversion rules

In Type Conversions, we covered numeric, string, and boolean conversions for primitives, leaving out details for objects.

Now, with knowledge of methods and symbols, we can fill this gap. Objects are always true in boolean contexts. Numeric conversion occurs during subtraction or mathematical operations, while string conversion typically happens when outputting objects.

We can implement custom string and numeric conversions using object methods.

Hints

JavaScript use different type conversion strategies, known as "hints", to handle various situations:

  1. "string": Used for object-to-string conversions, such as when performing operations that expect a string result, like alerting an object or using it as a property key in another object.

For example:

alert(obj);
anotherObj[obj] = 123;
  1. "number": In the case of an object-to-number conversion, which occurs during mathematical operations:

Explicit Conversion: You can explicitly convert an object to a number using the Number() function.

For example:

let num = Number(obj);

Mathematical Operations: Objects can be implicitly converted to numbers in mathematical operations, excluding the binary plus operator.

For example:

let n = +obj; // Unary plus
let delta = date1 - date2;
let greater = user1 > user2;
  1. "default": it's is used in situations where the operator is unsure about the expected type

    For binary plus (+), which can concatenate strings or add numbers, it uses the "default" hint to convert objects. Similarly, comparisons using == with strings, numbers, or symbols also use the "default" hint.

For example:

// Binary plus uses the "default" hint
let total = obj1 + obj2;

// Comparison with a number uses the "default" hint
if (user == 1) { ... };

Symbol.toPrimitive

Symbol.toPrimitive is a built-in symbol used to define the conversion method

For example:

obj[Symbol.toPrimitive] = function(hint) {
  // Conversion logic here
  // Must return a primitive value
};

If Symbol.toPrimitive method exists, it's used for all conversion hints.

For example:

let user = {
  name: "John",
  money: 1000,

  [Symbol.toPrimitive](hint) {
    alert(`hint: ${hint}`);
    return hint == "string" ? `{name: "${this.name}"}` : this.money;
  }
};

// Conversions demo:
alert(user);      // hint: string -> {name: "John"}
alert(+user);     // hint: number -> 1000
alert(user + 500); // hint: default -> 1500

In the above example, the single Symbol.toPrimitive method handles all conversion cases based on the provided hint.

toString/valueOf

If Symbol.toPrimitive is not implemented, JavaScript looks for the toString and valueOf methods as fallbacks.

toString() and valueOf() are methods used for converting objects to primitive values. These methods are invoked implicitly in various contexts to perform type conversions.

toString():

  1. The toString() method returns a string representing the object
  2. It's automatically called when an object is used in a string context, such as concatenation with a string or when passed to functions like alert()
  3. If toString() is not overridden in the object, it returns "[object Object]"

For example:

let obj = {
  name: "John",
  age: 30,
  toString() {
    return `${this.name}, ${this.age} years old`;
  }
};

console.log(obj.toString()); // Output: "John, 30 years old"

valueOf():

  1. The valueOf() method returns the primitive value of the object.
  2. It's automatically called when an object is used in a numeric context, such as arithmetic operations or comparisons
  3. If valueOf() is not overridden, JavaScript tries to use the object's primitive value by default (e.g., number value if possible)

For example:

let obj = {
  value: 42,
  valueOf() {
    return this.value;
  }
};

console.log(obj.valueOf()); // Output: 42

Further conversions

In operations involving objects, JavaScript undergoes two conversion stages.

  1. The object is converted to a primitive using predefined rules
  2. If required, the resulting primitive is further converted

For example:

let obj = {
  toString() {
    return "2";
  }
};

alert(obj * 2); // 4

In the above example, the object is first converted to the primitive value "2", then the multiplication operation is performed, resulting in the numeric value 4.

Likewise, the binary plus operator performs string concatenation.

For example:

let obj = {
  toString() {
    return "2";
  }
};

alert(obj + 2); // "22"

In the above example, the object is converted to the string "2", which is then concatenated with the string "2", resulting in "22".

About

Hey everyone! πŸ‘‹ I'm diving headfirst into a 100-day JavaScript adventure, and I couldn't be more thrilled to share it with you all! πŸŽ‰ Over the next three months, I'll be immersing myself in everything JavaScript has to offer, from the very basics to some seriously advanced concepts.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published