Skip to content

Instantly share code, notes, and snippets.

View AkashRajvanshi's full-sized avatar
😎
DevOps

Akash Rajvanshi AkashRajvanshi

😎
DevOps
View GitHub Profile
//Example of Properties, keys & Values
let user = { // An object
name: 'akash', // 'name' is a key: 'akash' is a value
age: 22
};
const fullName = {
first: 'Akash',
last: 'Rajvanshi'
};
console.log(fullName.first) // Akash
// In this code, we create an object via an object literal, which starts with a curly brace and end with a curly brace {...}.
// Inside it, we have propety: {Key = first, last} and {value = Akash, Rajvanshi}
const user = {
firstName: 'Akash',
lastName: 'Rajvanshi',
fullname: function () { //method
return `${this.firstName} ${this.lastName}`
}
};
console.log(user.fullname()) //Akash Rajvanshi
console.log(user.firstName) //Akash
console.log(user.fullname()) // call method fullname
// Akash Rajvanshi
user.firstName = 'Abha' // Set property 'firstName'
console.log(user.firstName) // Abha
delete user.firstName
console.log(user.firstName) //undefined
console.log(Object.keys(user) // [ 'lastName', 'fullname' ]
// But if we set a property to 'undefined', the property still exits and the object still contains its key.
user.firstName = undefined
console.log(Object.keys(user)) // [ 'lastName', 'fullname', 'firstName' ]
Object.defineProperty(user, 'canBeDeleted', {
value: 123,
configurable: true
});
Object.defineProperty(user, 'cannotBeDeleted', {
value: 456,
configurable: false
});
console.log(delete user.cannotBeDeleted) // false
const fullName = {
first: 'Akash',
last: 'Rajvanshi',
get full() {
return `${this.first} ${this.last}`
}
};
console.log(fullName.full) // Akash Rajvanshi
const fullName = {
first: 'Akash',
last: 'Rajvanshi',
set full(name) {
const parts = name.split(' ')
this.first = parts[0]
this.last = parts[1]
}
};
let fullName = {
first: 'Akash',
last: 'Rajvanshi'
};
fullName = {...fullName, age: 22}
console.log(fullName) // { first: 'Akash', last: 'Rajvanshi', age: 22 }
// Extra Features
// 1. Changing content of an object