daemonl

In case you were wondering...

JS102 - It's all the same thing

Objects, that is. Everything in javascript is an object... or a variable, a pointer, whatever you like to call it, the point is it's all the same.

var a = "A String";
var b = 46;
var c = function(){ alert("BOO!"); };
var d = new Date();
var e = {};
var f = [];

Notice we didn't have to say what any of them are. They are just variables/objects/pointers. And they can be changed to other types too:

console.log(a); // "A String";  
a = a + 1;  
console.log(a); // "A String1;  
a = 42;  
console.log(a); // 42;  
a = a + 1;  
console.log(a); // 43;

Now... something odd happened there, the + operator did two different things!

That's because if you add a string and something, both get treated as strings, and if you add two numbers... they are added.

var a = "1";  
console.log(a); // "1"  
a = a + 1;  
console.log(a); // "11"

Huh? Notice the difference between 1 and "1". Very different things - a number and a string. A string of 'numeric characters' isn't a number. But get ready for this:

var a = "1";  
console.log(a); // "1";  

console.log(a+1); // "11";  
console.log(a/1); // 1;  
console.log(a/2); // .5;  
console.log(a*1); // 1;  
console.log(a-1); // 0;

Javascript knows that if you are subtracting, dividing or multiplying, then both sides must be numbers, but not so much for +, because + is also used for strings.

In other languages this is solved by having a different operator (like . ) for strings, but - and this is the fun part with javascript - it is that way because it always has been and to change it now would cause untold horror.