JavaScript objects
change url
JavaScript objects
Objects are collections of key-value pairs where keys are strings (or Symbols) and values can be any data type. They're one of JavaScript's two fundamental data structures (along with arrays)
including arrays, functions, dates, regex, etc is an object.
Everything except primitives is an object (Reference types = Object types)
Every reference type has Object.prototype in its prototype chain. All Reference Types Inherit from Object All reference types inherit from Object.prototype. Prototype chain: Instance → Constructor.prototype → Object.prototype → null
typeof is unreliable - use specific checks (Array.isArray(), instanceof)
null is NOT an object despite typeof
Prototype chain - objects inherit from prototypes
Functions and arrays ARE objects with special behaviors
Property descriptors control property behavior
Shallow vs deep copying matters for nested structures
Key Corner Cases:
null is not an object despite
typeof null === "object"- this is a known JavaScript bug kept for backward compatibilityArrays return "object" - use
Array.isArray()to checkFunctions return "function" - but they're still objects with properties
Objects in javascript can be created using 4 different approaches:
// Object literal
const obj = { a: 1 };
// Constructor function
function Person(name) { this.name = name; }
const p = new Person('John');
// Object.create method
const proto = { greet() { return 'hi'; } };
const obj = Object.create(proto);
// Class syntax (ES6)
class Person {
constructor(name) { this.name = name; }
}Every property has hidden attributes (enumerable, writable, configurable). Object.defineProperty, Object.getOwnPropertyDescriptor
Every object has an internal [[Prototype]] (accessible via proto or Object.getPrototypeOf()):
JavaScript classes are prototype-based constructors with guardrails and better syntax. JavaScript uses prototype-based OOP (not class-based like Java/C++)
Arrays are objects with numeric string keys and a special length property:
Functions are callable objects
types of this?
Array - typeof
Object - In object keys are strings or symbols only (numbers are converted to strings)
Function - typeof function
Object
Object.hasOwn()
Object.hasOwnProperty - checks only particular object value
Object.assign - shallow copying (default cloning), merging. Oн выполняет только поверхностное слияние. Вложенные объекты не сравниваются, а просто заменяются. (spread operator do the same, Всё, что появляется с правой стороны - будет иметь приоритет при слиянии)
structuredClone() - deep copying (can affect performance, since if huge nested object - a lot of memory used)
Object.freeze
Object.seal(obj); // can modify existing, but not add/delete
const obj = {
name: 'John',
greet() { return this.name; },
arrow: () => this.name // ⚠️ lexical this
};
obj.greet() // 'John'
obj.arrow() // undefined (or global in non-strict)
const fn = obj.greet;
fn() // undefined ⚠️ lost context
// Solutions
fn.call(obj) // 'John'
fn.bind(obj)() // 'John'Getters & Setters
const obj = {
_value: 0,
get value() { return this._value; },
set value(v) {
if (v < 0) throw Error('negative');
this._value = v;
}
};
obj.value = 10; // uses setter
obj.value // 10 (uses getter)typeof [] // "object" ✓ truthful (it IS an object)
typeof function // "function" ⚠️ special case (but still object)
typeof null // "object" ⚠️ bug (NOT an object)typeof "function" is a special case for historical reasons, but functions ARE objects:
function fn() {}
fn instanceof Object // true
fn.customProp = 'x'; // works because it's an objectBuilt-in Reference Types
Array, Function, Date, RegExp, Error, Map, Set, WeakMap, WeakSet, Promise, Proxy, etc.
Auto-boxing: JS temporarily wraps primitives in objects:
const str = "hello";
str instanceof Object // false
typeof str // "string"
// But they have "wrapper objects" for methods
str.toUpperCase() // works via String.prototype temporarily
"hello".toUpperCase()
// Under hood: new String("hello").toUpperCase()