2

Actually, I'm working with someone else code and they used arrow function in a line. I'm having trouble to replace it with regular function.

This is the line:

const R = (elem) => object(document.querySelector(elem));

I've tried to change it like:

const R = function(elem) {
  object(document.querySelector(elem))
};

But no good result. :(

adiga
  • 34,372
  • 9
  • 61
  • 83
RIR360
  • 99
  • 1
  • 8
  • `return object(document.querySelector(elem))` [implicit return](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Function_body) – adiga Aug 02 '19 at 06:56

1 Answers1

4

Arrow functions have a built in way to shorten a return syntax: If an arrow function is simply returning a single line of code, you can omit the statement brackets and the return keyword. This tells the arrow function to return the statement. So the only thing you need to do is to add the return keyword explicit if you are not using an arrow function.

const  R = function(elem){ return object(document.querySelector(elem)) };

And be careful if you try to translate an arrow function which is using this keyword.

UPDATE: Response to comment

In the following code there are parenteses used to define an object with a function as property. If you don't use parenteses you need braces and return inside this arrow function, otherwise you get an SyntaxError.

const object = (elem) => ({
    css: function(attribute, value) {
        elem.style[attribute] = value;
        return object(elem);
    }
});

Without arrow functions it becomes:

const object = function(elem) {
    return {
        css: function(attribute, value) {
            elem.style[attribute] = value;
            return object(elem);
        }
    };
}
kai
  • 6,702
  • 22
  • 38
  • oh my god. I just forgot about that. But how can I change this? const object = (elem) => ({ css: function(attribute, value) { elem.style[attribute] = value; return object(elem); } }); – RIR360 Aug 02 '19 at 07:47
  • @RezowanIslamRizvy I updated the answer and answered your comment. – kai Aug 02 '19 at 08:09