This question already has answers here:
Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?
(22 answers)
Closed 4 years ago.
I'm wondering if there's a shorthand way to write something like this in JavaScript
if (thingExists) {
thingExists.manipulate
}
I think I remember seeing something along the lines of
thingExists?.manipulate
but that may have been TypeScript or something.
Anyway, any knowledge on that matter is appreciated,
Thanks!
You can use && for short circuiting:
thingExists && thingExists.manipulate
thingExists.manipulate will be evaluated if and only if thingExists is truthy.
Example:
var obj = { func: function() { console.log("func is called"); } };
obj && obj.func(); // => func is called
var falsy = null;
falsy && falsy.imaginaryFunc(); // => nothing
Related
This question already has answers here:
What is the !! (not not) operator in JavaScript?
(42 answers)
Closed 4 years ago.
I brow some code in javascript, found some code of function like that
function isPromise(obj) {
return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
}
As what I say to the title, why this function use !!obj" ??
If you are referring to "double bang" in JavaScript it is a force coercion falsely or truthy to its boolean true or false
See this answer:
What is the !! (not not) operator in JavaScript?
This question already has answers here:
What is "x && foo()"?
(5 answers)
What does this symbol mean in JavaScript?
(1 answer)
What a strange syntax?
(3 answers)
Closed 4 years ago.
jBox.prototype.position = function (options)
{
// this line
!options && (options = {});
}
In conventional programming boolean statements are used in if else statements.
What does !options && (options = {}); translate too?
options is a json or array. What does !options mean?
options = {} is assigning a empty json to variable options, how does it return a boolean value to be used with &&.
The code:
!options && (options = {});
is the equivalent of:
if(!options) {
options = {};
}
It means that if options is a falsy value (empty) then initialize it with an empty object literal.
This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 5 years ago.
I have a large json object. I need to access x = a.b.c.d.e.f.g. However b (or c, d, e...) can be undefined. This data structure is being imported from somewhere else.
Is there a way to try to get to assign x with null or undefined without throwing an error?
Update
Optional chaining is now part of the ECMAScript spec and can be used on most javascript clients (browsers, node.js, etc)
x = a.b?.c?.d?.e?.f?.g
To use a default value if the access fails you can use the Nullish coalescing operator (??)
x = a.b?.c?.d?.e?.f?.g ?? 'my default value'
original answer (2017)
The easiest way is to use try catch
try {
x = a.b.c.d.e.f.g
} catch(e) {
x = undefined;
}
There is a proposal for this called optional chaining you can check it here: https://github.com/tc39/proposal-optional-chaining
x = a.b?.c?.d?.e?.f?.g
If you are using a transpiler you'll be able to use it, however its still in the very early stages and might not be accepted to be supported in the spec
There are some proposals to solve this ( syntactic sugar missing) problem. Hopefully somewhen we may do this:
let x = a?.b?.c?.d?.e;
However, until then we need to fall back to objects if the variable is undefined:
var x =( ( ( ( (a || {}).b || {} ) || {} ).c || {} ).d || {}).e;
I admit that this is quite ugly. Maybe object destructuring is more beautiful:
let ({
b: {
c: {
d: { e:x } = {}
} = {}
} = {}
}) = a;
This question already has answers here:
Accessing Properties in object [duplicate]
(3 answers)
Closed 7 years ago.
I used to believe that there is no difference between them but after seeing this piece of code, all my information about objects in Javascript failed.
var search = function(name) {
for(var x in friends) {
if(friends[x].firstName === name) {
console.log(friends[x]);
return friends[x];
}
}
};
This code works. But
var search = function(name) {
for(var x in friends) {
if(friends.x.firstName === name) {
console.log(friends.x);
return friends.x;
}
}
};
this doesn't.
Thanks for explaining.
friends.x is not the same thing as friends[x], it's the same thing as friends['x'].
When you use friends[x] the value x can be a variable (or any expression), but when you use friends.x the x is a literal name, it won't use the variable x.
As #Guffa already explained, friends.x and friends['x'] are the same, the difference in those approaches is that when you use [] this syntax you can use variables, 'property like this', or reserved words, this is good when you do not know exactly the property you will need.
This question already has answers here:
Is there a better way to do optional function parameters in JavaScript? [duplicate]
(28 answers)
Closed 8 years ago.
In PHP I can do something like this:
public myFunction($variable=0) {
//Do some stuff
}
In Javascript, the following does not work:
var myFunction = function(variable=0 )
{
//do some stuff...
};
Try this
var myFunction = function(variable) {
variable = variable || 0;
// this variant works for all falsy values "", false, null, undefined...
// if you need check only undefiend, use this variant
// variable = typeof(variable) == 'undefined' ? 0 : variable
};
Default function parameters will be in ES6; ES5 does not allow it.
With ECMAScript 6 you can do this.
Check an example:
function multiply(a, b = 1) {
return a*b;
}
multiply(5); // 5
But this is still experimental and today is only supported by Mozilla Firefox browser.
Check this link do see documentantion:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters#Browser_compatibility