As I was scrolling through Twitter just now I noticed a tweet where someone was commenting on the type of question asked in interviews and comparing against the daily reality of the position. The point he was making I totally agree with but I was surprised to see a number of people in the comments seeming to suggest the question wasn't a valid one to be asked in any coding interview.
I disagree, as the question tests the interviewee’s problem solving abilities, knowledge of the language, and how they handle pressure. Important characteristics to assess when considering hiring someone.
The question was “What will be the value of:”
var a = 10, b= 20; console.log(-+a++-+-+b--);
At first glance a reaction like “WTF…” is natural, such obfuscation should never be present in real code. But nothing else about interviews is a realistic situation why should the code questions be? This isn’t actually a hard problem to solve. Take a moment and think about how this will execute and you should be able to figure it out.
First off the values of a and b will be retrieved.
Then the postfix operators ++ and -- have higher precedence so they will be pulled out of the expression and applied to the variables BUT postfix operators are applied AFTER the values are returned to the expression so now a has the value 11 and b the value 19. But their original values will be used in evaluating the expression.
What we have at this point is:
This might look like multiple addition and subtraction operators, but these apply on left and right operands. Which are mostly missing, so what will happen? Well there are two operators Unary Plus and Unary Negation. These operate right to left, the opposite of addition and subtraction, and they only require one operand, on their right. Unary plus converts its operand to a number if it isn't already, unary negation does the same but then negates it. All very complex sounding, but its not really. I’m sure you understand what this means -10 how about -x well that means take the value of x, make it a number and negate it.
Starting with variable a with value 10. First it has the unary plus applied +(10) and becomes, eh 10, so nothing actually changed. Now the unary negation is applied -(10) and it becomes -10.
So our equation is now.
Now we do the same process working from the second variable b, with value 20. Working right to left - unary plus, then unary negation then unary plus leaves us with -20. Remember unary plus doesn't change the operand if its already a number so it isn't changed to positive in that last step.
Now we have two values, with a subtraction operator between them, (-10)-(-20)
A bit of maths now, subtracting a negative number from a negative number. Gives us the answer: 10.
If you are ever thrown a question like this remember its probably not as hard as it looks and you can probably solve it if you take a moment to break down the expression and consider how each operator behaves.