I’m still trying to get to grips with function definitions: am I correct in saying that this returns a type of undefined?
function foo() {
return
{
car: 'Audi'
};
}
I’m still trying to get to grips with function definitions: am I correct in saying that this returns a type of undefined?
function foo() {
return
{
car: 'Audi'
};
}
It returns undefined
, because of Automatic Semicolon Insertion. This is one of the major ASI hazards. Having a line break after return
makes it get treated as return;
. So your code ends up being:
function foo() {
return; // <=== Function returns here
{ // \
car: 'Audi' // > This is a freestanding block with a labelled statement which is the expression 'Audi'
}; // /
}
Remove the line break and it returns an object:
function foo() {
return {
car: 'Audi'
};
}
This is one reason that putting the opening {
on things is standard practice in JavaScript, even more so than other C-like languages.
Javascript assumes return
to be return;
, if you want to return any value it should be in the same line as return
.
If you are getting undefined
when you execute this function foo
, that's because the function is returning at return
itself, to get the object as return value, modify your function to be
function foo() {
return {
car: 'Audi'
};
}