How to pass data to function by the name of the parameters? - javascript

I am new to JavaSscript. Basically, I do not want to pass my data by the position of those function parameters. This is inconvenient when there are 10 or more parameters.
I want to pass it by the parameter name defined in the function. However, there is a side-effect when I use this statement: my_func(param01=1). In my view, the usage of param01=1 inside the function call, only represents that 1 is passed to the parameter param01 and no effect happens outside the function call.
This is my code:
function my_func(param01) {
console.log('param01 inside my_func: ', param01)
}
param01 = 3
my_func(param01=1)
console.log('param01 outside my_func: ', param01)
// the result is 1 instead of 3.
My question is: What is the right way to pass data to function by the name of the function parameter?

Use destructuring assignment, In this case the function may accept 10 parameters but you don't need to order the parameters because the value inside the function will be retrieved using key name. Also the parameters can be in any order while calling the function.
function my_func({
param01,
param2,
param3
}) {
console.log('param01 inside my_func: ', param01, param3)
}
param01 = 0
my_func({
param01: 1,
param3: 4
})
console.log('param01 outside my_func: ', param01)

If you want 0 on the outside, but 1 on the inside, you are gonna have a bad time.
The zero you pass in is perfectly acceptable. If you want zero to be a no-no... you can use default operator || which evaluates values for truthiness left-to-right and short-circuits.
function my_func(param01) {
param01 = param01 || 1; // internal = 0 || 1 = 1
console.log('param01 inside my_func: ', param01) // >>> 1
}
param01 = 0 // global = 0
my_func(param01) // pass in the global 0, which IS VALID
console.log('param01 outside my_func:', param01) // >>> 0
Alternatively, you can pass in an object.
function my_func(params={}) {
console.log('param01 inside my_func: ', params.param01) // >>> 1
}
param01 = 0 // global = 0
my_func({ param01 : 1 }) // pass in a 1
console.log('param01 outside my_func:', param01) // >>> 0

I think the main problem here is a misunderstanding as to how parameters work in JavaScript. It looks like you come from a language where this statement:
my_func(param01=1)
Would pass a parameter called param0 with the value 1 to the function.
But in JavaScript this is what happens:
param01 is a variable outside of your function and you assign 1 to it
The result of that assignment expression is 1 so 1 is also passed the the function as a parameter
This explains why param01 is also 1 outside of your function.
In JavaScript you don't specify the parameter names when calling your function. So this works just the same:
my_func(1)
If you want to provide more parameters you have multiple options:
You simply separate them with a comma: my_func(1, 2, 3, 4, 5, 6)
Your function declaration must then look like this:
function my_func(param1, param2, param3, param4, param5, param6)
Or you could use the rest parameter syntax:
function my_func(...params)
This way you can pass as many arguments as you like and they will all be in the params array. You can then access them like this: param[0] for the first parameter, param[1] for the second and so on.
You can create an array with your values and pass the array as a parameter:
const parameters = [1, 2, 3, 4, 5 ,6];
my_func(parameters)
Your function declaration must then look like this:
function my_func(params)
As a side note on clean coding: Your function should have as few parameters as possible. If you have a lot of parameters this usually indicates that the function is doing too many things, thence violates the single responsibility pattern and should be split up into smaller functions.

Param name inside function declaring can be random, while the order is important. But you can use default parameter value in js, to set them by default:
function my_func(param01 = 1) {
console.log('param01 inside my_func: ', param01)
}

You need to define every function parameters like what Jenny and brk did in the comments above.
Jenny:
my_func(1, 2, 3, 4, 5, 6);
blk:
my_func({
param01: 1,
param3: 4
})
You cannot pass 10 or more parameters by the parameter name defined in the function if you don't teach the computer what the 10 or more parameters are.
Please clarify if I misunderstood your question.

Related

What is the difference between using only paranthesis and curly braces within paranthesis while defining function in ReactJS? [duplicate]

This question already has answers here:
Where can I get info on the object parameter syntax for JavaScript functions?
(1 answer)
What does this symbol mean in JavaScript?
(1 answer)
Closed 2 years ago.
I am new to React. Recently I came across an application wherein some function had the definition as:
async function (a, b) => {//body} which is quite understandable. But also in the same apllication some functions had the structure as async function ({a,b}) => {//body}. What is the difference between defining function between the above two methods?
The second example is destructuring the function arguments. It basically provides a shorter syntax for extracting an object key's value without the dot notation mess
Let's say you have an object
const myObject = { x: 1, y: 2 };
So, when you pass myObject to the function, you can call the variables without the dot notation. This makes the code easier to read.
function myFunction({ x, y }) {
//Here you can use directly x instead of myObject.x
}
You can read more about destructuring here
in the first function your parameter are 2 different variables
, in the second function they are parameters of the object you are passing
like
let Cat = {
name:"catty",
color:"gray"
}
secound example you pass the whole object like this
function ( Cat ) {}
function ( { name , color } ) {
/// here you can use name and color as "catty" and "gray"
}
if you use the first expample you would have to specify the parameters like this
function (Cat.name , Cat.color) {
}
the word async refers to waiting this function to call
In the first case, there are 2 arguments passed into the function, in the second the first argument passed into the function is an object which is being destructured.
const obj = { a: 1, b: 2 }
async function foo({ a, b }) => {
a; // 1
b; // 2
}
foo(obj);

How can this function work with a missing parameter

How can callback function work with one parameter when it requires 2 (selector and data) to go? Why doesn't it throw an error?
let links = document.querySelectorAll("a");
links.forEach(function(link){
link.addEventListener("click",function(e){
e.preventDefault();
ajax("get",e.target.href,render)
})
})
function ajax(url,metodo,callback){
let xhr = new XMLHttpRequest
xhr.open(metodo,url)
xhr.addEventListener("load",function(){
if(xhr.status==200){
callback(xhr.response)
}
})
xhr.send()
}
function render(selector,data){
document.querySelector(selector).innerHTML = data
}
In javascript, it is not necessary to call with same number of parameters as defined in function definition. If we do not define a default parameter value in function definition, then parameter becomes type of undefined.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters
Default function parameters allow formal parameters to be initialized
with default values if no value or undefined is passed.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
Starting with ECMAScript 2015, there are two new kinds of parameters:
default parameters and rest parameters.
Default parameters: In JavaScript, parameters of functions default to
undefined. However, in some situations it might be useful to set a
different default value. This is where default parameters can help.
In the past, the general strategy for setting defaults was to test
parameter values in the body of the function and assign a value if
they are undefined. If in the following example, no value is provided
for b in the call, its value would be undefined when evaluating a*b
and the call to multiply would have returned NaN. However, this is
caught with the second line in this example:
function multiply(a, b) {
b = typeof b !== 'undefined' ? b : 1;
return a * b;
}
multiply(5); // 5
With default parameters, the check in the function body is no longer necessary. Now, you can simply put 1 as the default
value for b in the function head:
function multiply(a, b = 1) {
return a * b;
}
multiply(5); // 5
For more details, see default parameters in the reference.
Rest parameters: The rest parameter syntax allows us to represent an
indefinite number of arguments as an array. In the example, we use the
rest parameters to collect arguments from the second one to the end.
We then multiply them by the first one.
function multiply(multiplier, ...theArgs) {
return theArgs.map(x => multiplier * x);
}
var arr = multiply(2, 1, 2, 3);
console.log(arr); // [2, 4, 6]
Argument Object:
Using the arguments object, you can call a function with more
arguments than it is formally declared to accept. This is often useful
if you don't know in advance how many arguments will be passed to the
function. You can use arguments.length to determine the number of
arguments actually passed to the function, and then access each
argument using the arguments object.
For example, consider a function that concatenates several strings.
The only formal argument for the function is a string that specifies
the characters that separate the items to concatenate. The function is
defined as follows:
function myConcat(separator) {
var result = ''; // initialize list
var i;
// iterate through arguments
for (i = 1; i < arguments.length; i++) {
result += arguments[i] + separator;
}
return result;
}
You can pass any number of arguments to this function, and it
concatenates each argument into a string "list":
// returns "red, orange, blue, "
myConcat(', ', 'red', 'orange', 'blue');
// returns "elephant; giraffe; lion; cheetah; "
myConcat('; ', 'elephant', 'giraffe', 'lion', 'cheetah');
// returns "sage. basil. oregano. pepper. parsley. "
myConcat('. ', 'sage', 'basil', 'oregano', 'pepper', 'parsley');
To make it throw error, if same number of argument is not passed in function, typescript can be used.

Javascript: Compose a function with argument placement instructions for each composition

I'm looking for a javascript function that can:
Condition (I)
compose another function when it does not have recursion in its definition, kind of like in maths when the function is given a power, but with multiple arguments possible in the first input - e.g. with a (math) function f:
f(x) := x+2
f5(x) = f(f(f(f(f(x))))) = x+10
Condition (II)
Or maybe even input custom arguments into each step of composition:
(52)2)2=
Math.pow(Math.pow(Math.pow(5,2),2),2) = Math.pow.pow([5,2],2,["r",2]])
//first arg set, how times the next, 2nd arg set - "r" stands for recursion -
//that argument will be occupied by the same function
//Using new solution:
_.supercompose(Math.pow,[[5,2],[_,2],[_,2]]) //-> 390625
2((52)3)=
Math.pow(2,Math.pow(Math.pow(5,2),3)) = Math.pow.pow([5,2],["r",2],["r",3],[2,"r"])
//Using new solution:
_.supercompose(Math.pow,[[5,2],[_,2],[_,3]]) //-> 244140625
_.supercompose(Math.pow,[[5,2],[_,2],[_,3],[2,_]]) //-> Infinity (bigger than the max. number)
Note: The above are just templates, the resulting function doesn't have to have the exact arguments, but the more close to this (or creative, for example, a possibility of branching off like this ->[2,4,"r",4,2,"r"], which would also be complicated) the better.
I've been attempting to do at least (I) with Function.prototype, I came up with this:
Object.defineProperty(Function.prototype,"pow",{writable:true});
//Just so the function not enumerable using a for-in loop (my habit)
function forceSlice(context,argsArr)
{returnArray.prototype.slice.apply(context,argsArr)}
Function.prototype.pow = function(power)
{
var args=power<2?forceSlice(arguments,[1]):
[this.pow.apply(this,[power-1].concat(forceSlice(arguments,[1])))];
return this.apply(0,args);
}
//Usage:
function square(a){return a*a;}
square.pow(4,2) //65536
function addThree(a,b){return a+(b||3); }
// gives a+b when b exists and isn't 0, else gives a+3
addThree.pow(3,5,4) //15 (((5+4)+3)+3)
Worst case, I might just go with eval, which I haven't figured out yet too. :/
Edit: Underscore.js, when played around with a bit, can fulfill both conditions.
I came up with this, which is close to done, but I can't get it to work:
_.partialApply = function(func,argList){_.partial.apply(_,[func].concat(argList))}
_.supercompose = function(func,instructions)
{
_.reduce(_.rest(instructions),function(memo,value)
{
return _.partialApply(_.partialApply(func, value),memo)();
},_.first(instructions))
}
//Usage:
_.supercompose(Math.pow,[[3,2],[_,2]]) //should be 81, instead throws "undefined is not a function"
Edit: jluckin's cleareance of terms (recursion-> function composition)
Edit: made example function return number instead of array
The term you are looking for is called function composition, not necessarily recursion. You can apply function composition in javascript easily since you can pass a function as an argument.
I created a small function called compose, which takes a function, an initial value, and the number of times to compose the function.
function compose(myFunction, initialValue, numberOfCompositions) {
if (numberOfCompositions === 1) {
return myFunction(initialValue);
}
else {
return compose(myFunction, myFunction(initialValue), --numberOfCompositions);
}
}
When this function is evaluated, you pass in some function f(x), some initial x0, and the repeat count. For example, numberOfCompositions = 3 gives f(f(f(x)));
If there is one composition, then f(x) is returned. If there are two compositions, compose returns f(x) with f(x) replacing x as the argument, with 1 passed in as the composition so it will evaluate f(f(x)).
This pattern holds for any number of compositions.
Since functions are treated as objects and can be passed as arguments of functions, this method basically wraps your "non-recursive" functions as recursive functions to allow composition.
Success(simplicity wins):
_.supercompose = function (func,instructions,context)
{
var val;
for(var i = 0; i < instructions.length; i++)
{
val = _.partial.apply(_,[func].concat(instructions[i])).apply(context||this,val?[val]:[]);
}
return val;
}
//Usage (with a function constructor for operations):
_.op = function(o){return Function.apply(this,"abcdefghijklmnopqrstuvwxyz".split("").concat(["return " + o]))}
_.op("a+b")(3,5) //-> 8
_.op("a*b")(3,5) //-> 15
_.supercompose(_.op("(a+b)*c*(d||1)"),[[1,2,3],[-5,_,1],[1,2,_,3]])
//-> (1+2)*((-5+((1+2)*3))*1)*3 -> 36

What is the difference between arguments and parameters in javascript?

I know that a parameter is a variable passed to a function and gives value to the argument in the function, but I'm having trouble understanding:
What is the main difference between "arguments" and "parameters" in javascript?
The parameters are the aliases for the values that will be passed to the function. The arguments are the actual values.
var foo = function( a, b, c ) {}; // a, b, and c are the parameters
foo( 1, 2, 3 ); // 1, 2, and 3 are the arguments
When you define a function, the variables that represent the values that will be passed to it for processing are called parameters. For example, the following function definition has one parameter called $number:
function doubleIt($number) {
return $number *= 2;
}
However, when you use a function, the value you pass to it is called an argument. So, in the following case, $price is passed as the argument to doubleIt():
$price = 50;
$inflated_price = doubleIt($price); // 100
parameters (if any) define the method signature.
Arguments are values passed into a function.
But same difference I guess.
void function(int param1, string param2) //defines the types the function must receive.
function(1, "Hello World") 1 and "Hello World" are passed as arguments. The parameter receives (if you like) the argument.
It is explained well here
13 Function Definition
Syntax
FunctionDeclaration :
function Identifier ( FormalParameterList (opt) ) { FunctionBody }
FunctionExpression :
function Identifieropt ( FormalParameterList (opt) ) { FunctionBody }
FormalParameterList :
Identifier
FormalParameterList , Identifier
FunctionBody :
SourceElements (opt)
Officially they are called parameters, but the actual arguments are given in the same called object. However, both words are interchangeable.
Parameters are properties of a function.
Arguments are properties of a particular call to a function.
In javascript, if you don't give a number of arguments equal to the number of parameters, the extra come across as undefined.
function f(a,b,c) // 3 parameters
f(1) // 1 argument given; inside the function f, a will be 1, and b and c will be undefined
so parameters works just like a place holder for your arguments
when you going to call the function to give it a value you will give the function a value and that value stored in the place of parameter1 and parameter2
function add (parameter1 , parameter2 ) {
return parameter1 + parameter2;
}
add(10 (argument 1), 20 (argument2 ))

What is this javascript code doing?

this.String = {
Get : function (val) {
return function() {
return val;
}
}
};
What is the ':' doing?
this.String = {} specifies an object. Get is a property of that object. In javascript, object properties and their values are separated by a colon ':'.
So, per the example, you would call the function like this
this.String.Get('some string');
More examples:
var foo = {
bar : 'foobar',
other : {
a : 'wowza'
}
}
alert(foo.bar); //alerts 'foobar'
alert(foo.other.a) //alerts 'wowza'
Others have already explained what this code does. It creates an object (called this.String) that contains a single function (called Get). I'd like to explain when you could use this function.
This function can be useful in cases where you need a higher order function (that is a function that expects another function as its argument).
Say you have a function that does something to each element of an Array, lets call it map. You could use this function like so:
function inc (x)
{
return x + 1;
}
var arr = [1, 2, 3];
var newArr = arr.map(inc);
What the map function will do, is create a new array containing the values [2, 3, 4]. It will do this by calling the function inc with each element of the array.
Now, if you use this method a lot, you might continuously be calling map with all sorts of arguments:
arr.map(inc); // to increase each element
arr.map(even); // to create a list of booleans (even or odd)
arr.map(toString); // to create a list of strings
If for some reason you'd want to replace the entire array with the same string (but keeping the array of the same size), you could call it like so:
arr.map(this.String.Get("my String"));
This will create a new array of the same size as arr, but just containing the string "my String" over and over again.
Note that in some languages, this function is predefined and called const or constant (since it will always return the same value, each time you call it, no matter what its arguments are).
Now, if you think that this example isn't very useful, I would agree with you. But there are cases, when programming with higher order functions, when this technique is used.
For example, it can be useful if you have a tree you want to 'clear' of its values but keep the structure of the tree. You could do tree.map(this.String.Get("default value")) and get a whole new tree is created that has the exact same shape as the original, but none of its values.
It assigns an object that has a property "Get" to this.String. "Get" is assigned an anonymous function, which will return a function that just returns the argument that was given to the first returning function. Sounds strange, but here is how it can be used:
var ten = this.String["Get"](10)();
ten will then contain a 10. Instead, you could have written the equivalent
var ten = this.String.Get(10)();
// saving the returned function can have more use:
var generatingFunction = this.String.Get("something");
alert(generatingFunction()); // displays "something"
That is, : just assigns some value to a property.
This answer may be a bit superflous since Tom's is a good answer but just to boil it down and be complete:-
this.String = {};
Adds an object to the current object with the property name of String.
var fn = function(val) {
return function() { return(val); }
}
Returns a function from a closure which in turn returns the parameter used in creating the closure. Hence:-
var fnInner = fn("Hello World!");
alert(fnInner()); // Displays Hello World!
In combination then:-
this.String = { Get: function(val) {
return function() { return(val); }
}
Adds an object to the current object with the property name of String that has a method called Get that returns a function from a closure which in turn returns the parameter used in creating the closure.
var fnInner = this.String.Get("Yasso!");
alert(fnInner()); //displays Yasso!

Categories

Resources