tags:

views:

30

answers:

1

When I see a field:value pair as

"name":"foo" and "name":foo

what is the difference between the two? Are both the values supposed to be strings?

And what about

"age":3 and "age":"3"

Is the first one an integer? I am confused.

Thanks.

+4  A: 

Strings vs. variables

The following assigns the string value "foo" to a property:

item = { "name" : "foo" } // item.name = "foo"

The following assigns the value of the foo variable to a property. If the foo variable doesn't exist, you'll receive an error message:

item = { "name" : foo } // foo doesn't exist yet, will result in error

foo = "my value" // foo is defined here
item = { "name" : foo } // item.name = "my value"

Numbers vs. strings

The following assigns a Number value to a property:

child = { "age" : 3 } // child.age = 3

Numbers can be used in all mathematical operations. For example, child.age * 3 will result in 9 and child.age + 4 will result in 7.

The following assigns a string value to a property:

child = { "age" : "3" } // child.age = "3"

Strings cannot be used in all calculations. For example, child.age * 3 will result in 9, but child.age + 4 will result in 34, due to string concatenation.

You should only use strings if the data is textual data. If the data is numerical, store it as a number (without the quotes).

Niels van der Rest
One thing to note unless it has been changed, numbers started with a ZERO has to be surrounded in quotes. With zipcodes, I was forced to throw my values in the collection as "08010." If i tried doing so w/o the quotes, the leading zero gets cut off.
luckytaxi
@luckytaxi: Technically, zip codes aren't numbers, but codes ;) But you do point out an important aspect of number in JavaScript: numbers starting with a zero are treated as **octal numbers**. So if you enter 012, you'll end up with 10 instead of the 'expected' 12.
Niels van der Rest