惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
Security Latest
Security Latest
C
Cisco Blogs
P
Palo Alto Networks Blog
Know Your Adversary
Know Your Adversary
Project Zero
Project Zero
C
Cyber Attacks, Cyber Crime and Cyber Security
NISL@THU
NISL@THU
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Secure Thoughts
P
Privacy International News Feed
V
Vulnerabilities – Threatpost
D
Docker
Google Online Security Blog
Google Online Security Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Recent Announcements
Recent Announcements
T
The Exploit Database - CXSecurity.com
G
Google Developers Blog
Schneier on Security
Schneier on Security
小众软件
小众软件
爱范儿
爱范儿
GbyAI
GbyAI
J
Java Code Geeks
T
Tailwind CSS Blog
Cisco Talos Blog
Cisco Talos Blog
The Hacker News
The Hacker News
D
DataBreaches.Net
Blog — PlanetScale
Blog — PlanetScale
TaoSecurity Blog
TaoSecurity Blog
MyScale Blog
MyScale Blog
B
Blog RSS Feed
Cyberwarzone
Cyberwarzone
有赞技术团队
有赞技术团队
Martin Fowler
Martin Fowler
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Securelist
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Y
Y Combinator Blog
S
Schneier on Security
Latest news
Latest news
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 叶小钗
F
Fortinet All Blogs
M
MIT News - Artificial intelligence
PCI Perspectives
PCI Perspectives
V
V2EX
V2EX - 技术
V2EX - 技术
O
OpenAI News
W
WeLiveSecurity

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback()
JavaScript Addition Operator in Details
Dmitri Pavlutin · 2016-01-02 · via Dmitri Pavlutin Blog
Post cover

Introduction

JavaScript is an awesome language. I like it because of the flexibility: just do the things in a way you like: change the variable type, add methods or properties to object on the fly, use operators on different variable types and much more.

However the dynamism comes with a price. Developer needs to understand how to handle types conversion for different operators: addition (+), equality (== and ===), inequality (!= and !==), etc. Many operators have their own way to handle the type conversions.

The addition operator

One of the most commonly used operator is addition: +. This operator is used to concatenate strings or sum the numbers:

  1. Strings concatenation:


var result = "Hello, " + "World!";

// string + string = string (concatenation)

// "Hello, World!"


  1. Numbers arithmetic addition:


var result = 10 + 5;

// number + number = number (addition)

// 15


JavaScript allows to use objects, arrays, null or undefined as operands. Let's try to demystify the general rule of conversion.

Conversion rules

Use following scheme to see how JavaScript converts types in addition operation:


operand + operand = result


  1. If at least one operand is an object, it is converted to a primitive value (string, number or boolean);
  2. After conversion, if at least one operand is string type, the second operand is converted to string and the concatenation is executed;
  3. In other case both operands are converted to numbers and arithmetic addition is executed.

If both operands are primitive types, then operator checks if at least one is string and executes the concatenation. In other case it just transforms everything to numbers and sum.

Object to primitive

The object to primitive conversion:

  • If object type is Date, then toString() method is used;
  • In other case valueOf() method is used, if it returns a primitive value;
  • In other case (if valueOf() doesn't exist or doesn't return a primitive value), then toString() method is used. This happens most of the times.

When an array is converted to a primitive, JavaScript uses its join(',') method., e.g. the primitive of [1, 5, 6] is "1,5,6". The primitive value of a plain JavaScript object {} is "[object Object]".

Learning from examples

The following examples help to understand the simple and complex cases of the conversions.

Example 1: Number and string


var result = 1 + "5"; // "15"


Explanation:

  1. 1 + "5" (The second operand is a string and based on rule 2 the number 1 becomes "1")
  2. "1" + "5" (Strings concatenation)
  3. "15"

The second operand is a string. The first operand is converted from number to string and the concatenation is done.

Example 2: Number and array


var result = [1, 3, 5] + 1; //"1,3,51"


Explanation:

  1. [1, 3, 5] + 1 (Using the rule 1, transform the array [1, 3, 5] to a primitive value: "1,3,5")
  2. "1,3,5" + 1 (Using the rule 2, transform the number 1 to a string "1")
  3. "1,3,5" + "1" (Strings concatenation)
  4. "1,3,51"

The first operand is an array, so it is transformed to a primitive string value. At next step the number operand is transformed to string. Then the concatenation between 2 strings is done.

Example 3: Number and boolean


var result = 10 + true; //11


Explanation:

  1. 10 + true (Based on rule 3 convert the boolean true to a number 1)
  2. 10 + 1 (Sum two numbers)
  3. 11

Because neither of the operands is a string, the boolean is converted to number. Then the arithmetic addition is performed.

Example 4: Number and object


var result = 15 + {}; // "15[object Object]"


Explanation:

  1. "15 + {}" (The second operand is an object. Apply the rule 1 and the object to primitive is a string "[object Object]")
  2. 15 + "[object Object]" (Using rule 2 transform the number 15 to a string "15")
  3. "15" + "[object Object]" (Strings concatenation)
  4. "15[object Object]"

The second object operand is converted to a string value. Because valueOf() method returns the object itself and not a primitive value, the toString() method is used, which returns string. The second operand is now a string, thus the number is converted to string too. The concatenation of 2 strings is executed.

Example 5: Number and null


var result = 8 + null; // 8


Explanation:

  1. 8 + null (Because none of the operands is string, convert the null to a number 0 based on rule 3)
  2. 8 + 0 (Numbers addition)
  3. 8

Because operands are not objects or strings, null is converted to number. Then numbers sum is evaluated.

Example 6: String and null


var result = "queen" + null; // "queennull"


Explanation:

  1. "queen" + null (Because none first operand is string, convert the null to a string "null" based on rule 2)
  2. "queen" + "null" (Strings concatenation)
  3. "queennull"

Because the first operand is a string, null is converted to string. Then the strings concatenation is done.

Example 7: Number and undefined


var result = 12 + undefined; // NaN


Explanation:

  1. 12 + undefined (Because none of the operands is string, convert the undefined to a number NaN based on rule 3)
  2. 12 + NaN (Numbers addition)
  3. NaN

Because neither of the operands is object or string, undefined is converted to number: NaN. Making an addition between number and NaN evaluates always to NaN.

See the examples in JS Bin

Conclusion

To avoid potential issues, do not use addition operator with objects, unless you clearly define toString() or valueOf() methods. As seen in examples, the addition operator has many specific cases. Knowing the exact conversion scenario will help you to prevent future surprises. Have a good coding day!

Dmitri Pavlutin

About Dmitri Pavlutin

Software developer and sometimes writer. My daily routine consists of (but not limited to) drinking coffee, coding, writing, overcoming boredom 😉, developing a gift boxes Shopify app, and blogging about Shopify. Living in the sunny Barcelona. 🇪🇸