default value in the function - javascript

Noticed two patterns to set a default value for an argument of the function:
function fn ( val ) {
val = val || 'default'; // (1)
val || ( val = 'default' ); // (2)
}
Generally I use #1, just found the second one.
which is better? and what is the difference between those? any other options?

Your methods will not work all the time. If you want to pass false as argument for example the expression will be considered false and your variable will be assigned the default value.
For a more robust method you could use:
val = typeof val !== 'undefined' ? val : "default";
With this method you can pass false as argument and even null (typeof null == "object")
If you have a lot of optional arguments you could also consider taking an object as parameter and complete it with default values on properties that are not set. This is easier because you can map the value to the property name and the order is not important anymore.

Related

Why is (null==undefined) true in JavaScript? [duplicate]

How do I check a variable if it's null or undefined and what is the difference between the null and undefined?
What is the difference between == and === (it's hard to search Google for "===" )?
How do I check a variable if it's null or undefined...
Is the variable null:
if (a === null)
// or
if (a == null) // but see note below
...but note the latter will also be true if a is undefined.
Is it undefined:
if (typeof a === "undefined")
// or
if (a === undefined)
// or
if (a == undefined) // but see note below
...but again, note that the last one is vague; it will also be true if a is null.
Now, despite the above, the usual way to check for those is to use the fact that they're falsey:
if (!a) {
// `a` is falsey, which includes `undefined` and `null`
// (and `""`, and `0`, and `NaN`, and [of course] `false`)
}
This is defined by ToBoolean in the spec.
...and what is the difference between the null and undefined?
They're both values usually used to indicate the absence of something. undefined is the more generic one, used as the default value of variables until they're assigned some other value, as the value of function arguments that weren't provided when the function was called, and as the value you get when you ask an object for a property it doesn't have. But it can also be explicitly used in all of those situations. (There's a difference between an object not having a property, and having the property with the value undefined; there's a difference between calling a function with the value undefined for an argument, and leaving that argument off entirely.)
null is slightly more specific than undefined: It's a blank object reference. JavaScript is loosely typed, of course, but not all of the things JavaScript interacts with are loosely typed. If an API like the DOM in browsers needs an object reference that's blank, we use null, not undefined. And similarly, the DOM's getElementById operation returns an object reference — either a valid one (if it found the DOM element), or null (if it didn't).
Interestingly (or not), they're their own types. Which is to say, null is the only value in the Null type, and undefined is the only value in the Undefined type.
What is the difference between "==" and "==="
The only difference between them is that == will do type coercion to try to get the values to match, and === won't. So for instance "1" == 1 is true, because "1" coerces to 1. But "1" === 1 is false, because the types don't match. ("1" !== 1 is true.) The first (real) step of === is "Are the types of the operands the same?" and if the answer is "no", the result is false. If the types are the same, it does exactly what == does.
Type coercion uses quite complex rules and can have surprising results (for instance, "" == 0 is true).
More in the spec:
Abstract Equality Comparison (==, also called "loose" equality)
Strict Equality Comparison (===)
The difference is subtle.
In JavaScript an undefined variable is a variable that as never been declared, or never assigned a value. Let's say you declare var a; for instance, then a will be undefined, because it was never assigned any value.
But if you then assign a = null; then a will now be null. In JavaScript null is an object (try typeof null in a JavaScript console if you don't believe me), which means that null is a value (in fact even undefined is a value).
Example:
var a;
typeof a; # => "undefined"
a = null;
typeof null; # => "object"
This can prove useful in function arguments. You may want to have a default value, but consider null to be acceptable. In which case you may do:
function doSomething(first, second, optional) {
if (typeof optional === "undefined") {
optional = "three";
}
// do something
}
If you omit the optional parameter doSomething(1, 2) thenoptional will be the "three" string but if you pass doSomething(1, 2, null) then optional will be null.
As for the equal == and strictly equal === comparators, the first one is weakly type, while strictly equal also checks for the type of values. That means that 0 == "0" will return true; while 0 === "0" will return false, because a number is not a string.
You may use those operators to check between undefined an null. For example:
null === null # => true
undefined === undefined # => true
undefined === null # => false
undefined == null # => true
The last case is interesting, because it allows you to check if a variable is either undefined or null and nothing else:
function test(val) {
return val == null;
}
test(null); # => true
test(undefined); # => true
The spec is the place to go for full answers to these questions. Here's a summary:
For a variable x, you can:
check whether it's null by direct comparison using ===. Example: x === null
check whether it's undefined by either of two basic methods: direct comparison with undefined or typeof. For various reasons, I prefer typeof x === "undefined".
check whether it's one of null and undefined by using == and relying on the slightly arcane type coercion rules that mean x == null does exactly what you want.
The basic difference between == and === is that if the operands are of different types, === will always return false while == will convert one or both operands into the same type using rules that lead to some slightly unintuitive behaviour. If the operands are of the same type (e.g. both are strings, such as in the typeof comparison above), == and === will behave exactly the same.
More reading:
Angus Croll's Truth, Equality and JavaScript
Andrea Giammarchi's JavaScript Coercion Demystified
comp.lang.javascript FAQs: JavaScript Type-Conversion
How do I check a variable if it's null or undefined
just check if a variable has a valid value like this :
if(variable)
it will return true if variable does't contain :
null
undefined
0
false
"" (an empty string)
NaN
undefined
It means the variable is not yet intialized .
Example :
var x;
if(x){ //you can check like this
//code.
}
equals(==)
It only check value is equals not datatype .
Example :
var x = true;
var y = new Boolean(true);
x == y ; //returns true
Because it checks only value .
Strict Equals(===)
Checks the value and datatype should be same .
Example :
var x = true;
var y = new Boolean(true);
x===y; //returns false.
Because it checks the datatype x is a primitive type and y is a boolean object .
Ad 1. null is not an identifier for a property of the global object, like undefined can be
let x; // undefined
let y=null; // null
let z=3; // has value
// 'w' // is undeclared
if(!x) console.log('x is null or undefined');
if(!y) console.log('y is null or undefined');
if(!z) console.log('z is null or undefined');
try { if(w) 0 } catch(e) { console.log('w is undeclared') }
// typeof not throw exception for undelared variabels
if(typeof w === 'undefined') console.log('w is undefined');
Ad 2. The === check values and types. The == dont require same types and made implicit conversion before comparison (using .valueOf() and .toString()). Here you have all (src):
if
== (its negation !=)
=== (its negation !==)
If your (logical) check is for a negation (!) and you want to capture both JS null and undefined (as different Browsers will give you different results) you would use the less restrictive comparison:
e.g.:
var ItemID = Item.get_id();
if (ItemID != null)
{
//do stuff
}
This will capture both null and undefined
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null, blank, undefined, zero you can test
if(!(!(data)))
{
//If data has valid value
alert("data "+data);
}
else
{
//If data has null, blank, undefined, zero etc.
alert("data is "+data);
}
}

What would be the most efficient way to check if a JavaScript variable is either falsey, or an empty array or object?

I have a use case where a function receives a variable which could be of various types, including an array or an object reference.
But I want to ignore any variables passed in which are falsey in the usual JavaScript senses, plus I want to treat empty arrays [] and empty objects {} as also being falsey.
I can see immediately there would be many ways to do this but I'm wondering what would be most efficient assuming a very modern JavaScript implementation and only vanilla JavaScript with no frameworks.
The obvious way is to check if it's an array or an object and check .length in the case of an array and Object.keys(x).length if it's an object. But considering that some other things which are already falsey are also typeof object and that empty arrays seem to behave either truthy or falsey depending on how you check, I'm betting that some ways are more efficient and probably more idiomatic too.
The following should match your criteria (Although it looks ugly).
if (
sth && // normal JS coercion
(!Array.isArray(sth) || sth.length) && // falsify empty arrays
(Object.getPrototypeOf(sth) !== Object.prototype || Object.keys(sth).length) // falsify empty objects
)
alert("pass");
Tests:
sth = []; // Don't Pass
sth = {}; // Don't Pass
sth = null; // Don't Pass
sth = false; // Don't Pass
sth = undefined; // Don't Pass
sth = ""; // Don't Pass
sth = [1]; // Pass
sth = { a: "" } // Pass
sth = new Date; // Pass
sth = "a"; // Pass
sth = function(){} // Pass
This checks if sth is truthy:
if(sth && (typeof sth !== "object" || Object.keys(sth).length))
alert("passes");
I use this al the time.
function IsEmpty(val){
return (!val || val == "" || (typeof(val) === "object" && Object.keys(val).length == 0) || val === [] || val === null || val === undefined);
}
Examples that pass
if(IsEmpty(false)){console.log("pass");}
if(IsEmpty("")){console.log("pass");}
if(IsEmpty([])){console.log("pass");}
if(IsEmpty({})){console.log("pass");}
if(IsEmpty(null)){console.log("pass");}
if(IsEmpty()){console.log("pass");}
Examples that fail
if(IsEmpty(true)){console.log("fail");}
if(IsEmpty("not null")){console.log("fail");}
if(IsEmpty([1])){console.log("fail");}
if(IsEmpty({"a":1})){console.log("fail");}
//!IsEmpty means is not empty
if(!IsEmpty(false)){console.log("fail");}
if(!IsEmpty("")){console.log("fail");}
if(!IsEmpty([])){console.log("fail");}
if(!IsEmpty({})){console.log("fail");}
if(!IsEmpty()){console.log("fail");}

Dynamically adding properties to an object

I have an object named Object1 which is third party object & I'm putting in properties inside it.
Object1.shoot({
'prop1':prop_1,
'prop2':prop_2,
'prop3':prop_3
});
Now I want the key 'prop1' to be added as property to Object1 only when prop_1 has some value. Otherwise I do not want to add it,
Whats the best way to do it?
You can check each property in for loop first.
var params = {
'prop1':prop_1,
'prop2':prop_2,
'prop3':prop_3
};
for (var param in params) {
if (typeof params[param] === 'undefined') {
delete params[param];
}
}
Object1.shoot(params);
You can make a helper function to add the property if defined:
function addProp(target, name, value) {
if(value != null) {
target[name] = value
}
}
var props = {}
addProp(props, 'prop1', prop_1)
addProp(props, 'prop2', prop_2)
addProp(props, 'prop3', prop_3)
The above does a null check instead of an undefined check. You can change as appropriate (e.g. you might not want empty strings, or number zero or anything else), though check this first:
How to determine if variable is 'undefined' or 'null'?

Optional parameters in JavaScript [duplicate]

This question already has answers here:
Set a default parameter value for a JavaScript function
(29 answers)
Closed 6 years ago.
Question
What is a good way of assigning a default value to an optional parameter?
Background
I'm playing around with optional parameters in JavaScript, and the idea of assigning a default value if a parameter is not specified. My method in question accepts two parameters, the latter of which I deem to be optional, and if unspecified should default to false. My method looks something like this...
// selects the item, appropriately updating any siblings
// item to select [, toggle on / off]
this.selectItem = function(item, toggle)
{
toggle = toggle && typeof toggle === 'boolean';
if (toggle)
{
// ...
}
}
Testing
After running a few tests on this jsFiddle, using the following principal for default value assigning:
function checkParamIsBoolean(param)
{
param = param && typeof param === 'boolean';
}
checkParamIsBoolean('me'); // boolean
checkParamIsBoolean([]); // boolean
checkParamIsBoolean(true); // boolean
checkParamIsBoolean(false); // boolean
checkParamIsBoolean(1 == 1); // boolean
checkParamIsBoolean(1); // boolean
checkParamIsBoolean(null); // object
checkParamIsBoolean(undefined); // undefined
​
As you can, the results vary, and aren't desired.
Expected
null = false
undefined = false
Actual
null = object
undefined = undefined
Summary
Are there any alternative approaches to assigning a default value to an optional parameter if it's unspecified; would it be better to use _toggle as the parameter and then assign the value to var toggle within the method?
Better solution is to use named arguments wraped in a object. It keeps your code clean and prevents errors in case of complex functions (with many default and non-default arguments). Otherwise you need to remember about the order of arguments and assign default values based on the types of arguments present (that's what you're trying to do).
That method is a primary way of passing params jQuery and jQuery's plugins.
function test(options) {
// set up default options
var defaults = {
param1: 'test',
param2: 100
};
// combine options with default values
var options = $.extend({}, defaults, options); // If you're not using jQuery you need different function here
alert(options.param1)
alert(options.param2)
}
test({'param2': 200}) // Call the function with just the second param
You can use this construction for optional parameters in your code:
//...
optionalParam = optionalParam || 'some default value';
In your concrete exaple it would be something like this:
this.selectItem = function(item, toggle)
{
toggle = toggle || false;
// ...
}
But in your case you could use toogle (optional parameter) directly in if statement (since you only want to check for its existence. Or optionally you could enforce boolean value like this toogle = !!toogle (double negation).
A very simple way to check if toggle is undefined, and if it is then set a default value:
if (toggle === undefined) toggle = "<your default value>";
Note that this does not change toggle if it is specified but of another type than what you expected.
Try it the other way around:
param = typeof param === 'boolean' && param;
This will make sure all are a boolean, see this fiddle
Why do you check the parameter to be boolean, if you expect an other result? The usual way would be checking for typeof toggle != "undefined", but in your case
toggle = Boolean(toggle);
should do the task. You can also use the shortcut !!toggle, or use it directly in the if-clause:
if (toggle) { // will evaluate to "false" for undefined
...
BTW, no need for a _toggle parameter; you can just reassign to toggle.
You can replace
param = param && typeof param === 'boolean';
with
param = !!(param && typeof param === 'boolean');
This will convert the result of the statement to the boolean negate, and then negate it back again.
If you consider null(as well as no args passed), undefined and ""(empty string) as "not an argument has passed to my function" use this statement:
toggle = toggle&&toggle||default_value
Now if you pass null, undefined or "" to your function as toggle arg, this line fills it with default_value.
Take a look at jQuery extend and how they handle optional parameters.
It can easilly be done with ArgueJS:
this.selectItem = function()
{
arguments = __({item: undefined, toggle: [Boolean, false})
if (arguments.toggle)
{
// ...
}
}
You can also check the type of item by changing undefined by the desired type.

Assigning a default value through the logical operator OR

We know that the javascript logical operator || produces the value of its first operand if the first operand is true. Otherwise, it produces the value of the second operand.
So in this example:
<script language="javascript">
function test (value){
this.value = value || "(value not given)";
}
</script>
if the parameter value passed to the function is treated as false like the integer 0 or the empty string "" then this.value will be set to (value not given) which is not true correct (because indeed we are passing a value).
So the question is which should be the best way to set this.value?
EDIT: All 4 first answers use the ternary operator "?". My question is about "||" operator.
The scheme with || is the most convenient to write, but it can ONLY be used when a falsey value (undefined, null, 0, "", false, NaN) is not a legitimate value. (When you just want to deal with null and undefined, you can use the new nullish coalescing operator (??) described in this proposal and included in ES2020.)
If you want to allow specific falsey values and not allow others, then you have to write more specific code to handle your specific cases. For example, if you wanted to allow an empty string, but not allow null or undefined or other falsey values, then you'd have to write more specific code like this:
function test(value) {
if (value || value === "") {
this.value = value;
} else {
this.value = "(value not given)";
}
}
Or if you only want to exclude only undefined, you can test for it specifically:
function test(value) {
if (value === undefined) {
value = "(value not given)";
}
this.value = value;
}
It depends on what values you want to exclude. If the "general false values" are too broad of a category, you can be more explicit:
function test(value) {
this.value = value !== undefined ? value : "(value not given)";
}
If you want to be able to assign falsey values do this.
this.value = (typeof value !== 'undefined') ? value : 'value not given';
This will retain values like false, '', and 0, but will use the default when the value is actually not passed as a parameter.
<script language="javascript">
function test (value){
this.value = arguments.length > 0 ? value : "(value not given)";
}
</script>
You can check to see if that argument was passed in by checking that functions arguments array's length.
The correct way is:
this.value = (typeof value == 'undefined') ? 'my argument' : value;
Probably duplicate question.
Google it.
Today depending on the browser support your application cares about, you might want to use default parameters instead:
var test = (value = '(value not given)') => {
this.value = value;
};
This is relevant today, also there has not been an update to the question and answers date since 2011 so I thought it might help.

Categories

Resources