Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "=>" mean in JavaScript? [duplicate]

Tags:

javascript

Here is the code:

function accum(s) {
  return s.split('').map((x,index) => x.toUpperCase()+Array(index+1).join(x.toLowerCase())).join('-');
}

I would like to know what "=>" is. This function takes a string and for the index number of each element it adds that many elements to the output. Here's an example:

accum("abcd") --> "A-Bb-Ccc-Dddd"
accum("RqaEzty") --> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
accum("cwAt") --> "C-Ww-Aaa-Tttt"
like image 256
MortiestMorty Avatar asked Jul 15 '16 21:07

MortiestMorty


People also ask

What does => mean in JS?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

How do I duplicate a string in JavaScript?

JavaScript String repeat() The repeat() method returns a string with a number of copies of a string. The repeat() method returns a new string. The repeat() method does not change the original string.

What does arrow mean in JS?

In short, with arrow functions there are no binding of this . In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever. With arrow functions the this keyword always represents the object that defined the arrow function.


1 Answers

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

So in your case

s.split('')

splits the input on empty spaces and for each element of the resulted array you apply the following function:

(x,index) => x.toUpperCase()+Array(index+1).join(x.toLowerCase())

The left part is the random element, x of the array (s.split('')) and it's corresponding index. The second part applies a transformation to this input.

like image 134
Christos Avatar answered Oct 03 '22 13:10

Christos