Search code examples
javascriptiife

How to convert an iife old ways function to an arrow function in a single line


how would you convert:

(function(age) {return `your ${age}`;
})(10);

to an arrow function? I tried but doesnt work:

(const years = (age) => `your ${age}`)(10);

Why does not work and if it is because of const?

And then another example, if I make:

const marco= { name: 'marco ccc',
  say hi: function () {
  return 'something';
  }
}

how would I convert sayHi into an arrow function?


Solution

  • Expressions get assigned to variables. Arrow functions are generally composed of 2 parts: the variable it's assigned to, and the body, eg:

    const foo = () => { ... }
    // ^ variable
                ^^^^ function body
    

    Initialization of variables can only be done as a statement, on a standalone line; the const can't be inside parentheses. You just need to separate out the variable the return value is being assigned to from (the function body and the call of the function):

    const years = ((age) => `your ${age}`)(10);
    //             ^^^^^^^^^^^^^^^^^^^^^^
    //             this is the function body
    //             that needs to be invoked immediately
    //                                     ^^ with the (10)
    //    ^^^^^    with the result assigned to `years`
    console.log(years);

    In an object, just replace function() with () => (and note that say hi isn't a valid object property in an object literal - either surround it in quotes, or use a single word instead):

    const marco = {
      name: 'marco ccc',
      sayHi: () => {
        return 'something';
      }
    };
    
    console.log(marco.sayHi());