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
Related
This question already has answers here:
Optional Chaining in JavaScript [duplicate]
(8 answers)
Closed 2 years ago.
I met in code condition line like this someObject.arrParam?.length. What syntax is that? How does that question mark thing's called? I know an optional operator which used for parameters in functions. Is that a variation of usage of it? Never met before.
This is called Optional Chaining in JavaScript. It allows to drill
down on objects without raising null exception.
Eg: Try running the below code snippet, then uncomment the line and run it to understand a working example.
let employeeA ={ name: "Dane", address : { city:"London"}}
let employeeB ={ name: "John"}
console.log(employeeA.address.city)
// console.log(employeeB.address.city) <---- this will raise an error
console.log(employeeB.address?.city) // <--- this wont
This was introduced as new feature in the latest ESNext iterations.
NodeJS Support : https://node.green/#ES2020-features-optional-chaining-operator-----
Current Browser Support : https://caniuse.com/#feat=mdn-javascript_operators_optional_chaining
More Details here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
That is called Optional Chaining (or conditional chaining) which basically will evaluate the whole expression as undefined if arrParam is undefined or null.
It's called "Conditional (ternary) operator".
result=condition?ifTrue:ifFalse
In x=(y>10)?100:1, if y>10, x is set to 100, else, x is set to 1.
Equivalent to:
if(y>10) x=100;
else x= 1;
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
This question already has answers here:
JS/ES6: Destructuring of undefined
(8 answers)
Avoid an error when destructuring from undefined
(3 answers)
Closed 3 years ago.
I'm a big fan of destructuring and optional chaining proposal in Javascript.
I couldn't help but feel that when destructuring a null or undefined value it'd be really useful if the result would be undefined as it is in optional chaining instead of throwing an error.
For example:
const person = null
console.log(person?.age) // undefined
However:
const person = null
const { age } = person // runtime error
It doesn't work like this of course but is there some Babel proposal to add this feature? Is there some workaround?
It sounds like you might just want to use || {} to destructure an empty object in case person is is null (and happens to also apply if it's otherwise falsey too):
const person = null
const { age } = person || {};
console.log(age);
You can use a default value using ||,
const person = null
const { age } = person || {}
console.log(age)
Short circuiting in JavaScript
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.
This question already has answers here:
What characters are valid for JavaScript variable names?
(12 answers)
Closed 7 years ago.
I am coding a scientific calculator and I need some help:
function √(in){
return Math.sqrt();
}
// throws an error
var √ = function(in){
return Math.sqrt();
}
// also throws an error
var √ = "sqrt";
√randomSqNum = 100,
√random = {sqrt:4,cubert:8},
√sqNum = ["0","1","4","9","16","25"],
√null = null,
√undefined = undefined;
They all throw an error!
Please explain why they throw an error.
Also, Is there a way around this?
In Javascript, variable names must begin with a letter, _ or $. More information here:
http://www.w3schools.com/js/js_variables.asp
JavaScript follows annex 31 of the unicode standard regarding identifier names.
I assume you are using U+221A as character. As you can see from the linked page, it can neither be used at the beginning of an identifier nor within it:
(likely because it is not even a letter).
Compare that to π, which is a letter and which can be used in an identifier name.
Also, Is there a way around this?
No. However, you can always try to find letters that look similar.
You cannot use it directly as a name, but you can use it as key.
var f={}
f["√"] = Math.sqrt
alert(f["√"](5))
In such way you can define +-*/ and many other funcions.
f["+"] = function(a){
return a.reduce(function(p,v){
return p+v
},0)
}
And when you have a parsed statement tree in form {o:fn,a:[s1,...,sn]} where fn is function name and s1,...,sn are subtrees or values, then you can simply get the result:
function calc(st){
return (typeof st == 'object')?f[st.o].apply(null,st.a.map(calc)):st
}