Search code examples
javascriptclassconsole.log

Order of execution for class in javascript


class Department{   
 constructor(){     
  console.log('parent class')   
 } 
} 
class Employee extends Department{  
  constructor(){    
   super()     
   console.log('child constructor method')   
  }     
  findName(){       
   console.log('Vimal');   
  } 
} 
let E1 = new Employee(); console.log(E1.findName())

Now in the above code it gives me the logs as "parent class" "child constructor method" "User Name" undefined Now where is this undefined coming from can anyone help me understand this


Solution

  • This function,

    findName(){       
       console.log('Vimal');   
      } 
    

    Returns undefined (by default in JavaScript, function that does not explicitly return something - return undefined).

    So when you do console.log(E1.findName()), you do 2 things:

    1. Run the function, then Vidal will be logged
    2. Printing the return value of E1.findName(). The function returns undefined so indeed undefined is logged.