You can use below object methods to prevent the object modification :
You can user Object.seal()
method to prevents the new properties being added to an object, but allows the modification of existing properties.
//Initialize an object var employee={ firstName:'John', lastName:'Doe', } // Seal the object const newEmployee = Object.seal(employee); newEmployee.age=33; console.log(newEmployee); // { firstName: 'John', lastName: 'Doe' }
You can user Object.freeze()
to prevents the modification of properties and values of an object, and prevents properties from being added or removed from an object.
//Initialize an object var employee={ firstName:'John', lastName:'Doe', } // Freeze the object const newEmployee = Object.freeze(employee); newEmployee.age=33; console.log(newEmployee); // { firstName: 'John', lastName: 'Doe' }
You can use Object.preventExtensions()
to prevent new properties or methods being added to an object.
//Initialize an object var employee={ firstName:'John', lastName:'Doe', } // preventExtensions the object Object.preventExtensions(employee); employee.age=33; console.log(employee); // { firstName: 'John', lastName: 'Doe' }
No. Most of the objects have prototypes except for the base object which is created by the user.
var dictionary = Object.create(null, { destructor: { value: "A destructive element" } });
A data structure in which data is stored as key value pairs. In which a unique key map to a value. Both the key and the value can be in any data type. A map is a inerrable data structure, this means that the sequence of insertion is remembered and that we can access the elements in e.g. for..of loop.
A) The Map is an instance of an object but the vice-versa is not true.
var map = new Map(); var obj = new Object(); console.log(obj instanceof Map); // false console.log(map instanceof Object); // true
B) In Object, the datatype of the key-field is restricted to integer, strings, and symbols. Whereas in Map, the key-field can be of any datatype (integer, an array, an object)
var map = new Map();//Empty map.set(1,'1'); map.set('one', 1); map.set('{}', {name:'John Doe'}); map.set(12.3, 12.3) map.set([12],[12345]) for(let [key,value] of map.entries()) console.log(key+'---'+value)
C) In the Map, the original order of elements is preserved. This is not true in case of objects.
D) A Map may perform better in scenarios involving frequent addition and removal of key pairs.
The arguments object is a collection of arguments like an Array object accessible inside functions that contains the values of the arguments passed to that function.
function testArguments() { for (var i = 0, len = arguments.length; i < len; ++i) { console.log(arguments[i]); } } testArguments(1, 2, 3) // output // 1 // 2 // 3
You can use date.getTime() method to compare date values instead comparison operators (==, !=, ===, and !==)
var date1 = new Date(); var date2 = new Date(date1); console.log(date1.getTime() === date2.getTime()); //true console.log(date1 === date2); // false
RegExp object is a regular expression object with predefined properties and methods.
Use Object.isFrozen() method to check if an object is frozen or not.
//Initialize an object var employee={ firstName:'John', lastName:'Doe', } console.log(Object.isFrozen(employee)); // output : false // Freeze the object Object.freeze(employee); console.log(Object.isFrozen(employee)); // output : true
Use Object.is() method to check whether two values are the same or not.
Two values are the same if one of the following conditions are true:
var x=10,y=10; console.log(Object.is('John Doe', 'John Doe')); // true console.log(Object.is(x, y)); // true console.log(Object.is([], []) ); // false
Purpose of Object is method are as follows:
The Proxy object is used to define custom behaviour for fundamental operations like lookup, assignment, enumeration, function invocation, etc.
var handler = { get: function(obj, prop) { return prop in obj ? obj[prop] : -1; } }; var p = new Proxy({}, handler); p.a = 101; p.b = undefined; console.log(p.a, p.b); // 101, undefined console.log('c' in p, p.c); // false, -1
The Object.isSealed()
method is used to check if an object is sealed or not. An object is sealed if all the below conditions hold true
If it is not removable
//Initialize an object var employee={ firstName:'John', lastName:'Doe', } console.log(Object.isSealed(employee)); // output : false // Seal the object Object.seal(employee); console.log(Object.isSealed(employee)); // output : true
Object.values : It returns an array of values.
var employee={ firstName:'John', lastName:'Doe', } console.log(Object.values(employee)); // [ 'John', 'Doe' ]
Object.entries : It returns an array of [key,value] pairs.
var employee={ firstName:'John', lastName:'Doe', } console.log(Object.entries(employee)); // [ [ 'firstName', 'John' ], [ 'lastName', 'Doe' ] ]
The Object.create()
method is used to create a new object with prototype object and properties and
It uses the existing object as the prototype of the newly created object. It returns a new object with prototype object and properties.
var employee={ firstName:'', printFullName: function(){ console.log(`${this.firstName} ${this.lastName}`); } } var empObj= Object.create(employee); empObj.lastName ='Doe'; // "lastName" is a property set on "empObj", but not on "employee" empObj.firstName='John'; //inherited properties from employee and can be overwritten empObj.printFullName(); // output: John Doe
The Object.defineProperty()
static method is use for defining a new property directly on an object, or modifies an existing property on an object, and returns the object.
var employee ={}; Object.defineProperty(employee, 'firstName', { value: 'John', writable: false }); console.log(employee.firstName); // John employee.firstName='Mike'; // throws an error in strict mode
There are 3 possible ways for accessing the property of an object.
get = object.property
object.property = set
get = object[property_name]
object[property_name] = set
let object = {}
object['1'] = 'value'
console.log(object[1])
An error object is a built-in error object that provides exception information when an error occurs. It has two properties: name and message.
function testException(num1, num2){ try { return test(num1,num2); } catch (error) { console.log(`Name: ${error.name}, Message: ${error.message}`); } } var result =testException(10,0); // Name: ReferenceError, Message: test is not defined
There are 6 types error names, and these are as follows
The Intl object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. It provides an access to several constructors and language sensitive functions.
Properties of Intl object as follows:
An object initializer is an expression that use for initialization of an Object. Objects can be initialized using Object.create(),new Object() or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}).
const boj1 = {a: 'john', b: 101, c: {}}; console.log(boj1.a); // expected output: "john" const a = 'john'; const b = 101; const c = {}; const obj2 = {a: a, b: b, c: c}; console.log(obj2.b); // expected output: 101 const oj3 = {a, b, c}; console.log(oj3.a); // expected output: "john"
Use Object.getPrototypeOf(obj)
method to get the prototype of the specified object. i.e. The value of the internal prototype property. If there are no inherited properties, then null value is returned.
var employee={ firstName:'John', lastName:'Doe', } var copyEmployee = Object.create(employee); var copyEmployee1 = Object.create({}); console.log(Object.getPrototypeOf(copyEmployee) === employee); // true console.log(Object.getPrototypeOf(copyEmployee1) === employee); // false
In ES5, it will throw a TypeError exception if the object parameter is not an object.
In ES2015, the parameter will be coerced to an Object.
// ES5 Object.getPrototypeOf('John'); // TypeError: "John" is not an object // ES2015 Object.getPrototypeOf('John'); // String.prototype
You can use Object.setPrototypeOf()
method that sets the prototype (i.e., the internal Prototype property) of a specified object to another object or null.
class Employee{ firstName='John'; lastName='Doe'; } class Emp{}; Object.setPrototypeOf(Employee.prototype, Emp.prototype); console.log(Emp); Object.setPrototypeOf({}, null);
The Object.isExtensible()
method is used to check if an object is extensible or not.
var employee={ firstName:'John', lastName:'Doe', } console.log(Object.isExtensible(employee)); //true
Use Object.preventExtensions()
method to prevent new properties from ever being added to an object.
var employee={ firstName:'John', lastName:'Doe', } Object.preventExtensions(employee); try { Object.defineProperty(employee, 'age', { value: 42 }); } catch (e) { console.log(e); // Expected output: TypeError: Cannot define property age, object is not extensible }
Use Object.defineProperties()
method to define new or modifies existing properties directly on an object and returning the object.
var employee={ firstName:'John', } var employee1 =Object.defineProperties(employee, { lastName: { value: 'Doe', writable: true }, age: { value: 32, writable: true } }); console.log(employee1.lastName); // Doe
You can use Object.getOwnPropertyNames()
method to get all the properties of an object.
var employee={ firstName:'John', lastName:'Doe' } console.log(Object.getOwnPropertyNames(employee)); // [ 'firstName', 'lastName' ]
You can use Object.getOwnPropertyDescriptors()
method to get all own property descriptors of a given object.
var employee={ firstName:'John', lastName:'Doe' } const employeeDescriptorsObject = Object.getOwnPropertyDescriptors(employee); console.log(employeeDescriptorsObject.firstName.writable); //true console.log(employeeDescriptorsObject.firstName.configurable); //true console.log(employeeDescriptorsObject.firstName.enumerable); //true console.log(employeeDescriptorsObject.firstName.value); // John
Object literals make it easy to quickly create objects with properties inside the curly braces.
//ES6 var firstName = 'John', LastName = 'Doe' empObj = { firstName, LastName } console.log(empObj); // { firstName: 'John', LastName: 'Doe' } //ES5 var firstName = 'John', LastName = 'Doe' empObj = { firstName : firstName, LastName: LastName} console.log(empObj); // { firstName: 'John', LastName: 'Doe' }
JavaScript has a built-in error object that provides error information when an error occurs. The Error constructor creates an error object and the instances of error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions.
The EvalError object indicates an error regarding the global eval() function. This exception is not thrown by JavaScript anymore, however the EvalError object remains for compatibility.
Syntax : new EvalError([message[, fileName[, lineNumber]]])
try { throw new EvalError('Hello John Doe', 'js1.js', 1); } catch (e) { console.log(e instanceof EvalError); // true console.log(e.message); // "Hello John Doe" console.log(e.name); // "EvalError" console.log(e.stack); }
You can use spread(…)
operator to convert the array to object.
var employees = ["John", "Max", "Adam", "Julia"]; var employeesObject = {...employees}; console.log(employeesObject); // { '0': 'John', '1': 'Max', '2': 'Adam', '3': 'Julia' }
Below is the list of placeholders available from console object,
var employee = {id: 1, name:"John", country: "Canada"}; console.log("Hello %s, your details %o are available in the object form", "John", employee); // Hello John, your details { id: 1, name: 'John', country: 'Canada' } are available in the object form
The console.dir()
is used to display an interactive list of the properties of the specified JavaScript object as JSON.
var employee = {id: 1, name:"John", country: "Canada"}; console.dir(employee) // { id: 1, name: 'John', country: 'Canada' }
The console.table()
is used to display data in the console in a tabular format to visualize complex arrays or objects.