# Lesson 15: Mastering JavaScript Unary + operator with challenges!

The **Unary** `+` operator is used to **convert any value to a number**, and it’s one of the fastest ways to perform type coercion. It’s a **unary operator**, meaning it takes **one operand** and evaluates to a numeric equivalent of that operand.

### 🔧 Syntax

```plaintext
+operand
```

---

### 🧾 **Examples**

#### ✅ Basic Examples:

```plaintext
+42        // 42
+"42"      // 42
+true      // 1
+false     // 0
+null      // 0
+undefined // NaN
+"abc"     // NaN
```

#### ✅ Real-world Example:

```plaintext
let userInput = "100.50";
let price = +userInput; // faster than Number(), parseFloat()
```

#### 📈 Diagram: Unary + Evaluation Flow

```plaintext
+value
   |
   v
Is primitive? ──► Yes ──► ToNumber() 
   |                       |
   No                      v
   |                   Final Number (or NaN)
ToPrimitive()
   |
   v
Then ToNumber()
```

---

## 🔹 2. **Fill Any Gaps**

### 🔍 **Hidden Concepts, Gaps, and Quirks**

#### 🧠 Uses `ToNumber()` Abstract Operation

* Same logic as `Number(value)` internally (defined in ECMA-262).
    
* Performs `ToPrimitive()` first if the value is an object.
    
* Then tries `valueOf()` → `toString()` chain.
    

#### 🤯 Non-Obvious Behavior

```plaintext
+[]        // 0  → Array → "" → 0
+{}        // NaN → Object → "[object Object]" → NaN
+["42"]    // 42
+[1,2]     // NaN → "1,2" is not a valid number
+function(){} // NaN → Function string → NaN
```

---

### ⚠️ **What Devs Often Get Wrong**

1. **Assuming +\[\] gives NaN** — Nope, it gives `0`.
    
2. **Misunderstanding +\[value\] vs +\[\] vs +\[x,y\]**.
    
3. **Not realizing it's not the same as** `parseInt()` or `parseFloat()`:
    
    ```plaintext
    parseInt("10abc")   // 10
    +"10abc"            // NaN
    ```
    

---

### 🧪 **Browser-Specific Quirk**

* `+document.all` (an exotic object) returns `NaN` in most browsers but behaves oddly in some contexts due to its legacy `[object HTMLAllCollection]` value.
    

---

## 🔹 3. **Challenge Me Deeply**

### 🟢 **Basic**

1. Convert `"50"` to a number using unary `+`.
    
2. Predict: `+true + +false`
    
3. What does `+null` evaluate to?
    
4. What will `+""` give?
    
5. Evaluate: `+["100"]`
    

### 🟡 **Intermediate**

6. Explain why `+[1,2,3]` gives `NaN`.
    
7. Coerce a variable to number only if it's a numeric string.
    
8. What happens with `+{valueOf: () => "42"}`?
    
9. Rewrite `parseFloat(input)` using unary `+` safely.
    
10. Predict: `+["42px"]` and explain why.
    

### 🔴 **Advanced**

11. Create a function that checks if any value can be safely coerced with `+` (i.e., doesn’t produce `NaN`).
    
12. Given: `const arr = [true, "10", false, null, "abc"];` → use unary `+` to return an array of numbers or `NaN`.
    
13. In what cases does `+obj` not call `toString()`?
    
14. What happens when you apply unary `+` to a Symbol?
    

### 🎯 **Brain-Twister**

15. What does this log?
    

```plaintext
let x = +[+[]] + +[+[]];
console.log(x);
```

---

## 🔹 4. **Interview-Ready Questions**

### 📘 **Concept-Based**

* How does unary `+` differ from `Number()` or `parseFloat()`?
    
* What’s the internal operation behind unary `+`?
    

### ⚠️ **Debugging-Based**

```plaintext
let value = "10px";
let coerced = +value;
console.log(coerced); // Why NaN?
```

### 🎭 **Scenario-Based**

* You receive data from a form as strings. When would you **not** use unary `+` for conversion?
    

---

### ✅ Best Practices

* Use `+` for **clean numeric strings**.
    
* Prefer `Number()` for safety and clarity when inputs are unknown.
    
* Avoid coercing objects unless necessary.
    

### 🚫 Red Flags

* Using `+` with complex objects (like dates or arrays).
    
* Relying on coercion without checking for `NaN`.
    

---

## 🔹 5. **Real-World Usage**

### ✅ **Where it's used:**

* **Forms & User Input**: Converting input fields to numbers
    
    ```plaintext
    let quantity = +document.querySelector("#qty").value;
    ```
    
* **Short-circuit conversion** in:
    
    * Analytics scripts
        
    * Game engines (e.g., Phaser.js internal scoring)
        
    * Financial calculations in React/Vue components
        
* Used in **framework internals**:
    
    * Vue uses unary `+` in its compiled template render functions for performance.
        

---

## 🔹 6. **Remember Like a Pro**

### 🧠 Mnemonics:

* **“Unary + = Upgrade to Number”**
    
* **+truth = 1**, **+false = 0**
    
* **+empty box = 0 (\[\])**, **+object = NaN ({})**
    

### 🧾 Cheatsheet:

| Input | Result |
| --- | --- |
| `+true` | 1 |
| `+false` | 0 |
| `+""` | 0 |
| `+"123"` | 123 |
| `+[]` | 0 |
| `+["123"]` | 123 |
| `+{}` | NaN |
| `+undefined` | NaN |
| `+null` | 0 |
| `+[1,2,3]` | NaN |

---

## 🔹 7. **Apply It in a Fun Way**

### 🎮 **Mini Project**: **"Smart Number Converter UI"**

**Goal**: Build a small input box that instantly shows the result of `+input` in real-time.

#### 🛠 Steps:

1. Create a simple HTML input box.
    
2. Use `input` event listener in JS.
    
3. Show the result of `+input.value` dynamically.
    
4. If result is `NaN`, show `"Invalid number"`.
    

#### 🔁 Extension Ideas:

* Add toggle to view `Number()`, `parseFloat()` results too.
    
* Show `typeof` of the input and coerced result.
    

---

## ➕ (Bonus Pro Insights)

### 🧩 **Open-Source Usage**:

* **Vue.js**, **React DevTools**, and **Chart.js** use coercion tricks like unary `+` to reduce performance overhead on large datasets.
    

### ❌ Common Mistakes:

* Using unary `+` to coerce potentially **non-numeric strings**.
    
* Using `+object` assuming custom coercion will work.
    

### ⚙️ **Performance Tip**:

* Unary `+` is faster than `Number()` in hot loops.
    

### 🛡️ **Polyfill?**

No need. It’s native and universal.
