Concisest way to handle undefined variables in JavaScript - javascript

I have an object that I am creating that could potentially have undefined properties.
Is there a more concise way to set the property than what I am doing below:
var ruleObj = {
factor: (ruleArray[2] ? ruleArray[2].trim() : null),
resultElseTarget: (ruleArray[10] ? ruleArray[10].trim() : null)
}
Notice how I have to repeat the variable after the ternary operator twice. The reason I'm asking is that I've run into this same type of problem several times and it doesn't seem like the best way to handle it.

Here’s a function that wraps another function to do nothing on null and undefined values:
const liftMaybe = f => x => x == null ? null : f(x);
Then you can define a trim that does nothing to undefined:
const trimMaybe = liftMaybe(x => x.trim());
and make use of it:
var ruleObj = {
factor: trimMaybe(ruleArray[2]),
resultElseTarget: trimMaybe(ruleArray[10]),
};
It differs from your original in its handling of empty strings, but I don’t know if that was intentional or if it’s even relevant.

Conciseness is one thing but with Javascript the bigger concern is readability and type checking.
In your example, if the value of ruleArray[2] is a boolean then it'd evaluate to false and set factor to null. Maybe that's what you want but just looking at your example code right now, I'd assume your ruleArray contains bools and not potential undefines.
The better way is to write a function to do null check
EDIT: someone was faster than me :) https://stackoverflow.com/a/46436844/643084
EDIT2: the other answer is great but i'd like to just make a note. null should not be treated the same as undefined even though they evaluate the same most of the times.

Some things:
Since you're checking indexes, you'd need to make sure that you have a length of at least the size you want. Otherwise ruleArray[10] can throw you and out of range error.
Assuming you are certain that you have the right number of elements in your array, you can use this to check a var for undefined, this is common to check incoming arguments (say you had something like function ( arg1, arg2 ) ):
arg1 = arg1 || 'some_default';
In your case, again assuming your array is long enough:
factor: ( ruleArray[2] || 'some other default' );
(Why would you set it to null if that's what you are trying to avoid).
If you're wondering, "is there a way to access an index that doesn't exist and just return null", the answer is "maybe...but I wouldn't".
Note, if the value is indeed falsy (say, 0, '', or false), you may not get what you expect, in which case you'd want to check for something more explicit, like null.
I get a lot of use of out the terse "something = thisValIfNotFalsy || someOtherDefaultVal. Like anything though careful when and where, etc.

You could do something like:
var ruleArray = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
function formatRule(rule) {
if (!rule) return null
return rule.trim()
}
var ruleObj = {
factor: formatRule(ruleArray[2]),
resultElseTarget: formatRule(ruleArray[10])
}
console.log(ruleObj.factor)
console.log(ruleObj.resultElseTarget)
We created a pure function that is tasked with producing either null or a trimmed value, which avoids duplicating this logic elsewhere.

Is there a more concise way
So far all answers seem to assume your input is either a string or null / undefined. For me I'd say the check for null / undefined is the wrong way round. You can only call trim on a string, so why not check it's a string?. It would also mean NaN / Numbers / Arrays etc, would not error. I'm assuming what your wanting this function to do is trim a string if it's a string, so I would also say you should pass the original value if not a string.
Maybe that's what #zaftcoAgeiha meant when he talking about not treating null & undefined the same.
Anyway, here is an example. Notice how numbers are still passed, but hello gets trimmed.
const ruleArray = [];
ruleArray[2] = null;
ruleArray[5] = 7;
ruleArray[7] = 'Helllo ';
const trimIfString = (x) => typeof x === 'string' ? x.trim() : x;
var ruleObj = {
factor: trimIfString(ruleArray[2]),
resultElseTarget: trimIfString(ruleArray[5]),
hello: trimIfString(ruleArray[7])
}
console.log(ruleObj);

You can use a function pattern and set default parameter with AND && operator when passing the parameter to check if variable is defined, if not set element value to null. You can include further checks to determine if variable is passed is a string.
let ruleArray = [];
ruleArray[10] = "def ";
let ruleFn = (factor = null, resultElseTarget = null) =>
({factor, resultElseTarget});
let ruleObj = ruleFn(ruleArray[2] && ruleArray[2].trim()
, ruleArray[10] && ruleArray[10].trim());
console.log(ruleObj, ruleObj.factor === null);

Related

Best alternative for optional chaining in javascript

I have the following chaining operator
const age = data.student?.age ? data.student.age: '';
this works fine in my local machine but seems to have problem in another machine. on further investigation i could understand that node js lower version(i suppose version below 12) doesn't support chaining operator. I understand that i can replace this with if condition like below but would like to know suggestions on what is the best possible alternative for this.
function checkAge(data){
if(data && data.student && data.student.age) {
return data.student.age;
} else {
return '';
}
}
const age = checkAge(data);
There is no need for code change. You only need to modify the target option in your TypeScript configuration and set it to anything ES2019 or below. Then you can use optional chaining in your TypeScript code and the compiler will produce the equivalent code.
The TypeScript code
const foo = a?.b?.c;
becomes
"use strict";
var _a;
const foo = (_a = a === null || a === void 0 ? void 0 : a.b) === null || _a === void 0 ? void 0 : _a.c;
when compiled: Playground Link
If the problem is readability, you could probably try object destructing.
So, your assigment would look something like this:
const {
student: {
age = ''
} = {}
} = data
Assuming declaring age as const, not to polluting scope with intermediate variables, and returning a number even for '0' and empty string in case of undefined are all a must, shorter option that comes to my mind would be following:
const age = (d=>(isNaN(d=(d.student||{}).age)?'':d))(data);
For less strict approaches, cleaner solution would be:
const age = (data.student || {}).age || "";
// In this case, though, numeric 0 would also be returned as empty string.
On the other hand, if you need to do this more than a few times, I would recommend to implement a handy picking function like:
const pick = (target, path)=>path.split(".")
.reduce(
(acc,key)=>acc&&acc[key]
,target
)
;
// And then...
const age = pick(data, 'student.age');
For picking approach it would be worth to reduce the number of
function calls performed by pick() function. I just used reduce for
the sake of brevity and simplicity.

How to find if value of an array is not defined?

If we have an array that does not exists and we check the value of the array it gives me an error. "variable is not defined"
for example I have:
var arr = new Array();
arr['house']['rooms'] = 2;
and I use
if ( typeof arr['plane']['room'] != 'undefined' ) )
it says arr['plane'] not defined...
I don't want to use this:
if ( typeof arr['plane'] != 'undefined' ) ) {
if ( typeof arr['plane']['room'] != 'undefined' ) {
}
}
In php I use isset that works nice for me, I searched a lot on google to find the answer but I can't...
The thing to realize is that there are no multi-dimensional arrays in javascript. It is easy to make an array element contain an array, and work with that, but then all references you make have to use that consideration.
So, you can do
arr = []; // or more appropriately {}, but I'll get to that soon
arr['house'] = [];
arr['house']['rooms'] = 2;
But doing
arr['house']['rooms'] = 2;
should give you an error unless you've already defined arr and arr['house'].
If you've defined arr but not arr['house'], it's valid syntax to reference arr['house'] - but the return value will (appropriately) be undefined.
And this is where you're at when you're looking at arr['plane']['room']. arr is defined, so that's ok, but arr['plane'] returns undefined, and referencing undefined.['room'] throws an error.
If you want to avoid the errors and have multiple levels of reference, you're going to have to make sure that all the levels but the lowest exist.
You're stuck with if (arr && arr['plane'] && arr['plane']['room']).
Or perhaps if (arr && arr['plane'] && room in arr['plane'] would be more accurate, depending on your needs. The first will check if arr['plane']['room'] has a truthy value, while the second will check if arr['plane']['room'] exists at all (and could have a falsey value).
Arrays vs objects
Arrays and objects are very similar and can both be accessed with [] notation, so it's slightly confusing, but technically, you're using the object aspect of the array for what you're doing. Remember, all arrays (and everything other than primitives - numbers, strings and booleans) are objects, so arrays can do everything objects can do, plus more. But arrays only work with numeric indices, i.e. arr[1][2]. When you reference an array with a string, you're attempting to access the member of the underlying object that matches that string.
But still in this case, it doesn't matter. There are no multi-dimensional arrays - or objects.
The [] notation with objects is simply a way to check for members of objects using a variable. arr['plane']['rooms'] is actually equivalent to arr.plane.rooms. but perhaps the arr.plane.room notation will help make it more clear why you have to first check arr.plane (and arr).
Use the following if you want to test for existence in an object:
if ( 'plane' in arr && 'room' in arr.plane ) {
// Do something
}
That's not an array, but an object, aka associative array. You can declare it like this:
var aarr = { house: { rooms: 2 } };
Now you can do:
if (aarr.house && aarr.house.rooms) {/* do stuff */ }
or uglier, but shorter:
if ((aarr.house || {}).rooms) {/* do stuff */ }
See also...
To more generally traverse an object to find a path in it you could use:
Object.tryPath = function(obj,path) {
path = path.split(/[.,]/);
while (path.length && obj) {
obj = obj[path.shift()];
}
return obj || null;
};
Object.tryPath(aarr,'house.rooms'); //=> 2
Object.tryPath(aarr,'house.cellar.cupboard.shelf3'); //=> null
JsFiddle

Pattern to avoid long dot-notation chains

When accessing nested objects using dot notation, I always have to make sure that the previous object exists, which gets pretty exhausting.
I basically want to avoid long if chains like
if (a && a.b && a.b.c && a.b.c[0] ... ) { v = a.b.c[0]; }
The only other thing I can think of is via the use of a try catch.
var v; try { v = a.b.c[0].d.e; } catch (e) {}
Is there a better pattern for this?
I think you've got the two prettiest solutions already.
But note that for something like, say, obj.obj.string.length your first solution will fail if string === "". Since an empty string is falsey, it'll trip the && guard.
But speaking of strings, you could do something like:
function getNestedProperty(obj, propChain) {
var props = propChain.slice(0), prop = props.shift();
if(typeof obj[prop] !== "undefined") {
if(props.length) {
return getNestedProperty(obj[prop], props);
} else {
return obj[prop];
}
}
}
var v = getNestedProperty(a, ["b", "c", 0, "d", "e"]);
Yeah... not too pretty :P
I'd say that, of the solutions proposed, try...catch is probably the simplest way to go
How about this one:
var hasProperty = function (object, property) {
var properties = property.split('.'),
temp = object;
while (temp && properties.length) {
temp = temp[properties.shift()];
}
return !!temp;
};
and then use it like:
if (a && hasProperty(a, 'b.c.0' ) { v = a.b.c[0]; }
The scenario you are referring to in your question is also called "optional chaining". Some languages already support it by now – for example C# has so called null-conditional operators which allow you to short-circuit your expressions:
var count = customers?[0]?.Orders?.Count();
Unfortunately, this feature has not yet made it into the current JS specifications.
There is an open Stage 1 proposol for "optional chaining" that can be tracked here.
This would allow you to write...
a?.b[3].c?.(x).d
...instead of:
a == null ? undefined : a.b[3].c == null ? undefined : a.b[3].c(x).d
If you want to take the risk and use it already at this early stage, you can target it via babel to include it in your project.
It's rather evil, but this should work and doesn't look too horrible:
var i = !a ? null : !a.b ? null : !a.b.c ? null : !a.b.c.d ? a.b.c.d.e;
The reason for the ! is to invert the test flag, to allow the success case to be the last expression in the ?:. That allows us to chain them together like this.
Do check the operator precedence if you want to do this for real (I did some very basic tests and I think I got it right). And do expect people to point and laugh if they see it in your code.

javascript ternary opretor to fill a variable based on conditions

I have this piece of code:
grp = $.cookies.get('grp');
if(grp == null){grp = 0}
1- how can i write it with ternary operators?
2- in word of performance is ternary form better or simple if statement if we have lots of them?
thanks in advance
do:
grp = $.cookies.get('grp');
grp = (grp == null) ? 0 : grp;
or
grp = $.cookies.get('grp') || 0;
I think the difference in performance is negligible, the important thing in such case is readability of the code.
Added: for example, if you want to check for object and create it if does not exist, then:
some_obj = window.some_obj || {};
To avoid type coercion always use the === operator. The null check is discouraged as well. When a value is undefined javascript always returns undefined.
Most of the time it's easier to create a helper function to avoid repeated code.
var grp = defaultIfUndefined($.cookies.get('grp'), 'My default value');
function defaultIfUndefined (value, defaultValue) {
if (typeof value === 'undefined') {
return defaultValue;
}
return value;
}

javascript initialize to undefined or null or ""

Java script has many falsy values as I started learning. I have a program that gets values from a service and loads into an array like this:
function loadNames() {
Global.names = // what should I use here? undefined, null, "", 0, {} or anything else
var lnames = getLNames(); // this is doing some magic
if ( lnames.length !== 0 ) {
Global.names = new Array();
for ( var i = 0; i < lnames.length; ++i)
Global.names[i] = lnames[i];
}
}
I want to know the right way of resetting Global.names. What is most appropriate here? In code I only want to check like if ( Global.names )
PS: I can't just take the return value into Global.names as the returned object is destroyed later. Hence, I need to do a deep copy
Thanks
Taken from JavaScript: the good parts :
"The if statement changes the flow of the program based on the value of the expression. The then block is executed if the expression is truthy. Here are the falsy values:
false
null
undefined
the empty string ''
the number 0
the number NaN
"
So basically if you set your var to any of those values, you'll be able to do a if(var){...}
I think you should init
GLobal.names = [];
and than just check if Global.names.length != 0.
If you want to reset it just make it an empty array again.
I think you'd be better off to initialize it as an array and test as
if ( Global.names.length )
Also, if you're just storing strings in the array you can simplify the function as
function loadNames() {
Global.names = getLNames().concat();
}
You don't have to initialise it to anything. You can do:
if (!Global.names) Global.names = [];
// add members to Global.names
This can be one in one statement:
Global.names = Global.names : [];
If you want to reset it, then:
Global.names = [];
or
delete Global.names;
Setting it to null is good, as you know that the variable exists but hasn't been assigned a value. This way you can easily see the state - if it's undefined then you've forgotten to declare it, if it's null it has been declared but never assigned a value, and if it's an Array then you can test the length from there.

Categories