1

Why is it that in JavaScript I can perform operations such as multiplication and subtraction with strings that are digits e.g. "10" with numbers?

Does JavaScript do type inference?

Consider the example below, why is it in the last two statements I get 1010 and not 20 in either one?

var foo = "Hello, world!";
var bar = "10";



var x = foo * 10; // x is now bound to type number
console.log("type of x= " + typeof x + ", value of x= " +  x); // this will print number NaN, that makes sense..


var y = bar * 10; // y is now bound to type number
console.log("type of y= " + typeof y + ", value of y= " +  y); // this will print number 100

y = bar - 10; // y is now bound to type number
console.log("type of y= " + typeof y + ", value of y= " +  y); // this will print number 0 

y = bar + 10; // y is now bound to type string!!
console.log("type of y= " + typeof y + ", value of y= " +  y); // this will print number 1010

y = eval(bar + 10); // y is now bound to type number!!!! 
console.log("type of y= " + typeof y + ", value of y= " +  y); // this will print number 1010 

output from the log:

type of x= number, value of x= NaN
type of y= number, value of y= 100
type of y= number, value of y= 0
type of y= string, value of y= 1010
type of y= number, value of y= 1010
Andy G
  • 19,232
  • 5
  • 47
  • 69
BOWS
  • 404
  • 2
  • 4
  • 17
  • 3
    the plus sign is both for string concantenation and adding numbers, so when one of the values is a string, the other value is coherced into a string as well. You can't multiple or subtract a string, so when those operators are used, the values are coherced to numbers. – adeneo Jun 09 '14 at 19:09
  • 1
    Good Solution Found Here: http://stackoverflow.com/questions/7124884/why-does-1-2-3-4-1-23-4-in-javascript/7124918#7124918 – BOWS Jun 19 '16 at 16:52

1 Answers1

3

In the second example

var y = bar * 10

Javascript is assuming you want to perform a mathematical operation and coerces your original string into a number.

In the last two examples you are trying to add 10 (number) to bar. bar (your variable) is a string, so JavaScript does its best, assumes you want a string as a result, and creates a string by concatenating "10" (as a string) and doesn't coerce your original string to a number.

Rules for type coercion are complex. I'll try and find a link for you. But Douglas Crockford's "JavaScript: The Good Parts" is a good read.

EDIT

Try this, explains it all quite nicely.

http://united-coders.com/matthias-reuter/all-about-types-part-2/

cortexlock
  • 1,446
  • 2
  • 13
  • 26