0

in a solution for a hackerrank riddle i found the following code. the link to the riddle is https://www.hackerrank.com/challenges/js10-data-types/problem

i have never seen anything before and in the internet was nothing to found about it. the code snippet is:

console.log(firstDecimal + +(secondDecimal));

what is this ++ sign?

thanks in advance for your help.

  • 1
    There is no `++` sign in the code you posted. – axiac May 09 '18 at 19:34
  • I see a `+` sign, a space and another `+`. They are definitely not the same thing as `++`. – axiac May 09 '18 at 19:37
  • 2
    The first `+` is the usual [addition operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition). The second `+` is the ["unary plus"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus) operator (it's just a `+` sign in front of the value, it doesn't change the value but it forces it to be evaluated as a number, in case it's something else). `++` is the [increment operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment) – axiac May 09 '18 at 19:41

2 Answers2

1

+(secondDecimal) is roughly equivalent to Number(secondDecimal). It converts the value of secondDecimal to a number. So

firstDecimal + +(secondDecimal)

is like

firstDecimal + Number(secondDecimal)

If you don't do this, and secondDecimal contains a string,

firstDecimal + secondDecimal

will perform string concatenation rather than numeric addition.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

As you can see in this simple example, it is just a simple casting in js.

var firstDecimal = '1',
  secondDecimal = '2';

console.log("Both strings:", firstDecimal + +(secondDecimal));

var fD = 1,
  sD = '2';

console.log("First numeric, second string:", fD + +(sD));

var fd = '1',
  sd = 2;

console.log("First string, second numeric:", fd + +(sd));

Read more about type conversation here

Saeed
  • 5,413
  • 3
  • 26
  • 40