Data Structures and Methods

Objects and methods


/** Get all keys in an array*/
Object.keys({a: 1, b: 2, c: 3}) // [a,b,c]

// Returns an array with all keys from object.

/** Get all values in an array*/
Object.values({a: 1, b: 2, c: 3}) // [1,2,3]

// Returns an array with all values from object.

/** Add properties to object */
const obj = {}
Object.defineProperties(obj, {
  propKey1: {
    value: "value 1",
    writable: false,
  },
  propKey2: {}
})

// Returns the object that was passed to the method.

/** Add/modify 1 property */
Object.defineProperty(obj, 'propKey1', { value: "some new value" })

// Returns the object that was passed to the method.

Objects and methods

/** Merge 2 objects*/
Object.assign(obj1, obj2)
// if matching keys, second arg's keys (obj2) will be added
const obj1 = {a: 1, b: 2, c: 3}
const obj2 = {c: 101, d: 205, e: 309}

const mergedObject = Object.assign(obj1, obj2)
// {a: 1, b: 2, c: 101, d: 205, e: 309}

/** Create new object with a prototype*/
Object.create()

const student = {
  name: "First Student",
  printIntroduction: function () {
    console.log(`My name is ${this.name} and
                 I'm currently studying ${this.subject}`);
  },
};

const student1 = { name: "Second student" };
studnet1.subject = "Maths"
student.printIntroduction()

Objects and methods

Object.preventExtensions(obj)
/**
prevents adding new properties,
prevents the object's prototype from being re-assigned
Returns the object that was passed to the method.
*/

Object.seal(obj)
/**
prevents extension, new properties cannot be added, 
existing properties cannot be removed,
Values of existing properties can still be changed,
prototype cannot be re-assigned,
Returns the object that was passed to the method.
*/

Object.freeze(obj)
/**
prevents extension, new properties cannot be added, 
existing properties cannot be removed,
Values of existing properties CAN NOT be changed,
prototype cannot be re-assigned,
Returns the object that was passed to the method.
*/

Object.isExtensible()
Object.isSealed()
Object.isFrozen()
/**
Returns true or false.
*/

Objects and methods

/** Convert Object to Map */
Object.entries()

// Ex:
const object1 = {
  a: 'somestring',
  b: 42,
};
console.log(Object.entries(object1)) // [[a, 'somestring'], [b, 42]]

for (const [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}

/** Convert Map to Object */
Object.fromEntries()

// Ex:
const entries = new Map([
  ['foo', 'bar'],
  ['baz', 42],
]);

const obj = Object.fromEntries(entries);

console.log(obj); // { foo: "bar", baz: 42 }

Objects and methods


Object.getPrototypeOf()
// returns the prototype of the specified object

Object.setPrototypeOf()
// sets the prototype of the specified object

Object.hasOwn(objName, propKey) // OR 
Object.hasOwnProperty(objName, propKey)
/**
returns true if the specified object has the indicated property 
as its own property. 
If the property is inherited, or does not exist, the method returns false
*/

Objects and methods


Object.is() 
console.log(Object.is(-0, 0)); // false

const obj = {};
console.log(Object.is(obj, {})); // false

/**
determines whether two values are the same value.
Two values are the same if one of the following holds:

both undefined, both null, both true or both false
both strings of the same length with the same characters in the same order
both the same object (meaning both values reference the same object in memory)

Object.is() is not equivalent to the == operator.
The == operator applies various coercions
but Object.is() doesn't coerce either value.
Object.is() is also not equivalent to the === operator.
The only difference between Object.is() 
and === is in their treatment of signed zeros and NaN values.
The === operator (and the == operator) treats the number
values -0 and +0 as equal, but treats NaN as not equal to each other.

Map and methods

// Create a new Map
const userDataMap = new Map();

// Adding key-value pairs to the map
userDataMap.set('John', { age: 30, city: 'New York' });
userDataMap.set('Alice', { age: 25, city: 'Los Angeles' });

// Checking if a specific key exists in the map
console.log(userDataMap.has('John')); // Output: true

// Getting the value associated with a specific key
console.log(userDataMap.get('Alice')); 
// Output: { age: 25, city: 'Los Angeles' }

Map and methods

// Getting an iterator for the entries (key-value pairs) in the map
const entryIterator = userDataMap.entries();

// Getting an iterator for the keys in the map
const keyIterator = userDataMap.keys();

// Getting an iterator for the values in the map
const valueIterator = userDataMap.values();

// Removing all key-value pairs from the map
userDataMap.clear();

// Removing a specific key-value pair from the map
userDataMap.set('John', { age: 30, city: 'New York' });
userDataMap.delete('John');

Map and methods

// Iterating over each key-value pair in 
// the map and performing an operation
userDataMap.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});

// Example usage of the custom 'groupBy' method
const groupedByAge = userDataMap.groupBy((value, key) => {
  return value.age;
});

Sets and methods

// Create a new Set
const mySet = new Set();

// Adding an element to the set
mySet.add(42);

// Getting the size of the set
console.log(mySet.size); // Output: 1

// Checking if the set has a specific element
console.log(mySet.has(42)); // Output: true

Sets and methods

// Clearing all elements from the set
mySet.clear();

// Deleting a specific element from the set
mySet.add(42);
mySet.add(24);
mySet.delete(42); // Deletes the element 42 from the set

// Getting an iterator for the keys in the set
const keyIterator = mySet.keys();

// Getting an iterator for the values in the set
const valueIterator = mySet.values();

// Getting an iterator for the entries (key-value pairs) in the set
const entryIterator = mySet.entries();

// Iterating over each element in the set and performing an operation
mySet.forEach((value) => {
  console.log(value); // Output: 24
});

Dates and methods

// Create a new Date object
const currentDate = new Date();

// getDate(): Returns the day of the month (1-31) for the specified date according to local time.
currentDate.getDate(); // Output: Current day of the month

// getDay(): Returns the day of the week (0-6) for the specified date according to local time.
currentDate.getDay(); // Output: Current day of the week (0-6)

// getFullYear(): Returns the year (4 digits) of the specified date according to local time.
currentDate.getFullYear(); // Output: Current year

// getHours(): Returns the hour (0-23) in the specified date according to local time.
currentDate.getHours(); // Output: Current hour (0-23)

// getMilliseconds(): Returns the milliseconds (0-999) of the specified date according to local time.
currentDate.getMilliseconds(); // Output: Current milliseconds (0-999)

// getMinutes(): Returns the minutes (0-59) in the specified date according to local time.
currentDate.getMinutes(); // Output: Current minutes (0-59)

// getMonth(): Returns the month (0-11) for the specified date according to local time.
currentDate.getMonth(); // Output: Current month (0-11)

Dates and methods

// getSeconds(): Returns the seconds (0-59) in the specified date according to local time.
currentDate.getSeconds(); // Output: Current seconds (0-59)

// getTime(): Returns the numeric value corresponding to the time for the specified date according to universal time.
currentDate.getTime(); // Output: Number of milliseconds since January 1, 1970

// getTimezoneOffset(): Returns the time-zone offset in minutes for the current locale.
currentDate.getTimezoneOffset(); // Output: Timezone offset in minutes

Dates and methods

// setDate(): Sets the day of the month for a specified date according to local time.
currentDate.setDate(15);
console.log(currentDate); // Output: Date with day set to 15th of the month

// setFullYear(): Sets the full year (4 digits) for a specified date according to local time.
currentDate.setFullYear(2025);
console.log(currentDate); // Output: Date with year set to 2025

// setHours(): Sets the hour for a specified date according to local time.
currentDate.setHours(15);
console.log(currentDate); // Output: Date with hour set to 15:00

// setMilliseconds(): Sets the milliseconds for a specified date according to local time.
currentDate.setMilliseconds(500);
console.log(currentDate); // Output: Date with milliseconds set to 500

// setMinutes(): Sets the minutes for a specified date according to local time.
currentDate.setMinutes(30);
console.log(currentDate); // Output: Date with minutes set to 30

Dates and methods

// setMonth(): Sets the month for a specified date according to local time.
currentDate.setMonth(11);
console.log(currentDate); // Output: Date with month set to December (11)

// setSeconds(): Sets the seconds for a specified date according to local time.
currentDate.setSeconds(45);
console.log(currentDate); // Output: Date with seconds set to 45

// setTime(): Sets the Date object to the time represented by a 
// number of milliseconds since January 1, 1970, 00:00:00 UTC.
currentDate.setTime(0);
console.log(currentDate); // Output: Date set to January 1, 1970, 00:00:00 UTC

Dates and methods

// toISOString(): Returns a string representing the specified date as an ISO formatted string.
currentDate.toISOString(); // Output: ISO formatted string representing the date

// toDateString(): Returns the "date" portion of the Date as a human-readable string in American English.
currentDate.toDateString(); // Output: Date portion in human-readable string format

W6_D4

By Yash Priyam

W6_D4

  • 122