We’ve already seen how values are assigned to variables. The equal to sign is an assignment operator.
var lucky_number = 7; var url = "http://www.webdevelopersnotes.com";
Operators work on one or more values, called operands to yield a single result. An expression is a combination of operands and operators.
Arithmetic operators work on one or more numeric values yielding a single result.
var a = 4 + 10;
In the expression above, the addition operator adds 4 and 10 to yield 14 and the assignment operator assigns this value to the variable a.
var b = 3; (variable b is assigned a value of 3) b = 10 + 5 + 3 + 6; (b now equals 24)
var c = 40 - 5; (c = 35)
var d = 100 * 4; (d = 400)
var e = 100 / 4; (e = 25)
Consider the following code
var a = 4; var b = 6; var c = 10; var d = 3; var e = a + b + c; (e = 20) var f = b - c + a; (f = 0) var g = b / d + b; (g = 8)
var a = 70 % 16; (a is now equal to 6, since the remainder left after dividing 70 by 16 is 6) var b = 64 % 8; (b equals 0)
var a = 5; a++; (a = 6) var b = 10; b--; (b = 9)
The function of the increment operator (and the decrement operator) can also be achieved by adding the digit 1 to the variable as:
a = a + 1; OR b = b - 1;
So why use a++ instead of a = a + 1?
Just like numbers, variables can contain the string data type. Any text has to be stored as strings. Here are a few examples:
var name = "Johnny Bravo"; var url_address = 'http://www.webdevelopersnotes.com/'; var music_piece = "Mozart's Symphony No. 40"; var page_number = "15";
The following will clear any doubts…
To concatenate two strings, you use the + string operator.
var first_name = "Johnny"; var last_name = "Bravo"; var full_name = first_name + last_name; Result: full_name = "JohnnyBravo"; (note, no space)
To introduce a space, we add a space character between the two variables.
full_name = first_name + " " + last_name; Now, full_name = "Johnny Bravo";
var page = "15"; var page2 = page + 1; var page3 = page + "2"; (note the quotes) Result: page2 = "151"; page3 = "152";
The reason is that the variable page stores digits as string data, the + sign, in this case behaves as the string concatenation operator and not as the arithmetic addition operator.
Twitter has been used from space. "Hello Twitterverse! We r now LIVE tweeting from the International Space Station -- the 1st live tweet from Space! :) More soon, send your ?s" was the first tweet sent by astronaut TJ Creamer (@Astro_TJ) on January 22, 2010. [more...]