0

I want to know , how javascript interpreter knows the datatype of a variable when execution . In case of Java and other languages , we use to declare the data type with but in javascript we simply declare it as "var".

var number1 = 2;
var number2 = 3;

var number3 = number1+number2;

console.log(number3);

Output is 5 . Why not 23?

Thanks.

Turing85
  • 18,217
  • 7
  • 33
  • 58
JavaUser
  • 25,542
  • 46
  • 113
  • 139

6 Answers6

1

Because neither is a string.

The type of a variable is associated with that variable's internal representation.

During source parsing variables are lexed according to the language grammar. No quotes, not a string, so it's a number. Since both are numbers, the result is a number.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
1

your variables are interpreted as a number because you did not make it a string using "".

var number1 = 2;
var number2 = 3;

var number1_ = "2";
var number2_ = "3";

var number3 = number1+number2;
var number3_ = number1_+number2_;

console.log(number3); // 5
console.log(number3_); // 23
messerbill
  • 5,499
  • 1
  • 27
  • 38
0

Because 2 and 3 are numbers. Declaring a variable with var doesn't mean "remove the type", or "set the type to a string", it just means that it can hold any type. You assigned a number to number1, and a number to number2. So adding these together the JS interpreter knows it's adding two numbers together.

sahbeewah
  • 2,690
  • 1
  • 12
  • 18
0

Because it's a number type:

typeof 4
--> "number"

typeof '4'
--> "string"
Mark Chackerian
  • 21,866
  • 6
  • 108
  • 99
test
  • 1
0

JavaScript variables are containers for storing data values.

when you assign a number to a container it's interpreter know it as number else if you assign a string it considered as string

var x = '2' ;
var y = '3'
console.log(typeof x) // string
console.log(typeof y) // string

console.log(x+y) // '23'

and now assign a number to each one :

var x = 2 ;
var y = 3
console.log(typeof x) // number
console.log(typeof y) // number

console.log(x+y) // 5
Moolerian
  • 534
  • 6
  • 18
0

I want to directly answer your question of how the javascript interpreter knows the datatype of a variable.

The thing you need to know about javascript unlike, lets say, java is that a variable in JS doesn't hold the type. In JS it's the value that holds the type. And the value's type cannot be changed. But it can be coerced.

So even though a variable's value is intrinsicly a number, like the number 5, a new string "5" can be created from it through implicit coercion without you explicitly changing the variable's type because the variable itself never held the type to begin with.

It's not that the variable changes to a string, but rather a new string value will be created and used for the variable depending on the context of the expression you are using it in.

Look up javascript coercion for more info.

haltersweb
  • 3,001
  • 2
  • 13
  • 14