0

New to Javascript and something that I came across was kind of interesting. I was shown this example:

"37" - 7 // "30"
"37" + 7 // "337"

This was an exercise to show how Javascript converts and handles strings and integers. What I don't understand is why these two statements are handled differently. The first statement will convert 37 to an integer and subtract 7, leaving 30 (if I change it to 6, it becomes 31). However, in the second statement, it treats it like a string and concatenates the second 7 onto the end of the string.

For testing purposes, I am writing this:

var number = "37" - 7 
console.log(number);

in a text, saving it as a .js file and executing it with Node.js.

If there is no easy way to explain this, I will just chalk this up to a bizarre behaviour that JS has. An over-complicated answer would be wasted on a newbie like me.

Thank you in advance.

2
  • 1
    You can't subtract from strings, so javascript treats the - sign as having numeric parameters. You can however add strings, so if you have a string on the left then javascript will convert the arg on the right to a string too. It's not strange behaviour, it's expected. Commented Jan 9, 2015 at 22:17
  • 1
    + is used both for addition and concatenation, whereas - is just minus. In your case you're concatenting strings with the +. Commented Jan 9, 2015 at 22:17

2 Answers 2

3

They are handled differently because + is overloaded. It has two functionalities:

  • addition
  • string concatenation

Those operations are defined on different data types (numbers and strings), so if it gets mixed types (not numbers), it has to decide which operation to perform. Someone decided that if at least one operand is a string, string concatenation should be performed.

The - operator however is only defined for numbers, so operands will always be converted to numbers.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah. I can't believe I overlooked that. It's been awhile since I messed around with a programming language that works with strings. I was used to the concat() function. Thank you for reminding me.
2

When you look at these two cases, the thing to remember is that addition has a different implication when you are working with strings.

When you do:

37 + 7 // 44

You are just adding two numbers... yet if you do

"37" + 7 // "337"

You are appending 7 to the string "37".

Since the subtraction symbol does not have a use with strings in JS, it assumes 37 as an int and does the subtraction which yields:

"37" - 7 // "30"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.