DEV Community

Abhay Singh Kathayat
Abhay Singh Kathayat

Posted on

A Complete Guide to Type Conversion in JavaScript: Implicit vs Explicit Coercion

*### Type Conversion in JavaScript
*

Type conversion in JavaScript refers to the process of converting a value from one data type to another. JavaScript is a dynamically typed language, meaning variables are not bound to a specific data type, and they can be converted automatically or explicitly between different types.

### Types of Type Conversion

There are two types of type conversions in JavaScript:

1. **Implicit Type Conversion (Type Coercion)

  1. Explicit Type Conversion**

### 1. **Implicit Type Conversion (Type Coercion)**

Implicit type conversion, also known as type coercion, happens automatically by JavaScript when performing operations between different data types. JavaScript automatically converts one type to another when needed.

#### Examples of Implicit Type Conversion:

  • String Concatenation When you add a number to a string, JavaScript automatically converts the number into a string.
  let result = '5' + 1;
  console.log(result);  // Output: '51' (String)
Enter fullscreen mode Exit fullscreen mode

-** Boolean Conversion **
When a non-boolean value is used in a boolean context, JavaScript converts it to true or false.

  let isValid = 'hello' == true;  // Implicit coercion
  console.log(isValid);  // Output: true
Enter fullscreen mode Exit fullscreen mode
  • ***Equality Comparisons* ** When comparing different types using ==, JavaScript performs type coercion to make the comparison work.
  let result = '5' == 5;
  console.log(result);  // Output: true (due to implicit coercion)
Enter fullscreen mode Exit fullscreen mode

** 2. Explicit Type Conversion**

Explicit type conversion, also known as type casting, is when you manually convert one type to another using built-in methods or functions. JavaScript provides several functions to convert between types.

Examples of Explicit Type Conversion:

- **Converting to String **
You can use the String() function or .toString() method to convert a value to a string.

  let num = 123;
  let str = String(num);  // Using String()
  console.log(str);  // Output: '123'

  let bool = true;
  let strBool = bool.toString();  // Using .toString()
  console.log(strBool);  // Output: 'true'
Enter fullscreen mode Exit fullscreen mode

- **Converting to Number **
You can use the Number() function, the unary + operator, or parseInt()/parseFloat() to convert a value to a number.

  let str = '123';
  let num = Number(str);
  console.log(num);  // Output: 123

  let bool = true;
  let numBool = +bool;  // Unary plus operator
  console.log(numBool);  // Output: 1

  let floatStr = '12.34';
  let floatNum = parseFloat(floatStr);
  console.log(floatNum);  // Output: 12.34
Enter fullscreen mode Exit fullscreen mode

- **Converting to Boolean **
You can convert a value to a boolean using the Boolean() function.

  let num = 0;
  let bool = Boolean(num);  // Converts to false
  console.log(bool);  // Output: false

  let str = 'hello';
  let boolStr = Boolean(str);  // Converts to true
  console.log(boolStr);  // Output: true
Enter fullscreen mode Exit fullscreen mode

### 3. **Detailed Type Coercion Behavior**

JavaScript's coercion behavior can be confusing, so let's look at how different operations convert types.

  • Addition (+) Operator If one of the operands is a string, JavaScript converts the other operand to a string and performs string concatenation.
  let result = '5' + 1;
  console.log(result);  // Output: '51'
Enter fullscreen mode Exit fullscreen mode
  • Subtraction (-), Multiplication (*), and Division (/) Operators JavaScript tries to convert both operands to numbers before performing the operation.
  let result = '5' - 1;
  console.log(result);  // Output: 4 (Number)

  let resultMul = '5' * 2;
  console.log(resultMul);  // Output: 10 (Number)
Enter fullscreen mode Exit fullscreen mode
  • Equality (==) and Strict Equality (===) Operators
    • == checks for equality with type coercion.
    • === checks for equality without type coercion (strict equality).
  let result = '5' == 5;
  console.log(result);  // Output: true (coercion happens)

  let strictResult = '5' === 5;
  console.log(strictResult);  // Output: false (no coercion)
Enter fullscreen mode Exit fullscreen mode
  • Logical Operators Logical operators like &&, ||, and ! coerce the operands to boolean values.
  let result = 0 || 'hello';
  console.log(result);  // Output: 'hello' (0 is falsy, 'hello' is truthy)

  let resultAnd = 1 && 0;
  console.log(resultAnd);  // Output: 0 (because 0 is falsy)
Enter fullscreen mode Exit fullscreen mode

### 4. **Falsy and Truthy Values**

In JavaScript, certain values are considered falsy or truthy when coerced to a boolean:

  • Falsy Values: false, 0, "" (empty string), null, undefined, NaN.
  • Truthy Values: All values that are not falsy, including [], {}, 1, "hello", etc.

Example:

let value = "";
if (value) {
  console.log("Truthy");
} else {
  console.log("Falsy");  // Output: Falsy (because "" is falsy)
}
Enter fullscreen mode Exit fullscreen mode

### 5. **Handling Null and Undefined**

  • Null to Number null converts to 0 when coerced to a number.
  let num = Number(null);
  console.log(num);  // Output: 0
Enter fullscreen mode Exit fullscreen mode
  • Undefined to Number undefined converts to NaN when coerced to a number.
  let num = Number(undefined);
  console.log(num);  // Output: NaN
Enter fullscreen mode Exit fullscreen mode
  • Null to Boolean null is coerced to false in a boolean context.
  let bool = Boolean(null);
  console.log(bool);  // Output: false
Enter fullscreen mode Exit fullscreen mode

### 6. **The toString() Method**

Every JavaScript object has access to the toString() method, which converts the object to a string. For example, when you call toString() on a number, it returns a string representation of that number.

Example:

let num = 123;
let str = num.toString();  // Converts number to string
console.log(str);  // Output: '123'
Enter fullscreen mode Exit fullscreen mode

Hi, I'm Abhay Singh Kathayat!
I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: kaashshorts28@gmail.com.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️