I am currently working through codecademy JavaScript course and in Objects section I found this error. Section is about factory functions and the factory function takes two parameters. Factory function returns an object when called. After return statement when I press enter and start the curly braces on new line the program gives an error but when I move the opening curly brace back to same line as return keyword the error goes away. I have no idea why is this happening. Can anybody please put some light on what's happening with this code.
Code that gives syntax error
const robotFactory = (model, mobi) =>
{
return
{
model: model,
mobi: mobi,
beep()
{
console.log('Beep Boop');
}
}
};
const one = robotFactory('P-500', true);
console.log(one.model);
Code that does work
const robotFactory = (model, mobi) =>
{
return {
model: model,
mobi: mobi,
beep()
{
console.log('Beep Boop');
}
}
};
const one = robotFactory('P-500', true);
console.log(one.model);
JavaScript puts on implicit ;
s. So with your following code:
const robotFactory = (model, mobi) =>
{
return
{
JavaScript treats the above code as:
const robotFactory = (model, mobi) =>
{
return;
{
This is a Syntax Error. So you should never have any return statement on its own line.
More information: ECMAScript Automatic Semicolon Insertion, Understanding Automatic Semicolon Insertion in JavaScript, What are the rules for JavaScript's automatic semicolon insertion (ASI)?