Introduction
We will explore one of the basic fundamentals of JavaScript, that is object, and specifically discuss why everything in JavaScript is an object or indeed if it is?
Background
JavaScript makes an arbitrary distinction between values:
Primitive values and Objects.
Primitive values include boolean, numbers, strings, null and undefined.
While everything else in a JavaScript is said to be an object which means window, JSON, Math and even functions and arrays are Objects as well. More on functions and arrays later in this post.
Differences between Objects and Primitive Values
One of the main differences between an object and a primitive value is the way they are compared.
Objects are compared by reference.
var obj1= {};
var obj2 = {};
obj1===obj2;
obj1===obj1;
All primitives are compared by value.
var number1= 5;
var number2=5;
number1===number2;
Object properties are mutable, i.e., they can be changed. The properties of an object can be added, removed or changed.
var obj = { name: 'KSN'};
obj.name;
obj.name='NKN';
obj.name;
Primitive value type properties are immutable, i.e., they cannot be changed.
var stringVariable = 'KSN';
stringVariable.length;
stringVariable.length=1;
stringVariable.length;
Is Everything in JavaScript An Object?
As mentioned earlier, value types in JavaScript are categorized into primitive values and objects.
Objects include arrays, functions, built-in objects and user defined objects too. But interestingly primitives sometimes behave like objects too!
Let's look at arrays first.
var arr = ["KSN","NKN"];
console.log(arr[0]);
arr.length;
arr.push("Jiya");
Arrays are indeed special objects where the properties are indexed which gives us the capability to access them using index.
Let's look at functions.
function addNumbers(x,y){
return x+y;
}
var sumOfTwoNumbers = addNumbers(2,3);
addNumbers.protoype;
addNumbers.call(this,2,3);
So function indeed objects.
Now, sometimes primitive values also act like objects.
This can be best explained with string
value type in JavaScript.
var stringVariable ='KSN';
stringVariable.length;
stringVariable.substring(0,2);
So this is how it works.
When we access the length
property of stringVariable
, it is converted into an Object and the length
property is accessed. Once the property is accessed, it returns to being a primitive value string
.
And that is why almost everything in JavaScript is an object!