What happens when you try to call a JavaScript function without any specified parameters

I've recently started learning about javascript and have been following a tutorial series that delves into the inner workings of sockets. You can check it out here.

The tutorial demonstrates the following code snippet:

var io = socket(server);
io.sockets.on('connection', newConnection);

function newConnection(socket){
    console.log('new connection' + socket.id);
}

I'm curious about how the 'newConnection' function works within the 'sockets.on'. It requires a 'socket' parameter, but seems to be a reference to the function itself. I've heard about callbacks before, but I'm still unclear on what's actually happening here. Could someone provide an explanation?

Answer №1

In the world of Javascript, functions are considered "first-class" objects which means they can be treated just like any other data type - passed as arguments, stored in variables, and so on. Let’s take a look at a simple example:

function greet(name) {
    console.log("Hello, " + name + "!");
}

function callGreet(func) {
    func("Alice");
}

callGreet(greet);

The last line here calls the function callGreet, passing in the function greet as an argument. Inside the callGreet function, it then calls the function func (which is essentially greet) with the argument "Alice".

The end result will be the message Hello, Alice! being displayed in the console.

This code snippet demonstrates how the on function will store the provided socket argument to be executed later, once a connection has been established.

Answer №2

When you pass your function to the socket.on method, it is similar to passing a variable. The code inside the socket.on can then utilize your function, including providing the necessary parameter.

An example of implementing the socket.on() method would look like this:

Socket.prototype.on = function (event, callback) {
    // other logic
    callback(socket); // passes socket to the newConnection function
}

So when you make the call:

io.sockets.on('connection', newConnection);

You are essentially passing your function newConnection as a callback. This name can be chosen by the programmer who wrote the socket.on. It will then execute your function as follows:

callback(socket); // Here, the callback is the second parameter
                  // in this case, it references
                  // the newConnection function

This means that the socket is passed to your function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determine whether a value is present in a JavaScript object in real-time while typing in a TextBox with the help of angular

Within a textbox, users have the freedom to input any value. Upon each keystroke, I must validate whether that value already exists in $scope.arrayObject. A common approach involves attaching a key-up event handler to the textbox and performing the necessa ...

What is the best method for passing page props in Next.JS?

One example is using the React Context API to pass props from the _app file to pages. Another scenario involves refactoring a ReactJS routing, where state is passed from app.js to pages through the route definition as shown below: <Route><Compon ...

My attempt at deploying my personal React App project on Vercel was unsuccessful

// encountering error during deployment on Vercel npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @testing-library/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e99b8c888a9da9d8da ...

Issue: Headers cannot be modified after being sent to the client - this occurs when making a request using Axios in React, not Postman

Whenever I send a request to the server using Postman, I don't encounter the "Cannot set headers after they are sent to the client" error. But when I integrate with React.js, this error keeps popping up. I'm looking for assistance in identifying ...

Encountering an error stating "ngbCollapse" is not a recognized property of "div" after relocating components to a sub module

Error compiler.js:215 Uncaught Error: Template parse errors: Can't bind to 'ngbCollapse' since it isn't a known property of 'div'. ("][ngbCollapse]="isHidden" In the process of organizing my code, I encountered an issue ...

Illuminate a corresponding regular expression within a text input

I currently have a functional code for testing regex, which highlights matching patterns. However, my challenge lies in highlighting the result within the same input as the test string. Below you will see the HTML and JavaScript snippets along with two ima ...

Transform a JSON array with keys and values into a structured tabular format in JSON

Looking to transform the JSON data below for a Chart into a format suitable for an HTML table: var chartJson = [ { header : '2016', values : [1, 5, 9] }, { header : '2017', values : [2, 4, 8] ...

AngularJS: incorporating modules across distinct controllers

Imagine we have two distinct AngularJS controllers housed in separate files that are both referenced in an HTML document. Here's how it looks: //controller1.js "use strict"; var someApp = angular.module('MYAPP'); //var someApp = angular.mod ...

Managing interactions with dynamically created buttons

Our Story Greetings! I am skilled in C# and VB.net, but I am diving into the world of Javascript and React. Currently, I am building a ticket purchase app to enhance my skills. While I was able to quickly create this app using Angular, React has posed mor ...

Switching up the content of an HTML page with JavaScript or JQuery: what you need

Is it possible to update HTML content using JavaScript or JQuery? https://i.sstatic.net/EWOXg.png I am trying to change the contents from 1 to 5 in a sequential order based on the time shown in the image. How can I achieve this using JavaScript or JQuery ...

New data row successfully added to HTML table, revealing an object display

When I click a button, a dialog box opens up. I can fill out the form inside the dialog box and submit it to insert a row into a table. After submitting the form, the newly inserted row displays as [object Object] immediately after submission: https://i.s ...

Comparing dynamic and static strings within objects using regex in JavaScript

Suppose there is an object with keys as strings containing dynamic values- let obj = { "/prodp/v1/engagemnt/{engID}/doc/{docID}": "roles_1", "/prodp/v1/engagemnt/{engID}/review/{reviewID}": "roles_2" } How can I find the value in the above object for the ...

What is the best way to access a promise's value in global scope within a reactjs application?

Currently tackling user authentication using web tokens in react. My approach involves utilizing the fetch() method to send a POST request to my backend, facilitating CORS. The issue arises when attempting to employ the setToken() hook within the .then() b ...

The hover effect on the ul element is not functioning as intended

Has anyone encountered issues with hovering over ul elements not working? http://jsfiddle.net/Samfr/5/ <ul class="navi"> <li> <a class='light'> Item1 <div class="hover-name" style="display:none"& ...

What could be causing React to throw an invalid hook error when using useRoutes?

I encountered an error while attempting to add a new route to my project. import React from "react"; import News from "./NewsComponents/News"; import Photos from "./PhotosComponents/Photos"; import Contact from "./Contact"; import Home from "./Home"; ...

Getting values for parameters using .attr("action") using JavaScript/jQuery - a beginner's guide

In my Ruby On Rails application, I have a form that is rendered like this: <%= form_tag myaction_path(item_id: item.id), { class: 'myaction', id: "myaction_#{item.id}", ...

Issue with Angular 6 subscribe event not being caught by subject?

A new element was crafted to house a loader: @Component({ selector: 'app-loader', templateUrl: './loader.component.html', styleUrls: ['./loader.component.scss'], providers: [LoaderService] }) export class LoaderCompon ...

Differences in behavior of jquery-ajax between Mozilla Firefox and Google Chrome

I am facing a peculiar issue. My current task involves using the Google Maps API to retrieve latitude and longitude data based on zip codes, with the following script: $(document).ready(function(){ $.ajax({ url:"http://maps.googleapis.com/maps/ ...

Stop HTML <dialog> from automatically closing using Vue

I'm working on a project where I need to use Vue to programmatically prevent an HTML dialog element from closing when the close event is triggered. Here's the code snippet I am currently using: import {ref} from 'vue'; const dialogTe ...

The process of reversing an array is not fully completing due to the pop method being used within a loop

Note: I've been immersed in code for hours now and have reached a stage where I'm starting to doubt the spelling of every word or question if I have dyslexia. Despite this, I know this should be a simple question. I want to create a basic functi ...