- Show the different ways of creating an object
- Display all the keys of an object
- Display all the values of an object
- Write a function which can check if a given object is empty or not
- Create an empty object which has no prototype attached to it
- Show the usage of 'Object.entries' to create an object from key value pairs
- Connect 2 objects so that one object is prototypically connected to the other
- Create an object with getter and setter for property
- Show the different types of accessor properties available for object property and write a code defining them
- Show the different options available to prevent the modifications to the object
- Modify the given object so that it can be used inside a for...of loop
- Show the creation of Regular Expression in JavaScript
- Write a polyfill for Object.create
- Write a code show Optional chaining for objects and functions
- Show the usage of static variable & function in a class and accessing it from the code
- Write a class which uses private variable and function
- Show how inheritance works in Class and the use of super keyword with working example
- Show the way of using Proxy for object
- Show how can we use for..of loop to iterate on a range with given start and end values in an object
- Prove that private looking variable in a function is not really private specific to that object
- Object can be created using Object constuctor
- Object can also be created using Object literal form
- Object can be created using
new
keyword to constructor function - Object can be created using Class
const object = Object.create({ key: value });
const object = {
key: value
}
function getObject(key, value){
this[key] = value;
}
const object = new getObject('key', 'value');
class Obj {
constructor(key, value){
this[key] = value;
}
}
const object = new Obj('key', 'value');
- The keys of an object can be obtained using
Object.keys
for(let key in obj){
if (obj.hasOwnProperty(key)) {
console.log(key);
}
}
for(let key of Object.keys(obj)){
if (obj.hasOwnProperty(key)) {
console.log(key);
}
}
Object.keys(obj).forEach((key) => {
if (obj.hasOwnProperty(key)) {
console.log(key);
}
});
obj.hasOwnProperty(key)
is used to only display the properties present on the object and not inherited ones.
- The values of an object can be obtained using
Object.values
which returns an array of values
console.log(Object.values(obj));
for(let value of Object.values(obj)){
console.log(value);
}
Object.values(obj).forEach((value) => console.log(value));
for(let key in obj){
if (obj.hasOwnProperty(key)) {
console.log(obj[key]);
}
}
Object.values
will only fetch the values of the object and not inherited ones
- Object is empty if it has no keys
- Few objects such as
Date
object does not have any keys but still are not empty. Hence additional check can be implemented to verify the stringification of the object is also empty
function isObjectEmpty(obj){
if(obj !== null && typeof obj !== "undefined" && typeof obj === "object")
return Object.keys(obj).length === 0 && JSON.stringify(obj) === "{}";
else
return false;
}
obj.constructor === Object
is also used to verify along with the length of keys to check if object is empty which works for objects created with literal form
- Objects created in JavaScript will have a prototype object on it connected to other object or
Object
- Object constructor can be used to create such an empty object
const obj = Object.create(null);
- The key value pairs can be directly converted to object using
entries
method of Object
const arr = [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ];
const obj = Object.fromEntries(arr);
const map = new Map([ ['foo', 'bar'], ['baz', 42] ]);
const obj = Object.fromEntries(map);
- Objects in JavaScript are connected its prototype and is accessible for objects getPrototypeOf or
__proto__
setPrototypeOf
is used to set the prototype of the object
const obj1 = { a: 1 };
const obj2 = { b: 2 };
obj2.setPrototypeOf(obj1);
const obj1 = { a: "Object 1 value" };
const obj2 = { b: "Object 2 value" };
obj2.__proto__ = obj1;
The lookup happens at the object level initially and if the key is not found, prototype chain lookup happens
getter
andsetter
on the properties of object can be used to control the read and write behavior
const obj = {};
Object.defineProperty(obj, 'data', {
_data: 0, // closure variable to hold the data
get() {
return this._data;
},
set(value) {
this._data = value;
}
});
If the this.data
is accessed directly, the function will call itself infinitely. Hence, we would require one more variable to store the data
Show the different types of accessor properties available for object property and write a code defining them
value
accessor is used to set the value of the propertywritable
accessor is used to set if the property can be modified or notconfigurable
accessor is used to set the property to be configurable or notenumerable
accessor is to set the property to be considered in enumeration
var obj = { };
Object.defineProperty(obj, 'prop', {
value: 1,
writable: true,
configurable: true,
enumerable: true
});
Except value
, other accessort mentioned accept true or false
preventExtensions
is an Object method which prevents addition of any new property to an objectseal
is an Object method which prevents addition and deletion of any property in an objectfreeze
is an Object method which prevents addition, deletion and update of any property of an object- There are also methods
isExtensible
,isSealed
andisFrozen
on Object to check
Object.preventExtensions(obj);
Object.isExtensible(obj); // false
Object.seal(obj);
Object.isSealed(obj); // true
Object.freeze(obj);
Object.isFrozen(obj); // true
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
- Symbol iterator can be used to define the iterator on the object
- The values of the object can accessed with
for..of
the way we can do it for array
const obj = {
[Symbol.iterator](){
const keys = Object.keys(this);
let idx = 0;
return {
next: () => {
if(idx >= keys.length)
return { value: this[keys[idx++]], done: true };
else
return { value: this[keys[idx++]], done: false };
}
}
},
key1: "value1",
key2: "value2",
key3: "value3"
}
const obj = {
*[Symbol.iterator]() {
for (let key in obj) {
yield obj[key];
}
},
key1: "value1",
key2: "value2",
key3: "value3"
}
- Regular expressions are patterns used to match character combinations in strings
- Regular expressions can be created using literal form or constructor form
- Constructor form accepts regular expression as the first argument and flags as the 2nd argument
- Literal form is simple which takes regular expression and flags in a single expression
// literal form
let re = /ab+c/g;
// constructor form
let re = new RegExp('ab+c', 'g');
In JavaScript, regular expressions are objects
- The creating of object can happen by making constructor call to the function
if (typeof Object.create !== 'function') {
Object.create = function (proto, propertiesObject) {
if ((typeof proto === 'object' || typeof proto === 'function') &&typeof propertiesObject !== 'undefined') {
// F is a dummy empty function
function F() {}
F.prototype = proto;
return new F();
} else {
throw new TypeError('Invalid proto or properties object');
}
};
}
- The optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects
- The expression short-circuits with a return value of undefined in the absence of property
// object property access
obj.val?.prop;
// object property access through bracket notation
obj.val?.[expr]
// array index access
obj.arr?.[index]
// object property access for function call
obj.func?.(args)
- Static members of the class are class level variables and not created for each instances of the class
- Static members can be accessed directly using class name
class Browser {
static className = "Browser";
constructor(os, browserName){
this.os = os;
this.browserName = browserName;
}
static areTheySameBrowsers(browser1, browser2) {
return browser1.browserName === browser2.browserName;
}
}
// driver code
const browser1 = new Browser("Linux", "Chrome");
const browser2 = new Browser("Windows", "Firefox");
Browser.className; // Browser
Browser.areTheySameBrowsers(browser1, browser2); // false
- Private members of the class are only accessible within the class and instances of the class do not have access to it
- Private members can be created with the prefix '#' before the name of the class member
class ClassWithPrivateFields {
#privateVar;
publicVar;
#privatFunc() {
this.#privateVar = 7;
this.publicVar = 10;
}
publicFunc() {
this.#privatFunc();
return [this.#privateVar, this.publicVar];
}
}
// driver code
const instance = new ClassWithPrivateFields();
// can't access private variable
instance.privateVar; // undefined
// can't access private function
instance.privatFunc(); // Error
instance.publicFunc(); // 7, 10
- Class level inheritance can happen when a class inherits from another class using the keyword
extends
- The child class can access parent class members using the keyword
super
- The non private members of parent class become available to child class when inherited
class BaseComponent {
constructor(componentName) {
this.componentName = componentName;
}
setState(obj) {
this.state = obj;
this.render();
}
addValues(props) {
return props.reduce((a, b) => a + b);
}
}
class Component extends BaseComponent {
constructor(name = '', props) {
super(name); // super() is used to call parent class consturctor
this.state = { ...props };
}
addValues(...props) {
const sum = super.addValues(props); // super.property is used to access parent class property
this.setState({ sum, props });
}
render() {
console.log(`Sum of ${this.state.props} is ${this.state.sum}`);
}
}
// driver code
let component = new Component('UI Component');
component.componentName; // UI Component
component.addValues(3, 5); // Sum of 3,5 is 8
component.addValues(9, -4, 6, 2); // Sum of 9,-4,6,2 is 13
super
call to constructor within constructor of child class must be the first statement
- The Proxy object enables create a proxy for another object, which can intercept and redefine fundamental operations for that object
- Proxy can be set for objects (including functions and arrays) to intercept the values which gives us the control on access and modification of the real object
- Proxy takes 1st argument as an object / function and 2nd argument as a object with different function traps
let obj = {
key: "value"
};
let proxy = new Proxy(obj, {
get(target, handler){
console.log("Proxy get is invoked on target with property: " + handler);
return target[handler];
},
set(target, handler, value){
console.log("Proxy set is invoked on target object with property: " + handler + " and value: " + value);
target[handler] = value;
}
});
// driver code
proxy.key2 = "value2"; // Proxy set is invoked on target object with property: key2 and value: value2
proxy.key1; // Proxy get is invoked on target with property: key1
There are lot of other traps used in Proxy apart from get
, set
, apply
- https://javascript.info/proxy
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
// Example
let range = {
start: 1,
end: 10
};
for (let i of range) console.log(i); // 1 2 3 4 5 6 7 8 9 10
- For..of loop uses iterator of an object to fetch the values one at a time
- Defining an iterator Symbol on the object to iterate from start to end will fetch the values of the range
Object.defineProperty(range, Symbol.iterator, {
value: function () {
let i = this.start;
return {
next: () => (i <= this.end ? { value: i++, done: false } : { value: undefined, done: true }),
};
},
});
- Private looking variables can be created in a function and can given access by providing function interfaces
- The functions maintain a closure over function variables and hence the function variables persist inside the function interfaces
- Though the variable is private within the function and cannot be accessed, these variables are not private to the created object
function ObjectCreator() {
var privateVar = 0;
// function interfaces get, set
this.getPrivateVar = function () {
return privateVar;
};
this.setPrivateVar = function (value) {
privateVar = value;
};
}
// driver code
var obj = new ObjectCreator();
obj.setPrivateVar(10);
obj.getPrivateVar(); // 10
var privateVarAccessor = {
get: obj.getPrivateVar,
set: obj.setPrivateVar
};
// obj private variable is accessible by other external entities
privateVarAccessor.set(5);
privateVarAccessor.get(); // 5
obj.getPrivateVar(); // 10