Objects in Javascript

·

2 min read

Object is the one of 6 primary types in javascript and most of the things in JS is built on top of Object. It can be constructed in two ways

  1. var obj = {
     a : 2
    }
    
  2. var obj = new Object();
    obj.key = value;
    

    Then to access the properties we need to use either . or []

    obj.a //2
    obj["a"] //2
    

Built in Objects

String , Number , Boolean etc. are sub types of Object, also called as Built in Objects. They are actually "built in Function" which can be used to construct new object of the specific sub type that this Function represent.

var objectStr = new String( "This is a string" );
typeof objectStr;      // "object"

var primitiveStr = new String( "This is a string" );
typeof primitiveStr;     // "string"

console.log(primitiveStr.length) // 16

Here we can see primitive value "This is a string" is not an "object" type , it is primitive string. But we can still access length. But why is that? Because Javascript will automatically coerces it to String object, which has the length property.

read only property

we can make a property read-only by setting writable property descriptor to true

var obj = {};

Object.defineProperty( obj , "a", {
    value: 2,
    writable: false, // not writable!
    configurable: true,
    enumerable: true
} );

obj .a = 3;

obj .a; // 2

Because writable is set to true, property reassignment will be silently ignore in non strict mode and throw an error in strict mode.

Arrays

Arrays are also objects, but they store data in a more structured way than normal objects.

var arr = [1, "name", 3]
arr.key = "value"
console.log(arr.length) // 3
console.log(arr.key) // "value"

Here you can see arrays can also have named properties but that does not add to the length of it.

var arr = [1, "name", 3]
arr["0"] = "value"
console.log(arr.length) // 3
console.log(arr) // [ 'value', 'name', 3 ]

But if numeric key ["0"] is used then it will work as a numeric index and end up modifying array contents.