Is it possible to use different names for the parameters in a function while still maintaining the same

(Apologies for any language barriers!) It's difficult to articulate my thoughts in English, but here is the code I've written:

function calculateAge(yearBorn){

    return 2020 - yearBorn;
}

var johnAge = calculateAge(1990);
var janeAge = calculateAge(2000);
var stevenAge = calculateAge(1998);

console.log(johnAge, janeAge, stevenAge);

function yearsUntilRetirement(currentAge, name){
    var age = calculateAge(currentAge);

    var retirementYear = 65 - age;

    console.log(name + ' retires in ' + retiredYear + ' years ');
}

yearsUntilRetirement(2000, "Alex");

This code functions perfectly fine and I'm curious as to why!

I have a function that calculates age (function calculateAge(yearBorn)) and I utilize it within another function called yearsUntilRetirement

In the first function, there's only one parameter defined as yearBorn, yet in the subsequent usage of the same function, a different parameter name calculateAge(currentAge) is employed instead of calculateAge(yearBorn). Surprisingly, it still works!

What exactly is happening here?

Can differing parameter names be used even if the function remains the same?

Answer №1

Consider the parameters as placeholders, eventually they are filled with a value. Whether you input 1 directly or store it in a variable like numberOne, the function will still receive the same value when executed.

For instance, let's take a look at a function named sum:

function sum(a, b) {
  return a + b;
}

Here are some ways you can use this function:

// Using integers directly
sum(1, 2);

// Utilizing variables
var firstNumber = 1;
var secondNumber = 2;

sum(firstNumber, secondNumber);

In both scenarios, upon running the sum function, the parameters a and b assume the values of 1 and 2 respectively. The naming convention of the parameters within the function does not impact the passed values.

It is important to remember that the sequence of the parameters is crucial. If you were to call sum(secondNumber, firstNumber), the values would be reversed which might lead to undesired outcomes. Hence, always pay attention to the order when invoking a function.

Answer №2

When a function is created, it requires a set of parameters:

function newFunction(input1){



}

When the function is called, you input a specific value into the call:

newFunction(value)

The magic happens here: the specified value will be assigned to input1 within your function. That's essentially what's happening.

Answer №3

Indeed, you are able to invoke a function repeatedly with various values for the parameters using distinct variable names.

function performAction(parameter) {
... carry out an action
}

height = 72; performAction(height);
weight = 160; performAction(weight);

Answer №4

When looking at the code below:

function findSquare(sideLength){

    return sideLength * sideLength;
}

The variable sideLength is essentially a temporary label. It holds no significance once outside of the function. The rest of the program is indifferent to what this particular variable is named within the function. All that matters is that the function requires one input parameter. Whatever value you provide when calling the function will be associated with that parameter and its variable name, effectively making it sideLength while inside the 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

Creating easy nested list views in React Native using object data structures

I am working with an array of objects that contains user data like this: const userList = [ { "firstName": "John", "lastName": "Doe", "date": "19 March 2018" }, { "firstName": "Anna", ...

When using AngularJS, encountered an issue where a view was not updating with new data from a $http request

When making a request to the 500px API using $http for popular photos, the response object is successfully returned. However, I am facing difficulty in pushing the retrieved photo items to the view. Below is my current controller code: meanApp.controller ...

Prompting Javascript Alert prior to redirection in ASP.NET

My current code is set up to display a message in an update panel while updating: string jv = "alert('Time OutAlert');"; ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", jv, true); It's working well in displaying the me ...

Issue with handling promise rejection of type error in node.js

Whenever I try running node server.js in Node.js, an error message pops up saying 'Cannot read property 'length' of undefined'. Despite installing all the necessary libraries (such as request) and browsing through various related posts ...

Is there a way to make Firebase Cloud Functions utilize ESLint?

Is there a specific command to activate ESLint for my cloud functions? Just to provide some context, I executed firebase init and completed the setup process, but it ended up using ESLint instead of TSLint which was unexpected. After that, I ran firebase ...

What is the reason behind V8's perplexing error notification?

When running this code on Chrome or Node (v8), an error message is displayed: Uncaught TypeError: f is not iterable function f(){} f(...undefined); Why is such an ambiguous error message generated in this case? Does it really have nothing to do with ...

Organizing your code with precision

I'm struggling with a project due to the poorly formatted code, making it almost impossible to read. Despite my attempts with various plugins and tools in VIM, Netbeans, Sublime Text 2, and Eclipse, the situation only seems to worsen. If anyone has ...

How can I input text into separate tabs using a specific method?

I've been struggling with this issue for a while now and here's the code I have so far: <html> <head> <script src="http://mihaifrentiu.com/wp-content/themes/mf/js/jquery_1.7.1.min.js" type="text/javascript"></scr ...

Is it possible to utilize the useRef Hook for the purpose of storing and accessing previous state values?

If you have already implemented the useState and useEffect Hooks for maintaining previous state, another approach is to utilize the useRef Hook to track previous state values as well. ...

Creating TypeScript modules for npm

I have been working on creating my first npm module. In the past, when I used TypeScript, I encountered a challenge where many modules lacked definition files. This led me to the decision of developing my module in TypeScript. However, I am struggling to ...

Steps for integrating WebRTC recording functionality with a Node.js server

Looking to develop a user-friendly video blogging solution that utilizes WebRTC technology for direct recording of video/audio within the browser, similar to Youtube's My_Webcam. The backend should be powered by Node.js. While exploring various Node. ...

Substitute the main node with the subordinate node within a json file

Here is a JSON object structure: { "coach": { "Errors": { "items": [ { "errorMessage": "You must select a date that is in the future.", "errorBOPath": "twl.date" ...

Is it possible that Typescript does not use type-guard to check for undefined when verifying the truthiness of a variable?

class Base {} function log(arg: number) { console.log(arg); } function fn<T extends typeof Base>( instance: Partial<InstanceType<T>>, key: keyof InstanceType<T>, ) { const val = instance[key]; if (val) { ...

Determine the percentage of payments, similar to Upwork, by leveraging the power

Currently, I am working on developing a percentage calculation similar to what is seen on the Upwork website. The calculation appears to be accurate when derived from the base amount at a rate of 10%. For instance, if we take a base amount of 89.00, the ...

Problem with Bootstrap 3 navbar on mobile devices - not tappable or responsive

After years of using Bootstrap, I've come across a new issue with my implementation of a Bootstrap 3 Nav. While testing on a desktop browser with device emulation, the nav collapses and functions properly. However, when tapping on the header on an ac ...

GULP showing an error message "ACCESS DENIED"

Exploring the fascinating realm of Gulp for the first time has been quite an adventure. I have managed to create a gulpfile that effectively handles tasks like reading, writing, and compiling sass/css/js/html files. However, when I try to access the site o ...

What is the reason why certain variables in req.body can be read by Express.js while others cannot?

Currently, I am not utilizing body-parser and it is clear that I need to incorporate it. My query pertains to the inconsistency in how my variables are being accessed through req.body without body-parser. Some of the variables display undefined values whil ...

Prevent additional clicks on the image

Currently, I am dealing with a situation where I have a list containing a jQuery handler for mouse clicks. The dilemma is that I need to insert an image into the list, but I want clicking on the image to trigger a different function than clicking elsewhere ...

What is the best method for obtaining user data when additional custom data is stored in Cloud Firestore?

Storing the user's information such as email, name, age, phone number, and uid is essential. In the user.model.ts file: export interface User { uid: string, name: string, email: string, phoneNumber: string, age: string } In auth. ...

Is there a way to fix the error "The requested resource does not have the 'Access-Control-Allow-Origin' header" within Express using Firebase functions?

Trying to send an email through nodemailer using Firebase functions, but encountering errors. The data for the email will come from a form. Error message: Access to XMLHttpRequest at 'my-firebase-functions' from origin 'my-angular-web-app&a ...