Is there a reason why the function
keyword is needed for regular javascript functions? What is the design consideration behind it by Ecma International?
For me, the brackets {}
after the function indicate that it is a function, hence it would seem logical that it can be omitted. At least, we should have two ways of writing it to reduce boilerplate.
Note, that arrow functions are not the same as regular function declarations because they are not hoisted.
Inside of an Object, we can specify it without a function
keyword.
const person = {
name: "Taylor",
sayHello() {
return `Hello! My name is ${this.name}.`;
}
};
Why can we not do it outside the scope of an Object?
CodePudding user response:
One reason for it would be that, if it was made such that we were able to have function declarations without the function
keyword, the syntax would be ambiguous. First keep in mind that:
Semicolons are optional (and some prefer to write without them)
Newlines are permitted between the end of an argument list
)
and the start of a function block{
Plain blocks are permitted - that is, syntax like:
console.log('foo'); { console.log('bar'); }
Then, if the following was permitted:
sayHello()
{
console.log('baz');
}
What would it mean? Does it mean that this would be the definition of a sayHello
function, or does it mean to invoke a function named sayHello
and then start a new block?
Requiring function declarations to use the function
keyword keeps things absolutely unambiguous.