ES6 Get default parameters/arguments - javascript

How can I get the value of the default parameters/arguments dynamicly without using the parameter variable?
function someFunc(param1 = 'value', param2 = 'value') {
console.log(arguments.length);
console.log(arguments[0]);
}
someFunc(); //0 undefined

I wanted to do the same, in order to assign several attributes to the instance of my class.
This approach might not help you since it uses one object argument instead of two arguments, still worth to mention:
class MyClass{
constructor(params={param1:3.1415, param2:'Hello'}){
//*assign* effectively destructures the params arg
Ojbect.assign(this,params);
}
}
Similarly your example would look like this:
function someFunc(params = {param1:'value', param2: 'value'}) {
console.log(Object.keys(params).length);
console.log(params['param1']);
}
Note that this approach requires your argument to be an object and that given one of the two arguments the other one will not be present in the default object.

You don't. Think about it this way. How do you get the default value with the old method?
function someFunc(param1, param2) {
param1 = param1 || 'value';
param2 = param2 || 'value';
console.log(arguments.length);
console.log(arguments[0]);
}
someFunc(); //0 undefined
Your best bet is to store the default value in a variable, and compare it in runtime. But that is kind of pointless.

Related

Why assign a value within a function's arguments?

I've come across this pattern in an open-source project and have never come across it before, and was wondering the reasoning for doing it:
doSomething(blah = blurgh);
It is a shortcut to do in a single statement : assigning a variable and using the assigned variable as argument of a function.
So instead of writing it :
blah = blurgh;
doSomething(blah);
You write just :
doSomething(blah = blurgh);
It assigns it as a default value for the argument:
function someFunc(thing = "default string") {
console.log(thing);
}
someFunc() // default string
someFunc('another string') // another string
You can assign anything you want as the default value, even a previous argument
function someFunc(arg1, arg2 = ar1) {...}
It will use the default value even if you pass null explicitly.

Returning a non-value property

In javascript, it is possible to define an object's property as a getter/setter rather than just a "plain" value:
Object.defineProperty( obj, 'complex_property', {
get: function getter() { return this.protected; },
set: function setter( value ) { this.protected = value; }
} );
Is there any way to return a non-value property of an object without first having its getter function evaluated so that this (or the like) is possible?
obj.property = function( name ) { return this.[ name ]; };
// Doesn't work:
// ReferenceError: invalid assignment left-hand side
obj.property( 'complex_property' ) = 5;
The last line effectively reads 6 = 5 - obviously an error - since this.complex_property is evaluated first, then returned. Combining closures with getter-setter properties is an effective way to simulate "private" properties and validate assignment values without having to use actual get/set functions: one of the nicer features of modern javascript. It'd be even nicer if there was a way to return an unevaluated getter/setter property: is there a way I've missed or is it just not possible? Are we stuck using set( prop, value ) functions?
Unfortunately, this isn't possible with JavaScript functions. All JavaScript functions created by user code can only return values, not references (and this won't be possible by code within the browser too, starting from ES6).
A ReturnStatement is evaluated as follows (bold my emphasis):
If the Expression is not present, return (return, undefined, empty).
Let exprRef be the result of evaluating Expression.
Return (return, GetValue(exprRef), empty).
The only way to do so is either using a set(property, value) function or creating an actual setter.
You can get a property. Well, a property descriptor at least. And it ain't pretty.
var prop = Object.getOwnPropertyDescriptor(obj /* from question */, 'complex_property');
prop.set.call(obj, 5);
edit:
obj.property = function (name) { return Object.getOwnPropertyDescriptor(this, name); }
obj.property('complex_property').set.call(obj, 5);

JavaScript passing argument via reference

let say I've got this kind of code:
var obj1 = {test: false};
function testCondition(condition){
if (!condition){
testCondition(condition);
}
}
testCondition(obj1.test);
above code will pass false as argument to testCondition. How can I do to pass reference to obj1.test instead of passing it's value?
EDIT
wow, thanks for quick responses!! :) But I would like to add, that I cannot pass the whole object, because I would like to build one generic function/method which would just check parameter and do onComplete callback or onError callback. Above code is only example of situation where I am right now.
You have two choices, from what I can see:
Pass the object itself, instead of its member. You can then access and modify the member:
function testCondition(object) {
if (!object.test) {
testCondition(object);
}
}
testCondition(obj1)
Alternatively, since you're changing a single value, you can have that value be returned by the function:
function testCondition(condition) {
if (!condition){
return testCondition(condition);
}
}
obj1.test = testCondition(obj1.test);
FYI, your code as you've displayed it right now will cause an infinite recursion if condition is false.
What's wrong with return values?
Alternatively you can wrap the argument in an object:
function foo(arg) {
var val = arg.val;
// do something with val
arg.val = val;
}
var arg = {val:"bar"};
foo(arg);
// do something with arg.val
You can't.
Pass obj1 instead, then examine condition.test inside the function.
You can't. JavaScript passes objects and arrays by reference, primitives (integers, strings, booleans) by value. What you're asking for is impossible, except by bad work-arounds:
function ugly(result) {
result.success = true;
}
var result = {};
ugly(result);
Instead, just return your value. It's how JavaScript is meant to work.
pass the whole object instead of its property:
testCondition(obj1);
and then
if(!passedObj.test){
etc...

Javascript function with default not required values

I can't find the similiar problem, I guess it's because i can't find a correct question/answer.
I want to create a function that will use default values if there is not arguments passed when calling a function, if so, replace default values with the values passed in function's parameters.
For example:
function openBlock(false){
// if parameter was passed with 'false' value, it will do this
// else it will put automatically a 'true' value to an function's argument
}
So if call a function openBlock() without any params, it will consider that it's param true by default. If i call a function with argument false like openBlock(false) it will override the default behavior.
Thanks
There are various ways to do this in Javascript, though none are built in. The easiest pattern is:
function(option) {
option = option || "default";
// do stuff
}
But as #FelixKling notes, this won't work in your case, as it will replace any false-y value (including explicitly setting the argument to false) with the default. For boolean arguments that you want to default to true, you need:
function(option) {
// default to "true"
option = option !== undefined ? option : true;
// do stuff
}
When you're dealing with more than one or two arguments, the best option is often to use a single options or config argument and check for the existence of properties:
function(options) {
var arg1 = option.arg1 !== undefined ? false : true;
var arg2 = option.arg2 || "default";
// do stuff
}
If you're using a library like jQuery or underscore, the extend method makes it quite easy to set up an object with default values and then overwrite them with supplied values if they exist:
function(options) {
var defaults = {
arg1: true,
arg2: "default"
};
options _.extend(defaults, options);
// do stuff
}
JavaScript doesn't really have default parameters implemented like other languages do.
You'll have to implement them yourself:
function openBlock(argument) {
argument = typeof argument !== 'undefined';
}
Take a look at Is there a better way to do optional function parameters in Javascript? for a more generic approach.

I want to pass JavaScript Objects as Arguments

function foo(o){
o=o || {};
}
foo(one:1); // ???
alert(foo(one); // ???
foo(one:1,two:2,three:3) // ???
alert(foo(one,two,three)); // ???
What exactly does this piece of JavaScript do?
o = o || {};
I've seen in many codes.
The expression
o = o || {};
means
Interpret the value of the variable "o" as a boolean. If that value is "true", then set "o" to its current value. If "false", set "o" to refer to a new Object instance.
The point is to make sure that "o" is not null, and to initialize it to a new Object instance if it is.
As far as calling the function, you need to use the "object literal" notation:
foo({ key1: value, key2: value, ... });
edit — as noted in a comment, the interpretation of the value of "o" as boolean is a rather interesting subject of its own. In this particular case, the intent is to check to see whether "o" is null. There are values for "o" that evaluate to false but which might need to be treated differently here, but there's obviously not enough context in the question to know.
you would create your object
var arg = {key: val};
and then
var result = foo(arg);
you pass the object that is the argument into the function. If your function can take more than one arg, when you define the function you would
var theFunction = function(arg1, arg2, arg3) {
// arg1, arg2, and arg3 are all references in this function
}
that way arg1, arg2, and arg3 are defined to be arguments. Javascript has some flexibility in that you could pass as many arguments as you want in; it is good design to define the function with explicit arguments so the API is clear. However, there are cases where you just don't know, so in Javascript you can get all the arguments that were passed in with the 'arguments' variable. Javascript makes this variable available in all functions. But you should use it rarely. Here is a link with examples
http://www.seifi.org/javascript/javascript-arguments.html
the
o = o || {};
sets the variable 'o' to be o, or if o is not defined, an empty object literal. It basically initializes the variable if it is 'falsy'. It is a technique to prevent null object issues.

Categories

Resources