Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"=>" operator in JavaScript

Tags:

javascript

I mixed up Ruby with JavaScript syntax when trying to declare an associative array in JavaScript.

>>> [a => b, c => d]

This results in a valid array and

>>> JSON.stringify([a => b, c => d])

returns "[null,null]" and

typeof(a) === "undefined" // true
typeof(b) === "undefined" // true
typeof(c) === "undefined" // true
typeof(d) === "undefined" // true

What does this syntax mean?

like image 378
JohnJohnGa Avatar asked Aug 17 '26 03:08

JohnJohnGa


1 Answers

That's the syntax for ES6's arrow function, which is both a shorthand and sets the values of this lexically. It uses the following syntax:

argument => returnValue

It can also be used with multiple arguments or with a function body (which makes a return statement needed for a non-void function):

() => 1
(arg1, arg2) => 2
argument => { return 3; }

The return value is implicit, which is why it appears to work. While this is still experimental, Firefox has implemented this, though other browsers have not yet done so.

The reason why you're getting "[null]" is that functions cannot be represented in JSON, so they are converted to null for serialisation purposes.

like image 101
Qantas 94 Heavy Avatar answered Aug 18 '26 19:08

Qantas 94 Heavy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!