Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coerce to number

Tags:

I have often seen the trick

after = +after; 

to coerce the variable after to a number. Reading through the Node.JS source I found another method:

after *= 1; // coalesce to number or NaN 

Are the two methods strictly equivalent in their behaviour?

like image 970
Randomblue Avatar asked Apr 07 '13 17:04

Randomblue


People also ask

What are the types of coercion?

And still there are only three types of conversion: numeric, string and boolean. coerced to true , no matter if an object or an array is empty or not. Objects are converted to primitives via the internal [[ToPrimitive]] method, which is responsible for both numeric and string conversion.

What is coerce in JavaScript?

What is Type Coercion in JavaScript? Type coercion is the automatic or implicit conversion of values from one data type to another. For example, converting a string value to an equivalent number value. It is also known as type conversion. Type coercion can be useful but it can cause inconsistencies.

How do I cast a number in JavaScript?

How to convert a string to a number in JavaScript using the parseInt() function. Another way to convert a string into a number is to use the parseInt() function. This function takes in a string and an optional radix. A radix is a number between 2 and 36 which represents the base in a numeral system.

What is implicit coercion?

Implicit coercion refers to type conversions that are hidden, with non-obvious side-effects that implicitly occur from other actions. In other words, implicit coercions are any type conversions that aren't obvious (to you).


1 Answers

Yes. Both Unary Operator + and Multiplicative Operators such as * (called from Compound Assignment op=) invoke the internal ToNumber algorithm.

You can even use a 3rd option by statically calling the Number constructor:

after = Number(after); 
like image 159
Fabrício Matté Avatar answered Oct 11 '22 12:10

Fabrício Matté