JAVASCRIPT OBJECTS
Prepared By : Srushti
Gajjar
1
Overview of JavaScript Objects
What are JavaScript Objects?
Collections of properties (key–value pairs) are used to model
complex data and real-world entities.
Creation methods:
Literal syntax: { name: "Martin", class: "12th", … }
Constructor form: e.g., new Object()
2
Object Properties
Definition: A property ties a key to a value within an object.
Instance Property (Example):
constructor: gives reference to the function that created the
object instance.
3
Object Methods — Static
MEthods
Method
Object.assign()
Description
Copy properties from one or more source objects to a target object
Object.create() Create a new object with the specified prototype
Object.defineProperty() Define or modify a property with a descriptor
Object.defineProperties() Define or modify multiple properties with descriptors
Object.entries() Return an array of key–value pairs
Object.freeze() Freeze object so its properties cannot be modified
Prevent new properties from being added; existing properties remain
Object.seal()
editable
Prevent new properties from being added (but can modify/delete
Object.preventExtensions()
existing)
Object.fromEntries() Convert a list of key–value pairs into an object
Object.getOwnPropertyDescriptor() Get descriptor of a specific property
Object.getOwnPropertyNames() Get all property names of the object
Object.getOwnPropertySymbols() Get all symbol properties of the object
Object.getPrototypeOf() Get the prototype of the object
Object.hasOwn() Check if object has a given property directly (not inherited)
Object.isExtensible() Check if new properties can be added
Object.isFrozen() Check if object is frozen
Object.isSealed() Check if object is sealed
Object.is() Compare two values for strict equality (handles edge
4 cases like NaN)
Object.keys() Get array of object’s property keys
Object.values() Get array of object’s property values
Object Methods — Static
5
Object Methods — Instance
Methods
If the
method.
method is called on an instance of a date object, then it is called an instance
Method Description
Define a function that will be called when a property is
obj.__defineGetter__()
accessed
obj.hasOwnProperty() Check if property exists directly on the object
obj.isPrototypeOf() Check if object exists in another object’s prototype chain
obj.propertyIsEnumerabl
Check if property is enumerable and an own property
e()
6
Object Methods — Instance
Methods
7
Object references and copying
JavaScript objects (and arrays, functions) are stored and
passed by reference. That means when you assign one
object to another variable, you get a reference to the same
underlying object — not a separate copy. To make a copy,
you can do a shallow copy (only top-level fields copied) or a
deep copy (nested structures duplicated). Which method to
use depends on how deep the structure is and what types it
contains.
8
Shallow copy (copies only first-level
properties)
A shallow copy creates a new object, but only copies
the first level of properties.
If those properties themselves are objects (arrays, nested
objects), their references are copied — not the actual
values.
So:
Top-level properties → duplicated (independent).
Nested objects/arrays → still shared between original
and copy.
Common ways: Object.assign({}, obj) and spread { ...obj }. Both
create a new object whose own (enumerable) properties are
copied. Nested objects/arrays stay shared (still referenced).
9
Shallow copy (copies only first-level
properties)
10
Deep Copy
A deep copy means creating a completely
independent clone of an object — including all
nested objects and arrays.
Top-level properties → copied
Nested objects/arrays → also copied (not just
referenced)
Any change in the copy will NOT affect the original
at any level.
This is the opposite of shallow copy, where nested
objects are still shared.
11
Deep Copy
12
What is this?
Definition: The this keyword in JavaScript refers to the object
that "owns" or invokes the current execution context. Its value
is determined dynamically, based on how a function is called.
13
this in Object Methods
In object methods, this refers to the object itself—allowing
access to its properties and behavior.
14
this in Global or Function
Context
Global Context: this refers to the global object
(window in
browsers, global in Node), unless in strict mode where it
becomes undefined.
15
Explicit Binding with
call/apply/bind
Override default this using:
call(thisArg, ...args)
apply(thisArg, argsArray)
bind(thisArg, ...args) (returns a new, bound function)
16
call(thisArg, ...args)
What it does: Immediately calls the function with this set to
thisArg. Accepts arguments as a comma-separated list.
Use when: You want to invoke a function right now with a
specific this.
Notes
If thisArg is null or undefined, non-strict mode will coerce it to the global
object (window in browsers); strict mode will keep this as null/undefined.
call does not create a new function — it executes immediately.
17
apply(thisArg, argsArray)
What it does: Like call, but accepts arguments as an array
(or array-like).
Use when: You have arguments in an array or array-like
structure (e.g. arguments) and want to pass them to a
function.
18
bind(thisArg, ...args)
What it does: Returns a new function with this permanently
bound to thisArg and (optionally) preset leading arguments
(partial application). It does not call the function — it gives you
a bound function to call later.
Use when: You need a function callback with a specific this
(e.g. event handlers, timers), or you want to create partially
applied functions.
19
this in Arrow Functions
No own this
Unlike normal functions, arrow functions do not bind their own this.
Instead, this is lexically inherited — meaning it takes the value of
this from the scope where the arrow function was defined.
Why is this important?
In normal functions → this is dynamic (depends on how the function
is called).
In arrow functions → this is static (captured from outer scope at the
time of creation).
20
this in Arrow Functions
•greet is an arrow function.
•Arrow functions don’t have their own this.
•Here, this is taken from the surrounding scope (the global scope, not person).
•In global scope, this.age is undefined → that’s why output is undefined.
21
Arrow function inside a normal
function
• Here arrow function greet is created inside a constructor function.
• Its this is captured from the surrounding function (Person), which refers to the
new object created with new. 22
• So arrow function works correctly here.
Notes:
• Arrow functions do not have their own this.
• this is lexically inherited from the surrounding scope.
• Using arrow functions as object methods often gives undefined.
• But arrow functions are useful inside constructors or callbacks where you want
to preserve the outer this.
• Commonly used in event listeners, promises, or setTimeout to avoid losing
this.
23
The Object Constructor Pattern
• Definition: Constructor functions are special functions used with new to
initialize new objects.
• Purpose: Allow creation of multiple object instances with similar
properties/methods
24
Adding Properties to Objects
const Dept = {
subject: "programming",
language: "JavaScript",
};
• To an object:
• Dot operator:
Dept.subject = "JavaScript";
• Bracket notation:
Dept["subject"] = "JavaScript";
• To a constructor: Define properties inside the constructor function.
function GFG(a, b, c) {
this.A = a;
this.B = b;
this.C = c;
this.G = "GEEK";
}
25
Note: We cannot add a property to an existing constructor like adding a property to an object (see
previous point), for adding a property we need to declare under the constructor.
Adding a Method to an Object
To an object instance:
Dept.n = function() {
return this.A + this.B;
};
Inside a constructor:
function Dept(a, b, c) {
this.A = a;
this.B = b;
this.C = c;
this.n = function() {
return this.A + this.B;
};
26
}
Purpose: Allows instances to have behaviors (methods) related to their properties
Ways to Instantiate Objects
Using new Object() syntax:
const obj1 = new Object(); // no initial properties
const obj2 = new Object("java", "JavaScript", "C#");
Using object literal ({}):
const obj3 = {};
These demonstrate alternative ways to create objects in JavaScript, aside
from constructors
27
What Is a Constructor Function?
Constructor functions technically are
regular functions. There are two
conventions, though:
1. They are named with a capital letter first.
2. They should be executed only with the "new"
operator.
When a function is executed with new, it
does the following steps:
1. A new empty object is created and assigned to
this.
2. The function body executes. Usually, it modifies
this, adds new properties to it. 28
3. The value of this is returned.
The new Operator in JavaScript
The new keyword (also called the new operator) is used to
create a new object instance from a constructor function or class.
What Happens Internally When You Use new?
let obj = new ConstructorFunction(args);
JavaScript does these steps under the hood:
1. Creates a new empty object {}.
2. Links the object’s internal [[Prototype]] to the constructor’s
prototype.
3. Sets this inside the constructor function to refer to the new object.
4. Executes the constructor function code.
5. Returns the object (unless the constructor explicitly returns
29
another object).
The new Operator in JavaScript
• Each new Person() call creates a different object with its own
properties.
30
new with Methods
• You can also add methods inside a constructor:
31
What If You Forget new?
• If you call a constructor without new, this becomes
undefined (in strict mode) or refers to the global object
(window in browsers).
• To prevent mistakes, you can enforce new:
32
new with Built-in Constructors
• The new operator also works with built-in constructors
like:
1. let obj = new Object(); // {}
2. let arr = new Array(1, 2, 3); // [1, 2, 3]
3. let date = new Date(); // current date
33
Object to Primitive Conversion & Methods of
Primitives
What Are Primitives?
• JavaScript primitives:
• string, number, bigint, boolean, symbol, null,
undefined
They are not objects, but JS allows methods on them.
let str = "hello";
console.log(str.toUpperCase()); // HELLO
34
Why Conversion Happens?
• JavaScript sometimes needs to convert objects to
primitives:
1. When using operators (+, -, *, etc.)
2. When comparing objects with primitives
3. When printing objects (alert, console.log)
35
Conversion Rules
• JavaScript uses hints when converting:
1. "string" → for string contexts (alert(obj))
2. "number" → for math (+, -, comparisons)
3. "default" → rare, e.g., ==
36
Custom Conversion with toString / valueOf
• Objects can define how they convert:
37
Symbol.toPrimitive - Modern way
to customize conversion:
38
Methods of Primitives
• Even though primitives are not objects:
• JavaScript wraps them in temporary “object wrappers” (String,
Number, Boolean).
• This allows calling methods like:
• "abc".toUpperCase()
• (123.456).toFixed(2)
39
Iterables in JavaScript
1. What is an Iterable?
An iterable is any object in JavaScript that can be iterated
(looped) over using:
for...of loop
The spread operator (...)
Some built-in methods (like Array.from())
For an object to be iterable, it must implement the special
method:
obj[Symbol.iterator]()
40
Iterator vs Iterable
Iterable: The object that can be looped over.Iterator: The
object returned by the Symbol.iterator method, which has a
next() method.
The next() method returns an object like:
{ value: ..., done: ... }
value: The next value in the sequence.
done: true when iteration is finished.
41
Built-in Iterables in JavaScript
Strings
Arrays
Maps
Sets
Some DOM collections (NodeList, HTMLCollection, etc.)
42
Map Example • A Map stores key–value pairs and
remembers insertion order.
• Maps are iterable, so you can loop over
them using for...of.
43
Set Example
• A Set stores unique values only (no duplicates). It’s
also iterable.
44
Custom Iterable Example
• You can create your own
iterable by defining
Symbol.iterator.
• Example: A custom range
iterable
Spread Operator
with Iterables
let str = "ABC";
console.log([...str]); // ['A',
'B', 'C']
45
JSON Methods in JavaScript
What is JSON?
JSON = JavaScript Object Notation
A text format for storing and exchanging data.
Syntax is similar to JavaScript objects, but JSON is always a
string when stored/transmitted.
46
JSON Methods in JavaScript
JavaScript provides two core methods:
1. JSON.stringify(obj) : Converts a JavaScript object → JSON
string.
47
JSON Methods in JavaScript
JavaScript provides two core methods:
2. JSON.parse(str) : Converts a JSON string → JavaScript object.
48
The toJSON Method
Objects can define a custom
toJSON() method.
When JSON.stringify() is called,
it checks if the object has a
toJSON method.
If yes, it uses the return value
of toJSON() instead of the
object itself.
49
Use Cases
JSON.stringify() → Save object data in localStorage, send
over
API.JSON.parse() → Convert API response (JSON string)
into JavaScript object.
toJSON() → Control how objects are serialized (e.g.,
remove sensitive info, format data).
50
References
https://www.geeksforgeeks.org/javascript/javascript-obje
ct-constructors
/
https://developer.mozilla.org/en-US/docs/Web/JavaScript
51
Thank You
52