Is it possible to attach a nested function to a parameter of the parent function in JavaScript?

Here's a query that might appear basic and straightforward. It could even be a repeated question, as I struggled to use the correct keywords in my search.

The puzzle seems to lie in why this code snippet functions correctly:

let rAMessage = 'Ride along, everyone!'

let messageNum = 5

function computeNumber() {
      return 5+5
    }

function RideAlong(message, number = computeNumber()) {
    alert(`${message} + ${number}`)
}

RideAlong(rAMessage)

However, this alternate version doesn't produce the desired outcome:

let rAMessage = 'Ride along, everyone!'

let messageNum = 5

function RideAlong(message, number = computeNumber()) {
    function computeNumber() {
      return 5+5
    }
    alert(`${message} + ${number}`)
}

RideAlong(rAMessage)

Is there a possible solution to make it functional?

Answer №1

The desired functionality of the second function is not entirely clear. However, it appears that you intend to allow for a number argument with the default value being the result of computeNumber, which is not defined outside the function. To achieve this, it would be advisable to compute the default value within the function itself:

let welcomeMessage = 'Welcome aboard everyone!'

function WelcomeAboard(message, number) {
    function computeNumber() {
      return 6 + 4
    }
    if (number === undefined) number = computeNumber()
    console.log(`${message} + ${number}`)
}

WelcomeAboard(welcomeMessage)

WelcomeAboard(welcomeMessage, 3)

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

Retrieve the "ready" event following the addition of HTML code

I wanted to share my jsfiddle with you all Check out this JSFiddle link $('#myP').click(function() { GetMap(); }); function GetMap() { var text = '<html lang="en"> <head> <link rel="stylesheet" href="https://cdn.r ...

When using Express.js for file uploading, it is important to first verify that a file has been sent, set a maximum file size limit, and ensure

After working with expressjs for a month, I've encountered some issues with file uploads. Despite researching on Google and various blogs, I haven't been able to find answers to the following three questions: What do I need to do or what setting ...

PHP is encountering issues when attempting to dynamically add rows using JavaScript

I have created this HTML code to dynamically generate rows: <tr > <td><?php echo $row['qty'];?></td> <td class="record"><?php echo $row['prod_name'];?></td> <td><input type ...

Incorporating a timer feature into the code for my memory game

Seeking the optimal method to incorporate a timer into my memory game. This game comprises numerous squares, and when the user successfully completes it, a modal appears congratulating them on their win and providing an option to restart the game. The obj ...

NPM encountered difficulties in resolving the dependency tree

I seem to be encountering a persistent issue that I cannot resolve on my own. My attempt to update webpack and webpack-cli in a project has been met with repeated errors of this nature: npm install webpack@latest --save-dev npm ERR! code ERESOLVE npm E ...

implementing key strokes instead of buttons in django forms

I am currently working on a website where users can enter text, vote on entries, and view live tables of the most popular submissions. You can check out the site here: This project is coded using django. I have successfully implemented a text entry form a ...

The map component in React is currently displaying all images for every project, rather than just the images for the designated project

Currently, I am developing a portfolio website using React. I am facing an issue where upon clicking 'view more' on a project card, instead of displaying specific images for that project, all the images are being shown in the pop-up. How can I re ...

Learn how to retrieve an API response from a different domain by carefully reviewing the following instructions

I am trying to retrieve a response from the following URL using the ajax/getjson method: However, I am facing an issue where JavaScript is not allowing me to communicate with the above URL because it is not generating JSON data. I have attempted to use da ...

Guide for accessing Javascript documentation via console?

There are many times when I am coding in Python, that I find myself wanting to quickly access the documentation for a function. In the iPython console, I can easily do this by entering dir?? which retrieves the documentation for the dir function. Is ther ...

Execute a node script file at random intervals

I've been utilizing forever to maintain the continuous execution of a node script: forever start script1.js However, my requirement is to run these files in a random order... For instance: Execute node script1.js Execute node script2.js Run script ...

Image not yet clicked on the first try

I am encountering an issue with my image gallery. Currently, when I click on a thumbnail, the large image is displayed. However, I would like the first image to show up without requiring the user to click on its thumbnail. How can I address this problem? B ...

What is the best way to adjust the Directions route Polyline to the edge of the map canvas?

I am currently working on a project that involves direction mapping, and I need the directions to be displayed on the right side of the panel when rendered. Here is what I am currently getting: https://i.sstatic.net/AMgA8.png However, I do not want the di ...

"Combining the power of JavaScript countdown with PHP date functionality

I have a JavaScript code that generates countdowns based on the user's PC date. I'm looking for a way to modify the script to use a specific timezone like: <?php date_default_timezone_set('Ireland/Dublin'); $date = date('m/d/Y ...

What is the process for incorporating a compiled JavaScript library into a TypeScript project?

In my Typescript project (ProjectA), I am utilizing several node packages. Additionally, I have a babel project (ProjectB) with a build configuration that supports output for multiple module definition standards such as amd, common.js, and esm. My questio ...

Removing elements based on the size of the display

I need assistance with a JavaScript issue. I have a table with 2 rows and 5 columns, each column representing a day of the week with a specific class. The goal is to detect the current day based on the browser's width/height and remove all elements in ...

Identifying Errors in Meteor's Data Publications

I am currently working on a web application using Meteor and AngularJS 2. Take a look at the publication function below: Meteor.publish('abc', function () { // For throwing the meteor error according to the condition if(!this.userId) throw new ...

Select an item from the options available

Looking to automatically select a specific item from a combobox upon clicking a button on my webpage. The page includes both PHP and JavaScript code for this functionality. Currently, I have a JavaScript function triggered by the "onclick" event of the bu ...

JavaScript function following AJAX request

I'm attempting to invoke a JavaScript function that is returned in an Ajax call What is the proper way to run a JavaScript function received from an Ajax call? Consider this script before the Ajax call <script> function start(){ console.l ...

What is the best way to monitor React hooks efficiently?

Prior to diving into a new React project, I always make sure that there are adequate developer tools available for support. One of my favorite features in React is the React Developer tool for Google Chrome. It allows me to examine the internal state of e ...

One way to create a unique JavaScript Module Pattern that retrieves the default value of a

I'm struggling to retrieve the latest private property from a Module, as I keep getting the initial value instead of the most recent one. Upon submission of the form and triggering onSuccess, I assign partnerId = 10. Subsequently, upon clicking an e ...