I was anticipating that the code would generate an undefined result, but it actually returned a function instead

Is anyone able to explain why this code is printing function when I expect it to print undefined? I am just starting out with JavaScript.

function createGreeter(greeting){
    function greet(){
        console.log(greeting,name)
    }
    return greet
}
    
let g1=createGreeter('Good Morning')
console.log(typeof g1)
let g2=createGreeter('Good Evening')

Answer №1

It seems like you're interested in creating a function that takes a greeting and returns another function that takes a name (while keeping a reference to the greeting variable in its outer lexical scope when returned) and combines those strings when the function is called.

// `createGreeter` function accepts a greeting string
// and returns a new function that takes a name input
// then, it concatenates both strings when called
function createGreeter(greeting) {
  return function (name) {
    return `${greeting}, ${name}.`;
  }
}

// Both of these functions return a greet function for a specific occasion
const goodevening = createGreeter('Good evening');
const expectingyou = createGreeter('I\'ve been expecting you');

// Now we can call these functions with a name argument
console.log(goodevening('Blofeld'));
console.log(expectingyou('Mr. Bond'));

Answer №2

Within the function greet, you are returning the function itself.

If you wish to store the result of the greet function in a variable, you must invoke it:

Instead of using return greet, consider using return greet()

Answer №3

Within the code, it is indicated on line 5 to return greet. The variable greet references the function greet itself. It might be advisable to adjust line 5 to return greet(), thereby triggering the execution of the greet() function and subsequently returning its result, which in this instance happens to be undefined.

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

Having trouble importing cubing.js into my discord bot running on node

When attempting to import the cubing.js module into my nodejs project for use in a discord.js bot, I encountered an error. The specific import causing issues was const {randomScrambleForEvent } = require('cubing/scramble'), resulting in 'Err ...

Step-by-step guide on activating a button only when all form fields are validated

My very first Angular 5 project. I've gone through resources like: https://angular.io/guide/form-validation and various search results I looked up, only to realize that they are all outdated. In my form, I have several input fields such as: <for ...

Enhance your .obj files by incorporating buttons using three.js

I am currently using three.js to load multiple obj files into a scene. These files combine to create a single unit. My objective is to enable users to customize the color of each part of this rendered unit. I am attempting to place buttons on each sectio ...

Remove a particular row from a database table

I'm facing an issue with my code. I want to be able to remove a row by clicking on a remove button within that row, but I'm unsure of how to accomplish this. <tbody id="myTable"> <?php if (!isset($_SESSION)){ ...

Encountering a VueJS error with Google Cloud Logging Winston: "TypeError: The 'original' argument must be a Function."

I have been attempting to integrate @google-cloud/logging-winston into my VueJS project by closely following the guidelines provided in both the npm package and Google Cloud docs. However, I am encountering an error message stating "TypeError: The &q ...

Morphing BufferGeometry in Three.js

Can two buffer geometries be morphed in three.js? Are there any helpful examples to explore for reference? I am particularly keen on learning about manual morphing using morph target influences. ...

Generating a component and rendering it according to the dynamic route parameters using mapStateToProps and reselect techniques

I have set up a global app container to store data for different rooms, with a sub-container called roomDetails that utilizes a reselect selector to pick a room from the global state based on ownProps.params.slug. This process is accomplished through mapSt ...

JavaScript Execution Sequence: Demystifying the Order of Operations

I am struggling to comprehend the order of execution in the following code snippet. It is a portion of a larger script, but it all begins with $( "#select-overlay" ). function findSelectedMap(mapID) { $.getJSON('maps.json', function (json) { ...

ES6 syntax does not allow for exporting routers

Looking to convert NodeJS modules (constant xxx = require('yyy')) into ES6 format, but encountering errors when exporting the router using the export syntax in ES6: throw new TypeError('Router.use() requires a middleware function but ...

Invoking an express route using JavaScript

After successfully defining some routes, including a text input search field at the top of the page, I created a listener function as shown below: $('#tags').keypress(function(e) { if (e.keyCode == 13 && document.getElementById('t ...

After successfully authenticating, you may introduce a new React component

Currently, I am working on a page that will only display information once a user has logged into their account. I have successfully implemented an authentication system using NodeJS, and now my goal is to restrict access to specific components or pages bas ...

Error: Attempting to access the 'street' property of an undefined value

My application loads a JSONPlaceholder data list of users, and I am attempting to enable editing of this data. However, I encounter an error: TypeError: Cannot read property 'street' of undefined Is there anyone who can provide assistance? c ...

How can I use Javascript / D3 to create a color scale mapping 5 hex colors to 17 colors?

If I start with the array of hexadecimal colors ['#1147FF', '#86D8FF', '#FFEF67', '#FF7D11', '#F30000'] in JavaScript, I can achieve the color scale I desire by adjusting the steps on the scales website fro ...

When stacking multiple geometries and utilizing EdgesHelper, edges may be inadvertently omitted

Having just started experimenting with three.js, I'm not entirely sure if I've made an error in my approach. You can view my demo here (use the left and right arrow keys to navigate): The issue I'm facing is that the "inner edges" are not ...

Automatically save using Jquery when there is a change in the input

Within my CMS (Wordpress) platform, I am implementing a colorpicker. <tr valign="top"> <th scope="row"><?php esc_html_e('Border Color', 'webthesign'); ?></th> <td valign="middle"> <input typ ...

Unable to store user data in the MongoDB Database

I'm currently facing an issue while trying to store user information in my MongoDB database. Everything was working fine until I implemented hashing on the passwords using bcrypt. After implementing password hashing, I am encountering difficulties in ...

Processing ajax requests in Rails 4 using HTML format

I'm currently in the process of setting up ajax functionality for my contact form and I am currently testing to ensure that the ajax call is being made. When checking my console, I noticed that it is still being processed as HTML and I cannot seem to ...

Develop a vector and embed it automatically in PHP

I am working on a program that automatically creates vectors based on client input in a function. The function retrieves data from the client, and if the client specifies they are from Tirana City, the function will generate a stack to store and manipula ...

Vue Js and form-data Event: A deeper look into handling form

Hey there #Vue.js2 I'm facing an issue while trying to create a function that is called within a form submit event. This particular function needs both the EVENT and ID as parameters. The problem arises when I call this function, as I am unable to spe ...

creating circular shapes with canvas functions

Creating a circle in my game seems to be more challenging than I anticipated. While there are numerous tutorials available, none seem to address my specific issue. The problem lies in where and how to draw the circle within my existing code: function start ...