Utilizing a function in Chrome Dev Tools

I am in need of clarification on a JavaScript concept that is confusing for me as a beginner. I have come across the following code snippet and I am having trouble understanding how it works:

function multiple(n) {
    function f(x) {
        return x * n;
    }
    return f;
}
var triple = multiple(3);
var quadruple = multiple(4);

Upon using the console to execute the following line of code:

console.log(triple(5));

I am getting the expected output, which is 15. This logic seems to work correctly with any number passed in (tripling or quadrupling based on the function used).

However, upon typing 'triple' into the console, I receive this block of code:

f(x) {
    return x * n;
}

Shouldn't the console instead display...

f(x) {
    return x * 3;
}

...as the number 3 is explicitly defined in the function by the statement:

var triple = multiple(3);

Answer №1

5 is never hardcoded into the function. The code snippet for g references the variable m, not the number 5. Although in this particular scenario, there is no mechanism to alter the value of m, consider a situation where it's possible to change m:

function multiply(m) {
    function g(y) {
        return y * m;
    }
    function modifyM(newM) {
        m = newM;
    }
    return { g: g, modifyM: modifyM };
}
var resultFor5 = multiply(5);
var quintuple = resultFor5.g;
var modifyQuintupleM = resultFor5.modifyM;

It's evident that m isn't hardcoded but treated as any other variable. In the given example, there might be limitations in changing the value of

m</code post execution of <code>multiply
, yet this doesn't imply that the contents within the closure formed by calling multiply are hardcoded in any manner.

Answer №2

By typing the keyword triple, you are simply displaying the original source code of your function.

The number 3 is hardcoded into the function through the following line of code.

This statement is incorrect. Passing a parameter to a function does not alter the source code of the function itself. To make changes to the source code, you would need to redefine the entire function. What you're actually doing is just passing in a value as an argument. The console output you see is correct.

When passing a parameter to a function, at runtime it essentially searches for the value stored at the memory address of that variable. However, this process does not involve rewriting the original source code of the function.

Answer №3

Essentially, the scenario is akin to having:

  var n = 3;
  function f(x) {
     return n * x;
  }

When you log f, you will observe the function as shown above. However, during its execution, the variable n retrieves its value from the nearest instance of n in the scope chain - in this case, n = 3, originating from the global context.

The intricacies of how the JavaScript engine stores the n variable within that closure (in your situation, the closure generated by the multiple function) remain unknown. Nonetheless, the key takeaway here is that variables inside a closure are retained via reference, not by value.

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

Tips for directing attention to a specific row with an input field in JavaScript

I duplicated a table and added an input field for users to search or focus on a specific row. However, there are two issues: When a user enters a row number, the table displays the wrong row - for example, if the user enters 15, the table shows row number ...

Enhancing traditional functions with Javascript annotations or decorators

Currently, I am in the process of developing a Next.js application, where I have defined an API as shown below: export default function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method === 'GET') { fn1Get(req, res); } e ...

SailsJs: Model.find().exec() can sometimes generate unexpected properties

I recently created a service function in api/services/SomeServices.js getCreditDebitNotes:function(vid){ console.log('resolving credit and debits'); var deferred=sails.q.defer(); CreditDebitNotes.find({vendorID:vid,status:1},{selec ...

Customizing the "added to cart" message in Woocommerce and setting up a notification system for customers

My main focus is on customizing the Woocommerce notation system for a personalized shopping cart experience. After some research, I stumbled upon a very helpful user response which suggested modifying the message by adding the following code snippet to th ...

Strange outcome in Three.js rendering

Is it possible to correct the reflection issue around the cycles? I noticed some strange results on my object and I've attached pictures to illustrate the problem. Current result in Three.js: https://i.sstatic.net/iJbpm.jpg https://i.sstatic.net/hv ...

My JavaScript code is functioning properly in jsfiddle, but when I try to run it on my own website, I encounter

Encountered an error message stating "Uncaught typeError: cannot call method 'hover' of null" following the line $('#nav li a').hover(function(){ in my JavaScript code. Check out the code on my site here: http://pastebin.com/GjZBEu3s Y ...

I am currently focusing on using websockets in combination with JavaScript and Golang servers to efficiently transmit files and

When front-end JavaScript websockets send a JSON object, it looks something like this: message_type: "1" to: "umesh" from: "moin" body: "" file: "{"filename":"reportesmtp.pdf" ,"fileextension":"application/pdf" ,"filesize":61813 ,"filedata ...

What is the best way to send data from a child functional component to a parent class component?

I am facing a situation where I have a parent class component and a child functional component. While there are examples available on passing values from a child class component to a parent class component, I am wondering how to pass a value from this type ...

Utilize the datepicker function in jQuery version 1.6.3 to select a range of dates

I need help adding a jQuery datepicker to my JSP page for selecting a date range. Below is the current code I am working with. $(function() { $( "#createdAtFrom" ).datepicker({ defaultDate: "+1w", changeMonth: true, ...

Steps for implementing CSS module with a dynamically generated class name

Recently, I started delving into the realm of CSS modules. My current project involves creating a slider that dynamically changes classes like "activeSlide", "nextSlide", and "lastSlide" to achieve different functionalities. However, I'm facing an is ...

Interactive hexagon shape with dynamic image content on click using a combination of CSS, HTML,

As a beginner in CSS, HTML, and JavaScript, I came across a code snippet to create a pattern of hexagons with images (refer to the first code below). My goal is to change the image displayed on a clicked hexagon to another picture (see second code). First ...

Displaying image behind bootstrap modal using Lightgallery js

Can anyone help me with an issue I'm having with previewing images using lightgallery js? The image is showing up behind the modal window. https://i.sstatic.net/FncZB.png I'm not sure why this is happening Here's the javascript code I am ...

What is the best way to calculate the total sum of the first element in each index of an array when using ng

I am looking to calculate the sum of the first elements from all indexes of an array using ng-repeat in AngularJS. My goal is to declare a variable and increment its value with each iteration of ng-repeat, then display that variable at the end. Below is ...

Parse a string containing a selection of markdown by using regular expressions for tokenization

I need to tokenize a string using a regular expression that consists of markdown formatting. Specifically, bold text is denoted by **text** and italic text is denoted by _text_. To tokenize the string "a _b_ c **d** _e", it should be split into ['a & ...

The use of asterisk (*) in importing dynamically

Hello everyone, I'm currently working on a project structure that looks like this: intranet ├── modules │ ├── storage │ │ ├── views │ │ └── route │ │ └── index.js │ │ │ ├── ...

"JavaScript code malfunctioning when using 'else if' statement for redirection functionality

Having some issues with this code. It's a basic validation script that checks if a field is empty and displays an error message. I'm new to this so struggling a bit. The validation part seems to be working but not the redirection. <body> & ...

I am having trouble displaying all the div elements with the same #id simultaneously

Click here for the code snippet The code provided seems to have a problem where hello2 and hello3 are not displaying. Is this issue related to the fact that '#id can only be used once'? Making it a class does not seem to work either. How can thi ...

What is the best way to retrieve the state from within a class method?

I'm having trouble accessing the redux state within this function in order to call Translator.init(data) whenever needed. Despite my efforts, I can't seem to access the state as expected. Since I'm more familiar with functional components th ...

Adjust the ng-show attribute in a different controller

I am attempting to toggle the visibility of a div using ng-show. Specifically, I have a navbar that should only be displayed in certain views. I have one controller managing the behavior of this div, and another controller where I want to manipulate the v ...

Setting up TailwindCSS in Nuxt3: A step-by-step guide

Looking to customize the default font Proxima Nova from TailwindCSS in my Nuxt3 project but navigating the file structure is a bit tricky for me. I've gone ahead and installed the tailwindcss module: npm i -D @nuxtjs/tailwindcss and added the module ...