Two negation operators are placed between two numeric strings, with a space between the negation operators. Asked in Infosys interview. Javascript interview question.


Let's break down Javascript Code:

console.log("1" - - "1");

Step 1: Evaluate the inner unary minus (- "1")

The unary minus operator converts its operand to a number and then negates it.

Here, the string "1" is first converted to the number 1.

Applying the minus sign gives -1.


So, "1" - - "1" becomes:

"1" - (-1)

Step 2: Evaluate the binary subtraction ("1" - (-1))

The binary subtraction operator always converts both operands to numbers.

The left operand, the string "1", is converted to the number 1.

The right operand is already -1.


Now the operation is:

1 - (-1)

Step 3: Perform the subtraction

Subtracting a negative number is the same as adding its positive:


1 - (-1) = 1 + 1 = 2.

Step 4: Output the result

The final result, 2, is printed to the console.

Note The Key Points :

Type coercion:
Both the unary minus and the binary subtraction force JavaScript to convert string operands to numbers.
(Unlike the + operator, which is overloaded to perform string concatenation if one operand is a string, the - operator is strictly arithmetic.)

Operator Precedence:
The unary minus has a higher precedence than the binary subtraction. Therefore, - "1" is evaluated before the subtraction takes place.

Thus, the code logs 2 to the console.

This awesome interview question asked in Infosys, frontend interview? 

Answer is :  D) 2

1 Comments

Previous Post Next Post