This is some tricky question. How can i pass value to last parameter if preceding parameters has default value?
function sum(a=10, b=7, c){
return a+b+c;
}
document.getElementById("result").innerHTML = sum(10);
<div id="result"></div>
I want 10 to be assign to c and result as sum of 3 values.
You can use named parameters (destructuring assignment). Basically your funcion receives an object, and you still can set the default values and pass only the properties you need. And with this approach the order of the properties doesnt matter at all. You can call sum({ c: 2 }) or sum({ a: 3, c: 4}) .. or whatever.
Further reading: http://2ality.com/2011/11/keyword-parameters.html
function sum({a=10, b=7, c}){
return a+b+c;
}
document.getElementById("result").innerHTML = sum({ c: 10 });
<div id="result"></div>
Note regarding the other answers: IMHO passing falsy values like undefined or null to as arguments, makes a function very inconsistent and hard to test. Thats why I would use named params if I know that some fields might not be needed for x reasons.
Pass undefined explicitly to get the default values:
function sum(a = 10, b = 7, c) {
return a + b + c;
}
const result = sum(undefined, undefined, 10);
console.log(result);
You can declare as: function sum(c, a=10, b=7) then use: sum(10)!
function sum(c, a=10, b=7){
return a+b+c;
}
document.getElementById("result").innerHTML = sum(10);
<div id="result"></div>
function sum(a , b = 10, c=7) {
return a + b + c;
}
Related
I think this is a simple one, and it may even have been asked previously, but I don't know what keywords to use to do a search. I believe that variables are strings and can only be strings, so even my question is a poor one, but I want to figure out a good way to do some math.
We start with something simple, like:
var a=0, b=a+1
console.log(a,b) // yields 0,1
But I then want to be able to update a later in the code and have it automatically update b, so if later I set:
a=1
console.log(a,b) // now yields 1,2
The goal being the updated b without having to tell the code that b=a+1 a second time (or hundreds of times, as this is a lot of math I am playing with).
Instead of using a variable you could use an object with a getter and setter.
const obj = {
a: 0,
get b() { return this.a + 1 },
set b(value) { this.a = value - 1 },
};
console.log(obj);
obj.a = 10;
console.log(obj);
obj.b = 20;
console.log(obj);
If you never plan to set b, then you can omit the setter.
Create a separate function that updates both variables. Then, whenever you want to modify them, call the method instead of reassigning the variables manually, for example:
var a = 0,
b = a + 1;
const increment = () => {
a++;
b++;
};
increment();
increment();
console.log(a, b);
I would use a function for b instead and call it whenever is needed.
let a = 1;
const b = () => a + 1;
console.log(b()); // prints 2
a = 10;
console.log(b()); // prints 11
You can create a function to increment both the values.
const func= () => {
a++;
b++;
};
And then you can call the function each time you have to increment values. If you have to increment continuously for a fixed number of times then call the function inside a loop.
I want to supply a function with only some of its parameters, and let the rest revert to their defaults. For example, I have a function like this:
function doSomething(a = 'apple', b, c){
//Do something with a, b and c
}
Now I want to call this function, but only supply arguments b and c (so that 'a' defaults to 'apple'). What is the best way to do this?
Normally, the defaults should be at the very end of your function (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters):
function doSomething(b, c, a = 'apple'){
//Do something with a, b and c
}
There is no absolute best way of doing it. But, there are few ways that can simplify and bring in more meaning to the code written with default parameters.
You can define all the default parameter in the starting of the arguments and for rest of the parameters which doesn't have a default value, make use of the rest operator.
Eg -
function doSomething(a='apple',b='banana',...args){
console.log(a);
console.log(b);
console.log(args);
}
let x,y;
doSomething(x,y,"hello","hey","hi");
output -
Go through the following link to get more understanding of the rest operator.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters
Though a little unrelated. By default javascript, parameters are undefined if they are not passed any value or reference. You can check that the parameters are not undefined inside your code block.
A useful pattern (used widely in the JavaScript world) is to allow callers to pass an options object, if entries are missing they will fall back to default values.
It's particularly useful if you're dealing with a lot of parameters.
function doSomething(a, b, options) {
// Specify your defaults here...
let defaults = { c: 3, d: "bar" };
options = Object.assign({}, defaults, options);
let { c, d } = options;
console.log("doSomething: (a,b,c,d):", a, b, c, d);
}
doSomething(1,2, { c: 5, d: "foo" });
doSomething(1,2);
hope this will be clear if value of a param should always be same :
function doSomething(b, c, a = 'apple'){
console.log({b:b},{c:c},{a:a})
}
doSomething('hi','hello','a is not apple here--')
function doSomething1(b, c, a){
a = 'apple'
console.log({b:b},{c:c},{a:a})
}
doSomething1('hi','hello','a is apple here--')
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.
This is fuction:
let Func = (a=10, b) => {
return a + b;
}
Function Calling:
Func(null,20);
or
Func(20);
I want to get output : 30
Is there other way of calling function and get output 30?
There is no function overloading in JavaScript. The most you can get is that you can use named parameters in functions:
let Func = ({a=10, b}) => {
return a + b;
}
console.log(Func({b: 20}));
This obviously, changes the way you call the function, but it supports omitting the optional parameters.
Default parameters:
Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.
You can pass undefined as the first parameter. As said above, note that passing null won't work:
const Func = (a = 10, b) => {
return a + b;
}
console.log(Func(undefined,20));
If you can't pass undefined for whatever reason, then the best you'll be able to do is to explicitly test a inside the function, and reassign if needed. For example:
const Func = (a = 10, b) => {
if (a === null) a = 10;
return a + b;
}
console.log(Func(null,20));
You can also try to use a Destructuring assignment.
Idea is to create an array of values and set it to necessary argument. You can add default values based on the priority as well. This way, you do not need to construct your inputs or pass undefined.
const Func = (...rest) => {
const [ b, a ] = [ ...rest, 10 ]
return a + b;
}
console.log(Func(20));
console.log(Func(5, 20));
You can even extend it to work like this, but say you only want to pass values for b and d. This will create problems and you will have to rely on one of the approaches discussed in other answers(preferred answer in my opinion). But, if problem statement is straight forward, you can give this a try.
const Func = (...rest) => {
const defaultValues = [ 10, 5, 20 ];
const [ b, a, c, d ] = [ ...rest, ...defaultValues ]
return a + b + c + d;
}
console.log(Func(20));
console.log(Func(5, 20));
console.log(Func(5, 20, 25));
console.log(Func(5, 20, 25, 35));
I was watching a JavaScript talk, and the tutor said that if we pass a property of an object in a function it will actually change the real value, because we will be passing the variable by reference. Here is the slide:
but when I tried to practice the concept, that wasn't the case. Here is my code:
var obj = {val: 5};
function changeVal(x) {
x = x+5;
return x;
}
console.log(obj.val) // 5
console.log(changeVal(obj.val)) // 10
console.log(obj.val) // 5
I was expecting obj.val to change to 10.
Please tell me what's wrong here, and correct me if I am wrong. Thanks
You are passing not the object, but the primitive type. So when you pass the val of the obj, it is a number and is a primitive type.It copies the val and passes the copy to the object.
If you pass like this, it will work
var obj = {val: 5};
function changeVal( param ) {
param.val = param.val + 5;
return param.val ;
}
console.log(obj.val) // 5
console.log(changeVal(obj)) // 10
console.log(obj.val) // 10
You are not actually passing an object, just passing the value of property(val).
If you will pass obj in changeVal(), then it will actually change the value of the property of passed object.
For that you need to do like:
var obj = {val: 5};
function changeVal(x)
{
x = x+5;
return x;
}
console.log(obj.val); // 5
changeVal(obj); // Need to pass object instead of value of the property's value
console.log(obj.val); // 10
Primitive types (string, integer, boolean, etc...) are immutable, which means if you change one of the values inside a function, the callee (scope which calls your function) will not see the change.
function doSomething(a) {
a = a + 1;
}
var value = 2;
console.log(value); // result: 2
doSomething(value);
console.log(value); // result: 2
Pass-by-reference only works for objects. Like this:
function doSomething(obj) {
obj.attribute = obj.attribute + 1;
}
var myObject = {attribute: 2};
console.log(myObject.attribute); // result: 2
doSomething(myObject);
console.log(myObject.attribute); // result: 3
More reading about Javascript types:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
Say for instance you have an Iphone . Now lets say a manufacturing company calls you and asks to borrow your Iphone for a reference just so they can design an Iphone that is similar and sell it to customers . Your original Iphone still exists and is never gone , but every now and then the factory needs to use it for a reference , think of your function as the factory that just make a copy of obj.
//Original data
var obj = {val: 5};
Once your function returns something , it technically becomes a value
Example :
return 3; is a value of 3
so
function changeVal(x) {
x = x+5;
return x;
}
is a new value of x which in this case would be x + 5;
x is a copy of whatever you pass into the function .
Hope this helps.