+ 4
Why is it that in JavaScript console.log("5"-1) output 4 and console.log("5"+1) output 51 , I don't just get it
I don't just get it yet
5 odpowiedzi
+ 5
That's because the - operator has no behaviour on strings so it just parses an int from the string and subtracts it.
A trick you can use to add strings is:
console.log("5" - -1)
+ 4
My guess would be the first one isnt a valid string operation, so "5" is coerced into a number rather than an error being thrown (try this with something that can't be a number, like "foo"-1)
In the second case, string concatenation is performed because a string + something is treated like string.
I wouldn't worry too much, JS has a lots of strange behavior.
Edit: just noticed this is the same question as yours from 12 minutes earlier?
+ 3
When you do the “5”-1, the “5” is converted into a 5, and 5-1 is 4.
But when you do the “5”+1, the 1 in converted into a “1”, and you get “5”+”1”. If you join the text “5” and the text “1” together, you get 51.
If you try to use * (the times operator) on anything between quotation marks (“”), then it will return null.
Joining two strings (pieces of text) together is called String Concatenation.
Hope that helps!
+ 2
in JavaScript the + operator has two meanings. add and concatenate. if it sees only numbers it adds. if it sees strings it concatenates.
- * and / only have one meaning. subtract multiply or divide. so if the expression is "5"+4 the answer will be "54" due to the "5" string. but "5"*4 is 20 because thats all you can do with * so "5" gets coverted to 5 automatically.
this is called automatic type conversion. JavaScript will automatically convert values in expressions into numbers or boolean as needed to make sense of the expression
remember we dont declare variables to be int or char or whatever ahead of time in JavaScript. we just use them and they can change from one data type to another as needed to make sense of an expression throughout the script
+ 1
Anything inside double quotes is a string. So "5" + 1 would be the same as "five" + 1. However, 5 + 1 would be 6.
Examples:
5 + 1 + '"6" = 66
5 + 1 + 6 = 12
"5" + "1" + "6" = 516
"Hello" + " World!" = Hello World!
"Hello" + 6 = Hello6