Problem Statement
What will be the output of: '5' + 3 - 2
Explanation
The answer is 51. Let me break it down step by step.
First step: The string 5 plus the number 3. The plus operator sees a string, so it performs string concatenation. This gives us the string 53.
Second step: The string 53 minus the number 2. The minus operator only works with numbers, so it converts the string 53 to number 53, then subtracts 2. This gives us 51.
Key rules:
The plus operator with any string performs concatenation.
All other operators like minus, multiply, and divide perform numeric conversion.
Think of plus as the special operator:
Plus adapts. If it sees a string, it becomes a string operator.
Minus, multiply, and divide are strict. They only work with numbers and force conversion.
Code Solution
SolutionRead Only
// Step by step evaluation
console.log('5' + 3 - 2);
// Step 1: '5' + 3 = '53' (string concatenation)
// Step 2: '53' - 2 = 51 (numeric conversion then subtraction)
// Result: 51
// More examples
console.log('5' + 3); // '53' (string)
console.log('5' - 3); // 2 (number)
console.log('5' * 3); // 15 (number)
console.log('5' / 2); // 2.5 (number)
// Order matters
console.log(3 + 5 + '7'); // '87' (8 + '7')
console.log('7' + 3 + 5); // '735' (all strings)
// Confusing examples
console.log('10' - 5 + 3); // 8
console.log('10' + 5 - 3); // 102 (string '105' - 3)
console.log(5 + 3 + '2'); // '82'
console.log('2' + 3 + 5); // '235'
// Force numeric conversion
console.log(+'5' + 3); // 8 (unary plus converts to number)
console.log(Number('5') + 3); // 8 (explicit conversion)