JavaScript returns undefined if curly brace is on next line

08/28/20181 Min Read — In JavaScript

Semicolons are optional in JavaScript. If you do not open a brace or add your return object to the same line as the return statement, JavaScript will interpret this as desiring to return undefined.

const returnHelloWorld = () => {
return {
message: 'hello world',
};
};
const returnUndefined = () => {
return
{
message: 'hello world';
}
};
const onClickHelloWorld = () => {
alert(JSON.stringify(returnHelloWorld()));
};
const onClickUndefined = () => {
alert(returnUndefined());
};
render(
<div>
<button onClick={onClickHelloWorld}>working</button>
<button onClick={onClickUndefined}>broken</button>
</div>
);

This behavior trips up a lot of developers coming from languages where the standard is to add the opening object brace on a fresh new lone. So remember, next time you are seeing a strange undefined error on a return of an object initialization, check to make sure that the brace starts on the same line as the return statement. A way to always avoid this issue entirely is to not return anonymous objects directly in your functions. Assigning an anonymous object to a variable ahead of time will save you a lot of pain down the road.

.e.g -

const returnHelloWorld = () => {
const response = {
message: 'hello world',
};
return response;
};
const onClickHelloWorld = () => {
alert(JSON.stringify(returnHelloWorld()));
};
render(
<div>
<button onClick={onClickHelloWorld}>working</button>
</div>
);