This question already has answers here:
Is there a better way to do optional function parameters in JavaScript? [duplicate]
(28 answers)
Closed 8 years ago.
In PHP I can do something like this:
public myFunction($variable=0) {
//Do some stuff
}
In Javascript, the following does not work:
var myFunction = function(variable=0 )
{
//do some stuff...
};
Try this
var myFunction = function(variable) {
variable = variable || 0;
// this variant works for all falsy values "", false, null, undefined...
// if you need check only undefiend, use this variant
// variable = typeof(variable) == 'undefined' ? 0 : variable
};
Default function parameters will be in ES6; ES5 does not allow it.
With ECMAScript 6 you can do this.
Check an example:
function multiply(a, b = 1) {
return a*b;
}
multiply(5); // 5
But this is still experimental and today is only supported by Mozilla Firefox browser.
Check this link do see documentantion:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters#Browser_compatibility
Related
This question already has answers here:
Where can I get info on the object parameter syntax for JavaScript functions?
(1 answer)
ES6 Object Destructuring Default Parameters
(1 answer)
Closed 2 years ago.
function lookupRecord2({value1 = "blue", value2 = 7}) {
console.log('theValues');
console.log(value1);
console.log(value2);
}
lookupRecord2( { value1: 'pink', value2: 9 } );
I've read that Javascript doesn't allow for named parameters so I'm confused how the above code works. What is happening here that's allowing me to override the params?
I think what's confusing is that the params are assigned with "=" whereas the object I'm passing uses ":" ...
ADDED:
I know this is a form of destructuring, but I still can't make sense of it b/c it's in the function declaration.
function des({ a = 1, b = 2 } = {}) {
console.log(a);
console.log(b);
}
des();
This is a destructing syntax where we're able to pass default values.
It works everywhere, not just in function declarations.
{ a = 1, b = 2 } = { b:3 }
// assigns 1 to "a" and because "b" already exists, "b" is 3
MORE INFO HERE: can someone explain this seemingly weird assignment `{key=value} = argument`
This question already has answers here:
Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?
(22 answers)
Closed 4 years ago.
I'm wondering if there's a shorthand way to write something like this in JavaScript
if (thingExists) {
thingExists.manipulate
}
I think I remember seeing something along the lines of
thingExists?.manipulate
but that may have been TypeScript or something.
Anyway, any knowledge on that matter is appreciated,
Thanks!
You can use && for short circuiting:
thingExists && thingExists.manipulate
thingExists.manipulate will be evaluated if and only if thingExists is truthy.
Example:
var obj = { func: function() { console.log("func is called"); } };
obj && obj.func(); // => func is called
var falsy = null;
falsy && falsy.imaginaryFunc(); // => nothing
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 7 years ago.
I was trying to "put a function into an object" so I wanted to do something like this but I'm getting errors everywhere.
var someobject = {
makename(1) : null,
makename(2) : null,
makename(3) : null,
makename(4) : null
};
function makename(num) {
return (identifier + ' Bot' + num)
}
In modern (ES2015) JavaScript environments, you can do this:
var someobject = {
[makename(1)]: "foo",
[makename(2)]: "bar"
};
The [ ] wrapper around the property name allows it to be an arbitrary expression. The result of evaluating the expression is interpreted as a string and used as the property name.
var someobject = {}
someObject[makename(1)] = null;
someObject[makename(2)] = null;
someObject[makename(3)] = null;
someObject[makename(4)] = null;
This works everywhere. However, #pointy's solution is nicer!
This question already has answers here:
Accessing Properties in object [duplicate]
(3 answers)
Closed 7 years ago.
I used to believe that there is no difference between them but after seeing this piece of code, all my information about objects in Javascript failed.
var search = function(name) {
for(var x in friends) {
if(friends[x].firstName === name) {
console.log(friends[x]);
return friends[x];
}
}
};
This code works. But
var search = function(name) {
for(var x in friends) {
if(friends.x.firstName === name) {
console.log(friends.x);
return friends.x;
}
}
};
this doesn't.
Thanks for explaining.
friends.x is not the same thing as friends[x], it's the same thing as friends['x'].
When you use friends[x] the value x can be a variable (or any expression), but when you use friends.x the x is a literal name, it won't use the variable x.
As #Guffa already explained, friends.x and friends['x'] are the same, the difference in those approaches is that when you use [] this syntax you can use variables, 'property like this', or reserved words, this is good when you do not know exactly the property you will need.
This question already has answers here:
Determine original name of variable after its passed to a function
(9 answers)
JavaScript: Get Argument Value and NAME of Passed Variable [duplicate]
(7 answers)
Closed 7 years ago.
I know this is completely useless, but I'm nonetheless curious. Is it possible to do something like the below?
function getVariableName ( v )
{
// .... do something .....
// return the string "v"
}
var x = 69;
var y = "somestring";
console.log(getVariableName(x)); // prints "x" to the console
console.log(getVariableName(y)); // prints "y" to the console
function getArgNames(fn) {
var matches = fn.toString().match(/\(([a-z_, ]+)\)/i);
if (matches.length > 1) {
return matches[1].replace(/\s+/g, '').split(',');
}
return [];
}
That will return an array of the names of all arguments passed in to the function.