3

So Im very new to ES6 and would love to know if there is a simpler way to return the string than having to try and figure out the order, I enjoy this method but I find that with large strings its quite a bit of torture. Please can anyone shoot me in the right direction ? Also Is it possible to use Arrow function for this function ?

function text(strings, ...values){
        if(values[3]>200){
          values[2] = "realy fast up too"
        }else{
          values[2] = "super slow up too"
        }
        return `${strings[0]}${values[0]} ${values[1]}${strings[1]}${strings[2]}${values[2]} ${values[3]}${strings[3]}${strings[4]}${strings[5]}${values[4]}`;
      }

      let sentance = text`Your ${this.color} ${this.cartype}can drive ${""} ${this.speed}Km/H while going ${this.carsound(carS)}`;

Also I tried using an arrow function like this below but I get an compile error (Unexpected token) on line 16 which is the first line you see

text(strings, ...values)=>{
        if(values[3]>200){
          values[2] = "realy fast up too"
        }else{
          values[2] = "super slow up too"
        }
        return `${strings[0]}${values[0]} ${values[1]}${strings[1]}${strings[2]}${values[2]} ${values[3]}${strings[3]}${strings[4]}${strings[5]}${values[4]}`;
      } 
3
  • 1
    There is no reason for using arrow functions for this. And I suggest using a loop. Commented Aug 28, 2015 at 13:09
  • For the arrow function, try let text = (strings, ...values) => ... Commented Aug 28, 2015 at 13:14
  • Excellent thanks guys. Help very appreciated. Commented Aug 28, 2015 at 13:35

1 Answer 1

1

I would do something like this if using jQuery

let text = (strings, ...values) {
    // code
    return $.map(strings, function(v, i){ return v + values[i]; }).join(' ');
}

arrow function is an anonymous function, You just can't use it as you use a function. You would have to assign it to a var, like so;

let text = (strings, ...values)=> { ... }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much Rafael, that worked awesome. I will have a read on the jQuery .map function to understand how it works in-depth. But thanks again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.