Sum of Two Numbers in JavaScript

Add two numbers. Coerce the strings or you glue 10 and 20 into 1020.

BeginnerBasic ProgramsExample 4 of 10
sum-of-two-numbers.js
1// Adding two numbers
2let num1 = 10;
3let num2 = 20;
4let sum = num1 + num2;
5
6console.log("Sum of", num1, "and", num2, "is:", sum);
7
8// Using template literal
9console.log(`Sum of ${num1} and ${num2} is: ${sum}`);

Output

Sum of 10 and 20 is: 30
Sum of 10 and 20 is: 30

What's going on

+ concatenates strings. Number("10") + Number("20") is 30. Forget Number and you get "1020".

parseInt("10px") is 10. Number("10px") is NaN. Pick on purpose.