KandZ – Tuts

We like to help…!

JavaScript 8 🧬 objects

a - creating objects
objects are a fundamental data structure used to store collections of key-value pairs.
Objects can represent real-world entities or abstract concepts with properties (keys) and methods (functions).
Almost all object are instances of Object.
A Typical Object inherits properties from Object.prototype
Creating Objects: 1. Object literal syntax → const const person = {}
2. Using Object Constructor → const person = new Object();
3. Using Object create Method → const person = Object.create(prototype);
4. Using Class syntax (ES6+) → class Person {}
const person = new Person('Alice', 30);

b - access, add, modify and delete object properties
You can access object properties by using dot or bracket notation
console.log(person.name); → Dot notation
console.log(person['age']); → Bracket notation
You can modify existing properties or add new ones
person.age = 31; → Modify existing property
person.city = 'New York'; → Add a new property
You can delete properties from an object using the delete operator
delete person.isStudent; → removes a property

c - check for property existence and property iteration
To check if an object has a specific property, you can use the in operator or hasOwnProperty
console.log('name' in person); → exists, returns true
console.log(person.hasOwnProperty('age')); → exists, returns true
You can iterate over the properties of an object using for...in loop
for (let key in person) { } → property iteration
person is the object
key will take on each property name of the person object in turn

d - Object.keys entries and more methods

Object.keys() and Object.methods() are built-in JavaScript methods.
keys() returns an array of the object's property names, keys
let keys = Object.keys(person); → returns ['name', 'age', 'greet', 'city']
entries() returns both keys and values
let entries = Object.entries(person); → returns [["name","Alice"], ["age",31], ["greet",null], ["city","New York"]]
entries.forEach(([key, value]) = > { } → iterates through the returned entries
and some more: toString(), toLocaleString(locales[, options]), valueOf(), assign(target, ...sources)
isPrototypeOf(object), propertyIsEnumerable(prop), values(object),
create(o, propertiesObject), defineProperty(obj, prop, descriptor)
defineProperties(obj, props), getOwnPropertyNames(obj), getOwnPropertySymbols(obj), freeze(obj), seal(obj)

Leave a Reply