-4

I recently encountered this code structure () => {} in the following code snippet

import { Server } from "socket.io";

const io = new Server(3000);

io.on("connection", (socket) => {
  // send a message to the client
  socket.emit("hello from server", 1, "2", { 3: Buffer.from([4]) });

  // receive a message from the client
  socket.on("hello from client", (...args) => {
    // ...
  });
});

But I don't understand what is this code structure? Have you any reference I could use to learn about it?

DarkBee
  • 16,592
  • 6
  • 46
  • 58
rider45
  • 83
  • 4
  • 4
    It's simple - That's not Python. – Bharel Apr 22 '22 at 06:03
  • 1
    this is javascript – juanpa.arrivillaga Apr 22 '22 at 06:05
  • 1
    `() => {}` this is an arrow function in JavaScript, Kind of lambda function in python but can contain multiple statements. – Abdul Niyas P M Apr 22 '22 at 06:05
  • Its just a short form for a function: `function (){ ... }`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Marc Apr 22 '22 at 06:41
  • Does this answer your question? [What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?](https://stackoverflow.com/questions/24900875/whats-the-meaning-of-an-arrow-formed-from-equals-greater-than-in-javas) – JΛYDΞV Apr 22 '22 at 06:48
  • 1
    This question has already been addressed on stack overflow. There is no need for anyone to repeat answering an already answered question, please visit the link that my account auto posted above. – JΛYDΞV Apr 22 '22 at 06:50
  • @Darkbee Wouldn't a duplicate have been the appropriate reason to close this? – JΛYDΞV Apr 22 '22 at 06:51
  • @jD3V on second thought yes, guess i paid to much attention to the `Have you any reference I could use` – DarkBee Apr 22 '22 at 06:52
  • @DarkBee, oh I see what you were looking at. I only asked, because I was wondering what you seen that prompted you to choose that reason. Obviously I only have 3.3k so I am still getting the hang of correctly using the privileges that were issued to me. – JΛYDΞV Apr 22 '22 at 16:35

1 Answers1

1

That's an arrow function used in javascript. You can get additional information here. Basically its equivalent with traditional functions would be:

import { Server } from "socket.io";

const io = new Server(3000);

io.on("connection", function (socket){
  // send a message to the client
  socket.emit("hello from server", 1, "2", { 3: Buffer.from([4]) });

  // receive a message from the client
  socket.on("hello from client", function (...args){
    // ...
  });
});
Erick Villatoro
  • 170
  • 1
  • 9