Matt Matt - 23 days ago 5x
Javascript Question

How is almost everything in Javascript an object?

I read this a lot in many JavaScript introductions. I just don't understand it. I always think of objects as something with methods and properties.
Arrays I understand, since it has key value pair.
How about "Strings" or "Numbers" or "functions" ?
These things above listed seem to be like functions to me. This means you input something, you get something out. You don't really get the access properties or anything. There's no dot notation used in arrays or this list of "objects".

Does anyone code some examples of each of these with dot notations which its methods and properties are being accessed? I suspect that definition of object is probably limited since I did start learning about JavaScript...


That's right, in javascript, almost everything is an object. But these objects are bit different from what we see in Java, C++ or other conventional languages. An object in JS is simply a hashmap with key-value pairs. A key is always a string, and a value can be anything including strings, integers, booleans, functions, other objects etc. So I can create a new object like this:

var obj = {}; // this is not the only way to create an object in JS

and add new key-value pairs into it:

obj['message'] = 'Hello'; // you can always attach new properties to an object externally


obj.message = 'Hello';

Similarly, if I want to add a new function to this object:

obj['showMessage'] = function(){


obj.showMessage = function() {

Now, whenever I call this function, it will show a pop-up with message:


Arrays are simply those objects which are capable of containing lists of values:

var arr = [32, 33, 34, 35]; // one way of creating arrays in JS

Although you can always use any object to store values, but arrays allow you to store them without associating a key with each of them. So you can access an item using it's index:

alert(arr[1]); // this would show 33

An array object, just like any other object in JS, has it's properties, such as:

alert(arr.length); // this would show 4

For in-depth detail, I would highly recommend John Resig's Pro Javascript Techniques.