JavaScript Interview Questions String

What is prototype chain?, what is constructor in JavaScript? , Can you have multiple constructors in JavaScript?, what is super keyword in JavaScript?,
             What is class in JavaScript?, how to create class using function expression in JavaScript?, What is a Function Declaration, What is a Function Expression, what is inheritance in JavaScript,
             how to implement inheritance in JavaScript, what are the built-in Objects in JavaScript, What is the difference between native, host and user objects, What are the various url properties of location object,
             . What is static method in JavaScript?, what is Getters/Setters in JavaScript?, How do you loop through or enumerate JavaScript object?, How do you test for an empty object?,
             How do you copy properties from one object to other?, What is difference class and function?, How do you create an object with prototype?

1. What is prototype chain?

Most of JavaScript object has a prototype, including the prototype object. Prototype  chain goes all the way back until it reaches an object that has no prototype.  JavaScript tries to search it on the __proto__  object which points to its prototype constructor function. But since prototype also has __proto__ object which points the prototype of its constructor function and it tries to find there. This search cycle continues until there is no __proto__ property on the prototype object.

2 what is constructor in JavaScript?

The constructor method is a special method, that is use for creating and initializing an object created within a class.

  

        class Employee{
        constructor(){
        this.country='USA'
        }
        }

        var empObj= new Employee();
        console.log(empObj.country);  // Output USA
    

3. Can you have multiple constructors in JavaScript?

No, JavaScript cannot have more than one constructor. If you created more than one constructor, then throw this error “A class may only have one constructor”

  

        class Employee{
        constructor(){
        this.country='USA'
        }
        constructor(firstName){
        this.firstName=firstName
        this.country='USA'
        }

        }
        var empObj= new Employee();

    

4. what is super keyword in JavaScript?

The super keyword refers to the parent class.

super keyword used to call parent class constructor and to access the parent class properties and methods.

  

        class Employee{

        constructor(firstName,lastName){
        this.firstName=firstName;
        this.lastName=lastName;
        }

        }


        class FullTimeEmployee extends Employee{
        constructor(firstName,lastName, age){
        super(firstName,lastName)
        this.age=age;

        }
        }

        var empObj= new FullTimeEmployee('John','Doe',32);
        console.log(empObj);  // output : FullTimeEmployee { firstName: 'John', lastName: 'Doe', age: 32 }

    

5. What is class in JavaScript?

A JavaScript class is a type of function. Classes are declared with the class keyword. We will use function expression syntax to initialize a function and class expression syntax to initialize a class.

6. how to create class using function expression in JavaScript?

  

        const employee = function(){
        this.firstName='';
        this.lastName='';

        }

        employee.firstName='John';
        employee.lastName='Doe'
        console.log(employee);  // output : [Function: employee] { firstName: 'John', lastName: 'Doe' }

    

7. What is a Function Declaration?

A Function Declaration defines a named function variable without requiring variable assignment. Function Declarations occur as standalone constructs and cannot be nested within non-function blocks.

  

        function sayHello(){
        console.log('Hello John Doe');
        }

        sayHello(); // output : Hello John Doe

    

8. What is a Function Expression?

A Function Expression defines a function as a part of a larger expression syntax (typically a variable assignment ). Functions defined via Functions Expressions can be named or anonymous.

  

        var sayHello = function() {
        console.log('Hello John Doe');
        }

        sayHello() // output : Hello John Doe
    

9. what is inheritance in JavaScript?

Inheritance means inherit the parent class members in child class and inheritance support by prototype.

10. how to implement inheritance in JavaScript?

The extends keyword is used to create a child class of parent class

  

        class Employee{

        constructor(firstName,lastName){
        this.firstName=firstName;
        this.lastName=lastName;
        }

        }


        class FullTimeEmployee extends Employee{
        constructor(firstName,lastName, age){
        super(firstName,lastName)
        this.age=age;

        }
        }

        var empObj= new FullTimeEmployee('John','Doe',32);
        console.log(empObj);  // output : FullTimeEmployee { firstName: 'John', lastName: 'Doe', age: 32 }

    

11. what are the built-in Objects in JavaScript?

Some of them are as follows:

  

        var obj = new Object();    // A new Object object
        var str = new String();    // A new String object
        var num = new Number();    // A new Number object
        var bool = new Boolean();   // A new Boolean object
        var arr = new Array();     // A new Array object
        var regex = new RegExp();    // A new RegExp object
        var func = new Function();  // A new Function object
        var date = new Date();      // A new Date object

    

12. What is the difference between native, host and user objects?

Native objects:  These objects are part of the JavaScript language defined by the ECMAScript specification. For example, String, Math, RegExp, Object, Function etc.

 Host objects: These objects are provided by the browser or runtime environment (Node). For example, window, XmlHttpRequest, DOM nodes etc considered as host objects. 

User objects: These objects are defined in the JavaScript code. For example, Employee object created for employee information.

13. What are the various url properties of location object?

Below are the location object properties:

  • href - The entire URL
  • protocol - The protocol of the URL
  • host - The hostname and port of the URL
  • hostname - The hostname of the URL
  • port - The port number in the URL
  • pathname - The path name of the URL
  • search - The query portion of the URL
  • hash - The anchor portion of the URL

14. What is static method in JavaScript?

Static methods are functions on class itself, and not on its prototype, unlike the other methods in the class, which are defined on its prototype.

Static methods are declared using static keyword and can access without creating  object of class.

  

        class Utility{

        static sayHello(){
        console.log('Hello John Doe');
        }
        }

        Utility.sayHello(); // Hello John Doe

    

15. what is Getters/Setters in JavaScript?

Class can have getter/setters to get the property value and or to set the property values.

  

        class Employee{

        _firstName = '';
        get firstName() {
        return this._firstName;
        }
        set firstName(value) {
        this._firstName = value;
        }
        }

    

16. How do you loop through or enumerate JavaScript object?

You can loop through using below options :

for-in : A loop structure that loops through the names of an object's enumerable properties, including inherited ones, whose names are strings

Object.keys : A function providing an array of the names of an object's own, enumerable properties whose names are strings.

Object.values : A function providing an array of the values of an object's own, enumerable properties.

Object.entries : A function providing an array of the names and values of an object's own, enumerable properties (each entry in the array is a [name, value] array).

Object.getOwnPropertyNames :A function providing an array of the names of an object's own properties (even non-enumerable ones) whose names are strings.

Object.getOwnPropertySymbols : A function providing an array of the names of an object's own properties (even non-enumerable ones) whose names are Symbols.

Reflect.ownKeys : A function providing an array of the names of an object's own properties (even non-enumerable ones), whether those names are strings or Symbols.

  

      
    

17. How do you test for an empty object?

You can check the object is empty or not using different ways and some of them are as follows:

A) Using hasOwnProperty

  

        class Employee{

        }

        function isObjectEmpty(obj) {
        for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
        return false;
        }

        return true;
        }

        var empObj = new Employee();

        var result =isObjectEmpty(empObj);

        console.log(result); // output : false

    

B) Using Object.keys()

  

        class Employee{

        }

        function isObjectEmpty1(obj) {
        return Object.keys(obj).length === 0;
        }

        var empObj = new Employee();

        var result =isObjectEmpty1(empObj);

        console.log(result); // output : false

    

C) Using for..in loop

  

        class Employee{

        }
        function isObjectEmpty2(obj) {
        for (var x in obj) { return false; }
        return true;
        }
        var empObj = new Employee();

        var result =isObjectEmpty2(empObj);

        console.log(result); // output : false

    

D) Using Object.entries()

  

        function isObjectEmpty3(obj) {

        return Object.entries(obj).length === 0;
        }

        class Employee{

        }
        var empObj = new Employee();

        var result =isObjectEmpty3(empObj);

        console.log(result); // output : false

    

E) Using JSON.stringify

  

        function isObjectEmpty4(obj){
        return JSON.stringify(obj) === '{}';
        }

        class Employee{

        }
        var empObj = new Employee();

        var result =isObjectEmpty4(empObj);

        console.log(result); // output : false

    

18. How do you copy properties from one object to other?

You can use Object.assign() method which is used to copy the values and properties from one object to another object. It returns the target object which has properties and values copied from the source object.

  

        var  employee={
        firstName:'John',
        lastName:'Doe'

        }

        var copyEmployee =[]
        copyEmployee =  Object.assign(copyEmployee,employee)

        console.log(copyEmployee); // [ firstName: 'John', lastName: 'Doe' ]

    

19. What is difference class and function?

Function Declarations get Hoisted to Top of the context, whereas classes declarations and function Expressions are not Hoisted.

Function Declarations, Expression can be Overridden as they are like a Variable - var if multiple declaration is available then it overrides its parent scope. Whereas the Classes are not Overridden they are like let | const, let doesn't allows multiple declaration with same name inside its scope.

Function's / classes allows only single constructor for its object scope.

Computed method names are allowed to ES6 classes having class keyword, but function keyword is not allowing it

20. How do you create an object with prototype?

The Object.create() method is used to create a new object with the specified prototype object and properties. i.e., It uses existing object as the prototype of the newly created object. It returns a new object with the specified prototype object and properties.

  

        var  employee={
        firstName:'John',
        lastName:'Doe',

        printFullName: function(){
        console.log(`${this.firstName}  ${this.lastName}`);
        }
        }

        var copyEmployee = Object.create(employee);
        copyEmployee.firstName ='Mike';

        copyEmployee.printFullName(); // output: Mike  Doe