15

I've just started getting accustomed with ES6 syntax and I was wondering if it was possible to assign to a variable with an arrow function. I'm writing a basic lightweight AJAX helper library and on a status of 200, I want to return a payload to the user, which I currently do with:

var responseData = "";
switch (payload.returnType.toLowerCase()) {
    case "json" : responseData = JSON.parse(httpRequest.responseText); break;
    case "text" : responseData = httpRequest.responseText; break;
    default : responseData = null; break;
}
callback(null, responseData);

This is fine, but I can't help but think I could make this cleaner, if I do:

callback(null, () => { switch(payload.returnType.toLowerCase()) { ... });

I would expect the return statement to send the result of the expression as the 2nd parameter in my callback, however when I console log from the caller it prints the switch statement.

Alternatively I have tried to do:

var responseData = () => {
    switch (payload.returnType.toLowerCase()) {
        case "json" : return JSON.parse(httpRequest.responseText); break;
        case "text" : return httpRequest.responseText; break;
        default : return null; break;
    }
}
callback(null, responseData);

In this case, responseData is always empty. Is it possible to have the return value as my 2nd parameter or have it bound to responseData as the result of the arrow function?

6
  • 1
    You create a function but do not execute the function.
    – Laurence
    May 14, 2016 at 14:55
  • You also have to actually return something - you dont need to return if you dont use {} but since your function has () => {} you need to return the value you want.
    – Neta Meta
    May 14, 2016 at 15:01
  • @NetaMeta yes sorry, I copy and pasted the first block in my answer, I know I need to return fromt he function to assign :)
    – Halfpint
    May 14, 2016 at 15:03
  • also as for your callback(null, () => { switch(payload.returnType.toLowerCase()) { ... }); this will also work if you execute it like so: callback(null, (() => { switch(payload.returnType.toLowerCase()) { ... }));
    – Neta Meta
    May 14, 2016 at 15:05
  • Just to make it crystal clear: Functions need to be executed to get their return value. May 14, 2016 at 16:02

3 Answers 3

13

You create an anonymous function but do not execute it.

For example:

var getResponseData = () => {
    switch (payload.returnType.toLowerCase()) {
        case "json" : return JSON.parse(httpRequest.responseText); 
        case "text" : return httpRequest.responseText; 
        default : return null;
    }
};
callback(null, getResponseData());
1
  • 9
    Thank-you, this worked perfectly, and then if I wanted to execute it within the parameter of callback I'd call it as a closure with (() => { ... })(); right?
    – Halfpint
    May 14, 2016 at 15:04
13

Even shorter with a self-executing function:

const res = (() => {
  return 'something'
})()

or even shorter if it's a one-liner:

const res = (() => 'something')()

Or with your code:

var getResponseData = (() => {
  switch (payload.returnType.toLowerCase()) {
    case "json" : return JSON.parse(httpRequest.responseText); 
    case "text" : return httpRequest.responseText; 
    default : return null;
  }
})();

You can clearly see the difference in this snippet:

const res1 = () => {
  return 'something'
}

const res2 = (() => {
  return 'something'
})()

const res3 = (() =>  'short something')()

console.log(res1)
console.log(res2)
console.log(res3)

2

I think your hunch is right, but you're on the wrong track, imho. What I think you want to do is create a map of response types to callbacks:

let parsers = new Map([
    ["json", JSON.parse], 
    ["text", (text) => text], 
    ["_", () => null]
]), t = payload.returnType.toLowerCase();

if (!parsers.has(t)) {
   t = "_";
}
callback(null, parsers.get(t)(httpRequest.responseText))

What makes this subjectively "cleaner" is that you separate logic from implementation. You can move the parser definition anywhere without affecting the code. That's why switch statements feel "unfunctional" (or undeclarative).

But of course, this all remains a matter of taste :)

6
  • If I use this, I get Iterator value json is not an entry object,
    – Halfpint
    May 14, 2016 at 15:17
  • I typed it out the top of my head, let me check for coding errors for a sec. (edit): oh wait I already see the first error, the pairs should be enclosed in an array as well. May 14, 2016 at 15:19
  • Thanks, I'm reading through the MDN docs on Map now, I really prefer this way over a boring switch...Got it working now, thanks again!
    – Halfpint
    May 14, 2016 at 15:20
  • yeah I think adding the array enclosure around the Map constructor's argument is the only error in there. May 14, 2016 at 15:23
  • What's the advantage of Map over a plan old hash?
    – user663031
    May 14, 2016 at 16:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.