Nodejs' try (check) for undefined [duplicate] - javascript

This question already has answers here:
Null-safe property access (and conditional assignment) in ES6/2015
(11 answers)
Closed 2 years ago.
In ruby we something like a.try(:property) even if a is nil(undefined) program won't throw an exception and keep going. But for nodejs/javascript if I have a.property and a is undefined program will throw an exception. I have to do something like
if (a) {
a.property
}
It is quite tedious and unpretty.
Is there something in nodejs similar like a.try(:property) so I don't have to check before I use a property?

I dont think there's any function like that in node.js. But you could build your own utility function like this...
// utility function
let tryProp = (a, p) => ( a? (a[p] ? a[p] : null) : null);
// Testing if property exists.
let x;
x = { key: "value"};
console.log(tryProp(x, 'john')); // returns null
console.log(tryProp(x, 'key')); // returns value
// Incase variable is undefined
let y;
console.log(tryProp(y, 'key')); // returns null

Related

What does "?." (dot after questiion mark) mean in JS [duplicate]

This question already has an answer here:
What does this symbol mean in JavaScript?
(1 answer)
Closed 2 years ago.
I stumbled upon the "?." syntax in another SO question. Something like this -
console.log(x?.y?.z);
What does it do?
This is called Optional Chaining.
It allows to use the property chaining without having to validate properties in each level. It short circuits property evaluation without raising exceptions - thus avoiding the "Cannot read X of undefined" error.
let o = {p: {q: 'foo'}};
try {
console.log('Trying to access the property x');
console.log(o.x.y);
}
catch(e) {
console.log('That was an error');
}
console.log('Trying to access the property x with Optional Chaining');
console.log(o?.x?.y);
Optional chaining more use cases
With function calls
let result = someInterface.customMethod?.();
With expressions
let nestedProp = obj?.['prop' + 'Name'];
With array elements
let arrayItem = arr?.[42];
ECMAScript Draft

How do I prevent TypeError blank is undefined? [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 3 years ago.
Is there an easier way to check if a variable is defined or not in JavaScript when the target is deep within an object?
For example.
// Lets assume this:
response = {
status: "simple-message"
}
// running this:
if (response.data.variable_to_check !== undefined) console.log('undefined');
// will result in this:
> TypeError: response.data is undefined
In PHP I can run the equivalent check:
if (!($response->data->variable_to_check ?? false)) die("Handled Undefined Error");
// will result in this:
> Handled Undefined Error
I know I can iterate manually by checking each item starting with the root to see if it's defined, but that seems tedious. That and wrapping everything in a try/catch.
Is there a cleaner / faster / smarter way to do this?
Use
try{
if(response.data.variable_to_check!==undefined){
console.log("undefined");
}
}
catch(err){console.log(err.message)}

Why 1["foo"] returns undefined instead of an error? [duplicate]

This question already has answers here:
How and why does 'a'['toUpperCase']() in JavaScript work?
(12 answers)
Why is 0[0] syntactically valid?
(7 answers)
Closed 4 years ago.
Today I came accross a strange thing in Javascript.
When in Chrome console if I execute :
> 1["foo"]
Chrome console returns :
undefined
I was expecting an error though. How is it possible? I fall on that by studying the underscore.js (an old version) invoke method that seems to use that JavaScript property:
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
var isFunc = _.isFunction(method);
return _.map(obj, function(value) {
var func = isFunc ? method : value[method];
return func == null ? func : func.apply(value, args);
});
};
As you can see, value could be a number and if 1["foo"] was raising an error, that code would be unsafe as I could do the following by mistake:
var a = {'foo' : 1}
_.invoke(a, 'foo'}
Everything, even primitives, are essentially objects and can have members (properties, methods, etc). All the code in question is doing is attempting to find a member on 1 with the name foo which is not found so undefined is returned.

Javascript - how to check if the parent object is not undefined? [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 5 years ago.
I find I'm doing this, whereby I need to check that the preceeding variable is not undefined before checking the next one in the chain:
if( this.props.someVar && this.props.someVar.data ) {
// do something with this.props.someVar.data ...
}
It would be ideal just to do this:
if( this.props.someVar.data ) {
// This throws an error because I haven't checked if `this.props.someVar` exists beforehand.
}
Is there an easier/shorter way to so this, preferably using pure Javascript?
I hate that too. The easiest way is to use try catch like this
try {
// do something with this.props.someVar.data
} catch (e) {
if (e instanceof TypeError) {
// TypeError happens when an object in the chain is undefined
}
}

Store extra properties in a javascript integer [duplicate]

This question already has answers here:
Javascript assigning value to primitive
(2 answers)
Closed 8 years ago.
Consider this excerpt from a node.js REPL session:
> var a = 5;
undefined
> a.b = true;
true
> a.b;
undefined
The intention is to store extra properties in a, which if successful would make the final line be true instead of undefined. How can I do this?
You cannot do that. A number is not an object in JavaScript. When you write:
a.b = true;
what happens is that the runtime instantiates a Number instance automatically. That's an object. You set the "b" property on that object to true, and then it's forgotten.
Now, you can do this:
var a = new Number(5);
a.b = true;
alert(a.b);
and it'll work just fine.

Categories