Immutables¶
First, a quick word about variables. A value is an indentifier that holds a value. In JavaScript every value has a type, but variables are not typed. In other words, any variable can hold any value. Most dynamic language (such as Perl, Python and Ruby) are like this.
Always declare variables with a var statement, because sometimes a missing var can cause a hard-to-find bug. Experiments at the command line are the only exception to this rule.
We can change an array or a ‘dictionary’. Immutable values are values that can’t be changed. We can’t change, for example, the third character in a string.
Strings¶
Strings literals are delimited by single or double quote marks, with special characters escaped. There’s no difference between the two forms (except in single quote you don’t have to escape double quote, and vice versa.) Generally, I prefer the single quote form as it’s less busy on the eye and slightly easier to type.
js> s = 'Hello world.'
Hello world.
We can add two strings together to produce a third string.
js> r = "I'm me. "
I'm me.
js> r + s
I'm me. Hello world.
typeof¶
There’s a built-in operator called ‘typeof’ that returns a string that, sort-of, gives the type of a value.
js> typeof(s)
string
Because typeof is an operator (just as ‘+’ is an operator) the parentheses are not needed, and many JavaScript programmers omit them.
js> typeof s
string
Here we see that typeof produces (returns) a string.
js> typeof typeof s
string
Numbers¶
JavaScript numbers are platform and processor independent. It uses IEE 754 to represent both integers and floats.
js> i = 42
42
js> typeof i
number
Booleans¶
JavaScript has keywords ‘true’ and ‘false’ whose values are always true and false respectively.
js> t = true
true
js> typeof b
boolean
Logical comparisions also produce Booleans.
js> f = (1 > 2)
false
js> typeof f
boolean
undefined and null¶
JavaScript has two values that represent None. Later, we’ll see why, and which to use when. For now we’ll simply note that they are different, because their types are different.
js> typeof undefined
undefined
js> typeof null
object
Gotchas¶
js> s = 'Hello world.'
Hello world.
js> s.lang = 'en'
en
js> s.lang === undefined
true