Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Everything is an object?

Tags:

javascript

At one popular blog, the author asked his audience what was their “Ah ha!” moment for JavaScript and most of the people said that it was realizing that everything in JavaScript is an object. But being new to JS and programming in general I don't quite get what that means. It doesn't seam like it's related to actual JS Object - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object

Or it does?

If it doesn't could you please explain what do they mean by "everything in JavaScript is an object".

Or it's all about OO Programming in general and reading something on this subject will help to understand it? Can you recommend what to read on this topic?

like image 596
gskalinskii Avatar asked Feb 07 '26 03:02

gskalinskii


1 Answers

What they mean, most likely, is that any data that can be assigned to a variable has properties (and therefore methods) that can be accessed in an object like fashion.

// strings
"asdf".length;              // 4
"asdf".replace('f', 'zxc'); // "azxc"

// numbers
(10).toFixed(2);            // "10.00"

// booleans
true.someProp;              // undefined (point is it doesn't crash)

They even have prototypes they inherit from.

"omg".constructor;          // function String() { [native code] }
String.prototype.snazzify = function() {
  return "*!*!*" + this + "*!*!*";
};

"omg".snazzify();           // "*!*!*omg*!*!*"

However, these are primitives, and while they behave object like in a lot of ways, they are different from other "real" JS objects in a few ways. The biggest of which is that they are immutable.

var s = "qwerty";
s.foo;              // undefined, but does not crash
s.foo = 'some val'; // try to add a property to the string
s.foo;              // still undefined, you cannot modify a primitive

Do note though that functions are real mutable objects.

var fn = function(){};
fn.foo;              // undefined
fn.foo = 'some val'; // try to add a property to the function
fn.foo;              // "some val"

So while it's not technically true that "everything in JS is an object", under most circumstances you can treat them mostly like objects in that they have properties and methods, and can potentially be extended. Just be sure you understand the caveats.

like image 180
Alex Wayne Avatar answered Feb 12 '26 05:02

Alex Wayne