Simplest Way to Learn JavaScript Logical Assignment Operators.
Introduce JavaScript (ES12) logical assignment operators and write a easy example to learn it.
As title, this article is going to share the JavaScript Logical Assignment Operators include (||=
) (&&=
) (??=
) by writing a simple code .
And, will supplement the other logical operator (?.
) (??
). (All assignment can use in function)
( This also become my personal note about operators.)
Contents
- Logical OR assignment (||=)( || )Logical AND assignment (&&=)( && )
- Optional chaining (?.)
- Nullish coalescing operator (??) + Logical OR (||)
Logical OR assignment (||=
) ( || )
The logical OR assignment (x ||= y) operator only assigns if x is falsy.
(JavaScript falsy values : false
,0
,–0
,0n
, ” ”, ‘ ’, `` ,null
,undefined
,NaN
)
tips: x || y : returns x when x is truthy ; returns y when x is not truthy.
const a = { name: "amy", baby: 2, age: 0, hobbit: [], email: "" };console.log((a.name ||= "hey"));
console.log((a.baby ||= 10));
console.log((a.age ||= 10));
console.log((a.hobbit ||= ["1", "2"]));
console.log((a.email ||= "amy@com"));
result would be :
amy
2
10
[]
amy@com
function :
function A() {
console.log("called A");
return false;
}
function B() {
console.log("called B");
return true;
}console.log(B() || A());// result
>> called B
>> true
Logical AND assignment (&&=) (&&)
The logical AND assignment (x &&= y) operator only assigns if x is truthy.
(JavaScript truthy values : All values are truthy unless they are defined as falsy (i.e., except for false, 0, -0, 0n, “”, null, undefined, and NaN))
let a = 1;
let b = 0;
console.log(a && 2);
console.log(b && 2);
result would be :
2
0
Optional chaining (?.)
The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.
(Easy way to check value is undefined or not)
If the value before the question mark is neither undefined
nor null
, then perform the operation after the question mark.
Otherwise, return undefined
.
const adventurer = {
name: "Alice",
cat: {
name: "Dinah",
},
};const dogName = adventurer.dog?.name;
console.log(dogName);
console.log(adventurer.someNonExistentMethod?.());
const catName = adventurer.cat?.name;
console.log(catName);
result :
undefined
undefined
Dinah
just like &&
but more clean
const adventurer = {
name: "Alice",
cat: {
name: "Dinah",
},
};let catName_old = adventurer.cat && adventurer.cat.name;
console.log(catName_old);let catName_new = adventurer.cat ?.name;
console.log(catName_new);// result
Dinah
Dinah
nestedProp :
let obj = { first: { a: 1, b: 2, x: 25 } };
let temp = obj.first;
let res_old = temp === null || temp === undefined ?undefined : temp.x;console.log(res_old);let res_new = temp?.x;console.log(res_new);// result
25
25
other example :
let myMap = new Map();
myMap.set("foo", { name: "baz", desc: "inga" });let nameBar = myMap.get("bar")?.name;
console.log(nameBar);// result
undefined
With nested structures :
let customer = {
name: "Molly",
details: {
age: 18,
location: "taiwan",
},
};
let customerCity = customer.details?.address?.city;let customerName = customer.name?.getName?.();console.log(customerCity);
console.log(customerName);// result
undefined
undefined
Combining with the nullish coalescing operator :
let customer = {
name: "Molly",
details: { age: 18 },
};
const customerCity = customer?.city ?? "Unknown city";
console.log(customerCity);// result
Unknown city
Nullish coalescing operator (??)
The logical nullish assignment (x ??= y) operator only assigns if x is nullish (null
or undefined
).
The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null
or undefined
, and otherwise returns its left-hand side operand.
Super similar to ||, the most different is only when Nullish left-hand side is Null or Undefined then returns the value by right-hand side.
code would be like:
let user = {
name: "Amy",
age: null,
email: "",
isMan: false,
brothers: 0,
};console.log(user.age ?? 18);
console.log(user.isMan ?? "not sure");
console.log(user.name ?? "userName");
console.log(user.undefinedVal ?? "default");
console.log(user.email ?? "aaa");
console.log(user.brothers ?? 666);
tips : null
or undefined
, so , age
and undefinedVal
will return right side value.
result :
18
false
Amy
default
0
But if we use Logical OR (||)
let user = {
name: "Amy",
age: null,
email: "",
isMan: false,
brothers: 0,
};console.log(user.age || 18);
console.log(user.isMan || "not sure");
console.log(user.name || "userName");
console.log(user.undefinedVal || "default");
console.log(user.email || "aaa");
console.log(user.brothers || 666);
result :
18
not sure
Amy
default
aaa
666
tips: left side = null
or undefined
or false
or 0
or“empty string”
will return right side value .
function with Nullish
function A() {
console.log("a was called");
return undefined;
}function B() {
console.log("b was called");
return false;
}function C() {
console.log("c was called");
return "foo";
}console.log(A() ?? C());
console.log(B() ?? C());
Explanation:
First log:console.log(A() ?? C())
After A was called, A will return undefined
. First log is console.log( undefined ?? C() )
now. According to the tips , we know that if left-hand side is undefined
, right-hand side will be execute. C was called and return ‘foo’ , So the result is a was called -> c was called -> foo
.
Second log:console.log(B() ?? C())
Function B is return false, based on the rules , only null
and undefined
will go on to right-hand side, So, C will not be execute. Result is b was called -> false
.
Results would be like:
a was called
c was called
foob was called
false
another example:
function config(options) {
console.log(options.duration ?? 100);
console.log(options.speed ?? 25);
return options;
}config({ duration: 125 })
we call the function config
and put ‘duration’ in param , now console.log turns to console.log(125 ?? 100)
, so result :
125
25
if only call config({})
without param , result would be
100
25
Supplement :
Operator Equivalent to
a || b a ? a : b
a && b !a ? a : b
a ?? b a !== undefined && a !== null ? a : bAssignment operator Equivalent to Only assigns if a is
a ||= b a || (a = b) Falsy
a &&= b a && (a = b) Truthy
a ??= b a ?? (a = b) Nullish
Reference:
Done (ง •̀_•́)ง