11

I see there + operator is being used to convert a string number to number and same does the Number() function ,

So i am wondering there must be good reason for + operator before string number being used in most cases over Number()

Is there any performance enhancement with + operator?

appreciate your help guys

note : don't get confuse with concatenation of string , its unary + oprator

DEEPAK
  • 1,364
  • 10
  • 24
  • 1
    *Is there any performance enhancement* No. Essentially they both use `toNumber` function. So it all falls on personal choice. Most people use `+`(unary + operator) because its less typing. But few people like to have verbose code so its easy for you to read/understand. Hence `Number()`. Refer: https://stackoverflow.com/a/17106702/3783478 – Rajesh Jan 20 '20 at 09:51
  • I suppose because `+` to type is fast. – Jai Jan 20 '20 at 09:54
  • 2
    Is there any performance enhancement with + operator? [Perhaps](http://jsben.ch/ZihEt). But I guess it depends on the exact runtime (I get opposite results with Chrome and Firefox) and it's probably negligible anyway. – Álvaro González Jan 20 '20 at 09:55
  • Almost certainly completely negligible in 99% of real-world situations – CertainPerformance Jan 20 '20 at 09:56
  • 3
    Note that you'll get behavioural differences between `Number` objects and primitives, e.g. `new Number('4') !== 4`, but `4 === 4`… – deceze Jan 20 '20 at 09:56
  • 3
    I get the feeling OP was wondering about, eg, `Number(val)` vs `+val`, but not `new Number(val)`, which is weird and completely different. There are rarely differences between `Number` and `+`, it's mostly just a style choice – CertainPerformance Jan 20 '20 at 09:58
  • Number() is used for type casting and + is used to concatenate string & to add (if all operands are numbers) – Aabir Hussain Jan 20 '20 at 10:01
  • 1
    @deceze I thought usage of `Numer` was `Number(4) === 4` and not `new Number`. Adding `new` will return an object. Like `new Boolean` etc. – Rajesh Jan 20 '20 at 10:03
  • @Aabir In this case OP is talking about the [*unary plus*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus_2)! – deceze Jan 20 '20 at 10:03
  • @AabirHussain The `+` OP is thinking about is unary plus, not the addition operator – CertainPerformance Jan 20 '20 at 10:03
  • @Rajesh Both are possible, different uses. Just wanted to point out the difference when used with `new`, as it wasn't explicitly ruled out. – deceze Jan 20 '20 at 10:04
  • Sorry, I get my mistake from @Rajesh comment. thanks – Aabir Hussain Jan 20 '20 at 10:05
  • yes , i get it , well i know new will create an object and that will never match and thank you for the resources – DEEPAK Jan 20 '20 at 10:07

0 Answers0