0

Js question

Hello, can someone explain why the code is outputing function? function foo() { return 2018; } foo.bar = "Programmers rule"; typeof foo; //function Thank you a lot.

15th Jun 2020, 7:29 PM
David
David - avatar
8 Antworten
+ 4
This really should be self-explanatory. Especially to someone who is level 15 like yourself. Anyway, typeof will return the type of whatever thing you pass to it. You have created a function called foo, so when you say typeof foo, it will, of course, return function.
15th Jun 2020, 8:07 PM
Russ
Russ - avatar
+ 3
David The difference is between : typeof foo; //function and typeof foo(); // number If you call the function (by adding the "()" to it), what you get is what it returns. If not, you just get what foo is - a function.
15th Jun 2020, 8:27 PM
Russ
Russ - avatar
+ 3
It's added just for confusion and doesn't have any impact on the output. I guess what it does do is give a glimpse into the fact that functions are a type of object, and thus can have attributes.
15th Jun 2020, 8:52 PM
Russ
Russ - avatar
+ 2
I've just seen your edit on your first comment, so let me refer you to this page I found. Hopefully it will help explain. https://www.dofactory.com/tutorial/javascript-function-objects
15th Jun 2020, 8:54 PM
Russ
Russ - avatar
+ 2
Russ thanks. You explained it nicely. I will Check it out.
15th Jun 2020, 8:54 PM
David
David - avatar
0
Russ I know about the typeof thing is just that in some challenges typeof is the data type after the return keyword, btw, shouldnt this return objects, since functions are objects?
15th Jun 2020, 8:24 PM
David
David - avatar
0
Ah, I see. Its s lot clearer now. Also, does this bar property have any meaning here? Or is it added just for confusion?
15th Jun 2020, 8:40 PM
David
David - avatar