Type of var is undefined

Hello everyone my doubt is creepy. But I know you can clear it…

//My Code is

function sum(a,b){

//Now tricky part is here
let var1 = new sum(2,3); //Output: 5
typeof var1  //return "Object". I understand its true....

let var2 = sum(2,3); //Output: 5
typeof var2 // return "undefined". I dont understand why...

Can anyone explain why typeof var2 is undefined?

The function sum(a,b) reports the a+b as its result, it doesn’t return anything.

Therefore the typeof var2 returns undefined since the value of var2 is undefined (since sum(2,3) didn’t return anything and var2 still has no value even after function execution).

The new sum(2, 3) statement on the other hand is initializing an object using the new keyword, which returns an object (add{} to be more specific - functions are specialized objects in javascript).

1 Like

In other words (cause this tripped me up hard when I started, so breaking it down a bit more) your function console.log's out the result, it doesn’t have a return statement. It doesn’t return anything, so it has nothing to evaluate the typeof, and so the result is undefined.

Try this…add return a+b; to your function and see what happens…