Returning an object from a function is not working as expected
Clash Royale CLAN TAG#URR8PPP
Returning an object from a function is not working as expected
For example
function a()
return
testing:1
;
function b()
return
testing:1
;
In the above code the function a() returns an object of testing:1, but the function b() returns the value of undefined. What is the reason behind this behaviour?
Is it because the return value starts in the second line?
3 Answers
3
Yes, is happening because when the interpreter runs the b
function an see the return
expression an anything near, it return undefined
.
b
return
undefined
The return statement is affected by automatic semicolon insertion (ASI). No line terminator is allowed between the return keyword and the expression.
Put multi-line return
in ()
brackets:
return
()
function a()
return (
testing:1
);
function b()
return(
testing:1
);
console.log(a());
console.log(b());
Javascript can be funky at times, but just having return
at the end of a function returns, just returns nothing/null/undefined. I think your case the space between return and { is causing it to return anyway, despite the array there.
return
Like your function a()
, have it typed like this:
function a()
function a()
return
testing:1
;
function b()
return
testing:1
;
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.