Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ES6: Is there a reason why the `function` keyword is needed?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading