An argument with default value precedes non-default argument in JavaScript [duplicate] - javascript

This question already has answers here:
Set a default parameter value for a JavaScript function
(29 answers)
Closed 11 months ago.
In JavaScript it's possible to define a function like this:
function func(a = 10, b)
{
return a + b;
}
How does one call this function by only specifying the value for b?

It'd only be possible by explicitly passing undefined, and by also providing a default for the second argument.
function func(a = 10, b) {
return a + b;
}
console.log(func(undefined, 5));
But this is quite weird - it's very confusing. I'd highly recommend not doing this at all - either put the arguments with default values at the end, or in an object.
function func({ a = 10, b }) {
return a + b;
}
console.log(func({ b: 5 }));

If you are okay with currying the first parameter:
bind saves the function with the arguments supplied, so when one calls it, it calls it with the arguments applied. The first argument is what to bind this to, so the second argument will bind to a:
function func(a, b) {
return a + b;
}
newFunc = func.bind(null, 10)
newFunc(2)
12

Related

Is having the first JavaScript parameter with default value possible? [duplicate]

This question already has answers here:
es6 how to use default parameters that go before non-default parameters?
(4 answers)
Closed 2 years ago.
It's practical to have the last parameter with a default value, as follows.
function add(x, y = 5) {
return x + y;
}
console.log(add(3)); // results in '8'
However, is it possible to have other than the last parameter with a default value? If so, how would you call it with the intention of using the first default value, but providing the second parameter?
function add(x = 5, y) {
return x + y;
}
console.log(add(,3)); // doesn't work
You still need to provide the first parameter regardless of its default value.
Try destructuring a single parameter instead, like this:
function add({ x = 5, y }) {
return x + y;
}
console.log(add({ y: 3 })); // results in '8'
You will still have to specify the y key, though, but this is a way better practice. 😄
You still could keep your add function the same by call it with params from destructed array like below snippet
function add(x = 5, y) {
return x + y;
}
console.log(add(...[,3]));

Modify arrow function javascript [duplicate]

This question already has answers here:
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
(14 answers)
Closed 6 years ago.
I have the following arrow function
if( rowCheckStatuses.reduce((a, b) => a + b, 0) ){}
rowCheckStatuses is an array of 1's and 0's, this arrow function adds them all up to produce a number. This number acts as a boolean to determine whether or not there is at least one "1" in the array.
The issue is, I don't really understand how arrow functions work, and my IDE thinks it's bad syntax and refuses to check the rest of my document for syntax errors.
How would I go about converting this to a regular function to alleviate both issues?
An arrow function can usually be converted by replacing
(<args>) => <body>
with
function(<args>) { return <body>; }
So yours would be
rowCheckStatuses.reduce(function(a, b) { return a + b; }, 0)
There are exceptions to this rule so it's important that you read up on arrow functions if you want to know all of the differences. You should also note that arrow functions have a lexical this.
You can refactor it as:
if( rowCheckStatuses.reduce(function(a, b){return a + b}, 0)
The initial accumulator isn't necessary (unless you expect the array to be empty sometimes), it could be:
if( rowCheckStatuses.reduce(function(a, b){return a + b})
This number acts as a boolean to determine whether or not there is at least one "1" in the array
It might be faster (and clearer) to use:
if( rowCheckStatuses.some(function(a){return a == 1}))
which will return true if there are any 1s in rowCheckStatuses and will return as soon as one is encountered. Another alternative is indexOf:
if( rowCheckStatuses.indexOf(1) != -1)
Lots of alternatives.
Replacing arrow functions with regular functions is usually unproblematic:
var f = x => y;
var g = function(x) { return y; }
Or, in your specific example:
rowCheckStatuses.reduce((a, b) => a + b, 0);
rowCheckStatuses.reduce(function(a, b) { return a + b; }, 0);
However, be aware of the exceptions:
Arrow functions don't bind a this value. Accessing this in an arrow function might thus return the value of the enclosing execution context's this:
function MyClass() {}
MyClass.prototype.f = () => this;
MyClass.prototype.g = function() { return this; }
myClass = new MyClass();
console.log(myClass.f()); // logs `Window`
console.log(myClass.g()); // logs `myClass`
Arrow functions also don't have access to a local arguments object. Accessing arguments in an arrow function might e. g. return the arguments of an enclosing function:
function test() {
var f = () => arguments;
var g = function() { return arguments; }
console.log(f()); // logs test's arguments
console.log(g()); // logs g's arguments
}
test('x');
The same holds for new.target and super. See also What are the differences (if any) between ES6 arrow functions and functions bound with Function.prototype.bind?

Concept about anonymous function and invoke in javascript [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 4 years ago.
Now I have to solve a exercise in the exercise from freecodecamp.
The outcome are expected as follows:
addTogether(2, 3) should return 5.
addTogether(2)(3) should return 5.
addTogether("This is sth") should return undefined.
addTogether(2, "3") should return undefined.
addTogether(2)([3]) should return undefined.
And by referring to some suggested solutions, one of the solutions is like:
function add(){
var args= [].slice.call(arguments);
if (!args.every(function(argument){return typeof argument === 'number';})){
return undefined;
}
if(args.length === 2){
return args[0] + args[1];
} else {
var a = args[0];
var addOne = function(b){
return add(a,b);
};
return addOne;
}
return false
}
add(2)(3)
In here, I am not really sure, why in the variable addOne, the anonymous function will successfully capture the the value in the second brackets, after calling the first value before?
I seek for the information about JavaScript function invocation, but still do not 100% sure why...
Edited:
With the features of closure, because I have already extracted the first parentheses, the next closure i.e the function, will automatically take the second input? And in this case, if I want to do addTogether(2)(3)(4)(5) , then I can do that by creating closures within different parentheses e.g
var a = args[0];
var addOne = function(b){
var addTwo = function(c){
var addThree = function(d){
return a+b+c+d;
}
}
};
Do I understand in the correct sense?
In here, I am not really sure, why in the variable addOne, the
anonymous function will successfully capture the the value in the
second brackets, after calling the first value before?
Because, when you say, addTogether(2), it means you're calling a function and passing it an integer 2, and when you say addTogether(2)(3), it means, you're calling a function and passing it an integer 2, which is then returning a function, to which you're passing the integer 3.
So, when the code says return addOne, it is returning the function which is called with the second parentheses, (3), so addTogether gets the value 2 and the return of addTogether, which is addOne gets the value 3.

Pass in any number of arguments into a Javascript function [duplicate]

This question already has answers here:
JavaScript variable number of arguments to function
(12 answers)
Closed 5 years ago.
I want to be able to pass in any number of arguments into a function and then be able to use those arguments later. I know I can pass in default arguments but I don't know what to declare in my function.
For example,
function test(????) {
console.log(a)
console.log(b)
console.log(c)
}
test(a="a", b="b", c="c")
I'm also challenged by being given this function and to make as little changes to the var declarations as much as possible. So here, variables, a, b, and c are declared and I'm not able to edit these variables. I should be able to pass in arguments that will then know to assign itself to these variables.
function test(???) {
var a,b,c
if (a>b){
c = a + b
}
}
test(a=2,b=3)
You actually don't need to define any arguments in the function parameters. All you need to do is access javascript's built in arguments object.
So your code could look like the following:
function test() {
var a = arguments[0];
var b = arguments[1];
var c = arguments[2];
console.log(a);
console.log(b);
console.log(c);
}
test("a", "b", "c");
For reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
Using an array is a good idea, but in the interest of completeness...
The ES6 way!
If you're able to support ES6 features, the spread operator combined with the arguments keyword is a neat way to get around that:
function anyNumber() {
console.log(...arguments); // -> 1 2 3 4
let argsAsArray = [0, ...arguments, 5]; // now they're an array
argsAsArray.forEach(s => console.log(s)); // -> 0 1 2 3 4 5
};
anyNumber(1,2,3,4);
There are a lot of cool things you can do with the spread operator, especially with object and parameter destructuring.
you could pass in an object or an array:
function test1([a, b, c]) {
// ...
}
test1([1, 2, 3]);
function test2({ a, b, c }) {
// ...
}
test2({ a: 1, b: 2, c: 3 });
function test(input) {
console.log(input.a);
console.log(input.b);
console.log(input.c);
}
test({ a: 1, b: 2, c: 3 });
You should use an array or an object.
In that array add as many arguments you want.
function test(arr) {
console.log(arr.a);
console.log(arr.b);
console.log(arr.c);
}
arr = {}
arr.a = "a";
arr.b = "b";
arr.c = "c";
k = test(arr);
Given javascript at updated Question, you can define default parameters within () following function name.
function test(a = 2, b = 3) {
let c;
if (a > b) {
c = a + b
} else {
c = 0
}
console.log(c);
}
test(); // 0
test(4); // 7
See also Can we set persistent default parameters which remain set until explicitly changed?

can I override in Javascript?

How can I create an object like that
var sum = {
a : 5,
b : 7,
sumar : function()
{
return (this.a+this.b);
},
sumar : function(a, b)
{
return (a+b);
}
}
and then use any of the methods declared like this?
sumar0 = sum.sumar(); //use the method without parameters
sumar1 = sum.sumar(6,7); //use the method with parameters.
Just like "overriding" the methods? is this possible?
Thanks in advance and sorry for my bad english
In Javascript, you do NOT declare two methods of the same name with differnt args like you do in some other languages. Instead, you declare only a single method with the name and then you examine the arguments when the function is called to decide which behavior you should follow.
When you do declare two properties with the exact same name, then one of them is ignored by the interpreter since there can only be one value for any given property in Javascript.
There is a long description of overloading in Javascript with a number of examples here:
How to overload functions in javascript?
In your specific case, you could test how many arguments were passed to the method and branch accordingly:
var sum = {
a : 5,
b : 7,
sumar : function(a, b)
{
if (arguments.length < 2) {
// no arguments passed, use instance variables
return (this.a+this.b);
} else {
// arguments were passed, use them
return (a+b);
}
}
}
document.write(sum.sumar() + "<br>");
document.write(sum.sumar(6, 7) + "<br>");
Though, I must say, this is a particularly odd method that sometimes operates on the instance properties and sometimes doesn't.

Categories