简体   繁体   中英

Typeof value of function value/name logs as “Undefined” . Why?

In the following function typeof(var2) logs as "undefined", whereas I expected it to be a function or a variable.

var add_nos = function()    {
    var x = 2+3;
    console.log(x);

}
var var2 = add_nos();
console.log(typeof(var2));
console.log(typeof(add_nos));

Can somebuddy pls explain, Why is that so ?

You're assigning the return value of add_nos() to var2 . Since it doesn't have any explicit return value, it returns undefined .

var var2 = add_nos();

add_nos() returns undefined implicitly, that's why console.log(typeof(var2)); prints undefined

What your u need to do is add a line to your function that looks like this return x; that will then return the value of x to whatever called the function. Allowing you to use functions in your calculations. Every function returns a value the thing is that if you don't define what it is to return it returns undefined you're function Ran just fine it just didn't have a value specified to be a return value.

When you execute a function, it returns something that you decided to return but it you did not returned any value explicitly then it will return undefined which in this case was assigned to var2. Some other languages do similar. eg python returns None in such case

The main thing to remember is that functions in JavaScript always return a value. The explicit case is when you include the return statement in your function and decide what to return. However, when you don't explicitly include a return statement in your function, JavaScript will return the value undefined .

Like others have mentioned, your function returns the undefined value because there is no explicit return statement in it. The variable var2 contains this undefined value. Therefore, your first typeof statement asks what the type of undefined is - which is undefined .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM