JavaScript Interview Questions Object

 How to prevent modification of an object in JavaScript? Is all objects have prototypes?
             What is map? what is the difference between map and object? What is an arguments object? How do you compare two date objects? What is a RegExp object?
             How do you determine whether object is frozen or not? How do you determine two values same or not using object? What is the purpose of using object is method?
             What is a proxy object? How do you determine if an object is sealed or not? What is the main difference between Object.values and Object.entries method? How do you create an object with prototype?
             How do you define property on Object constructor? What are the different ways to access object properties? What is an error object? What are the different error names from error object?

1. How to prevent modification of an object in JavaScript?

You can use below object methods to prevent the object modification :

A) Object.seal()

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' }
    

B) Object.freeze()

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' }
    

C) Object.preventExtensions()

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' }
    

2. Is all objects have prototypes?

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" }
        });
    

3. What is map?

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.

4. what is the difference between map and object?

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.

5. What is an arguments object?

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
    

6. How do you compare two date objects?

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
    

7. What is a RegExp object?

RegExp object is a regular expression object with predefined properties and methods.

8. How do you determine whether object is frozen or not?

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

    

9. How do you determine two values same or not using object?

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:

  • both undefined
  • both null
  • both true, both false
  • both strings of the same length with the same characters in the same order
  • both the same object (means both objects have same reference)
  

        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
    

10. What is the purpose of using object.is() method?

Purpose of Object is method are as follows:

  • It is used for comparison of two strings.
  • It is used for comparison of two numbers.
  • It is used for comparing the polarity of two numbers.
  • It is used for comparison of two objects.

11. What is a proxy object?

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
    

12. How do you determine if an object is sealed or not?

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 extensible.
  • If all its properties are non-configurable.

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
    

13. What is the main difference between Object.values and Object.entries method?

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' ] ]
    

14. How do you create an object with prototype?

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
    

15. How do you define property on Object constructor?

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
    

16. What are the different ways to access object properties?

There are 3 possible ways for accessing the property of an object.

  1. A) Dot notation: It uses dot for accessing the properties

get = object.property

object.property = set

  1. B) Square brackets notation: It uses square brackets for property access

get = object[property_name]

object[property_name] = set

  1. C) Property names: Property names are string or Symbol. Any other value, including a number, is coerced to a string.

let object = {}

object['1'] = 'value'

console.log(object[1])

17. What is an error object?

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
    

18. What are the different error names from error object?

There are 6 types error names, and these are as follows

  • EvalError: An error has occurred in the eval() function.
  • RangeError: A number "out of range" has occurred
  • ReferenceError: An illegal reference has occurred
  • SyntaxError: A syntax error has occurred             
  • TypeError: A type error has occurred
  • URIError: An error in encodeURI() has encodeURI() or decodeURI()

19. What is an Intl object?

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.

20. What are the properties of Intl object?

Properties of Intl object as follows:

  • Collator: Enable language-sensitive string comparison.
  • DateTimeFormat: Enable language-sensitive date and time formatting.
  • ListFormat: Enable language-sensitive list formatting.
  • NumberFormat: Enable language-sensitive number formatting.
  • PluralRules: Enable plural-sensitive formatting and language-specific rules for plurals.
  • RelativeTimeFormat: Enable language-sensitive relative time formatting.

21. What is an object initializer?

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"
    

22. How do you get the prototype of an object?

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
    

23. What happens If I pass string type for getPrototype method?

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

    

24. How do you set prototype of one object to another?

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);
    

25. How do you check whether an object can be extendable or not?

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
    

26. How do you prevent an object to extend?

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
        }
    

27. How do you define multiple properties on an object?

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
    

28. How do you list all properties of an object?

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' ]
    

29. How do you get property descriptors of an object?

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
    

30. What are enhanced object literals?

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' }

    

31. What is the purpose of Error object?

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.

32. What is the purpose of EvalError object?

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);
        }
    

33. What is the easiest way to convert an array to an object?

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' }
    

34. What are the placeholders from console object?

Below is the list of placeholders available from console object,

  • %o — It takes an object,
  • %s — It takes a string,
  • %d — It is used for a decimal or integer These placeholders can be represented in the console.log as below
  

        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
    

35. What is the purpose of dir method of console object?

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' }
    

36. How do you display data in a tabular format using console object?

The console.table() is used to display data in the console in a tabular format to visualize complex arrays or objects.