This content originally appeared on DEV Community and was authored by tywenk
Gotta go fast
Why waste time say lot word when few word do trick?
This is perhaps the insidious mantra of programmers the world over. Too busy hacking into the mainframe they have no time for multisyllabic variable names. They don't have the bandwidth in their own minds to cache long winded expressions. They would rather use --nay, they NEED to use-- terse, to-the-point, language to snipe their bits out of the sky. Like a painter at an easel, a programmer at a greasy keyboard feels the gravitational pull, the irresistible urge, the hypnotic Siren's song... to use shorthand expressions.
Wise programmers often warn young programmers to not adopt this mentality, especially while learning how to code. It can become a bad habit that can in cases lead to harder to read, harder to maintain, and harder to update code. That said, in my explorations of the topic, I found it useful to discover (to my delight) that a) there are proper places to use it, and b) people do use them and you should know how to read them. This blog is about the ternary expression and its tangent cousins -- the AND and the OR operators -- and how they can be used to write succinct yet still straightforward code.
The Ternary Expression
Ternary expressions are a shorthand way to write if else
statements.
Ternary expressions threw me off early on. The semantic structure of if else
statement was easy to understand. If this expression returns truthy, then execute this expression. If it is not truthy, execute this other expression. Why fix something that ain't broke?
The strange syntax of a ?
and the trailing :
were confusing. I think it's because when reading a line of code, the ?
and :
can be easily lost in the jumble of text and numbers.
Here's a breakdown of it, in plain English:
if this is true ?
then do this :
otherwise do this
The usefulness of ternary expressions comes in handy when you want a single-line way to assign a variable a value dependent on another variable. Let's take these three lines that return a isFullyCharged
as true
if our battery level is at 100%.
const batteryLevel = 26;
const isFullyCharged = batteryLevel == 100 ? true : false;
return isFullyCharged;
//false
Written out as an if else
statement, and assuming we still want to return a new boolean variable, it comes out much longer.
const batteryLevel = 26;
let isFullyCharged;
if (batteryLevel == 100){
isFullyCharged = true;
} else {
isFullyCharged = false;
}
return isFullyCharged;
Ternary expressions are useful then for concise single-line checks that are actually quite readable once their at first strange syntax can be overcome.
And, as I've read more about them, they can also simplify more complex situations, like nested checks, in which case using chained ternary expressions results in cleaner and less bug prone code.
The Logical OR Assignment
The logical OR operator can be used in many ways, but the one I will discuss here is its use as a way to check a value before assignment to a variable.
The OR operator, denoted as ||
, can be used in the primary statement to return a true
or false
value.
The ||
operator typically takes two expressions on either side of it. Take this example:
let a = 5
let b = 1
return b > a || a > b
This short program returns a true
or false
boolean. The OR operator is executed left to right. First b > a
is checked to be true. In this case, b
is smaller than a
, so the expression returns false
. Upon this return the ||
operator then returns the value of the expression on its right. In this case, a > b
returns true, because 5 is a larger number than 1, so as a result the entire expression returns true.
When it comes to logical OR assignment can be used as a checker to ensure a value is empty before assigning it. For instance, this example:
let name
return name ||= "No name"
The ||=
operator only assigns name
to "No name"
if name
is falsy.
The output of this program will be "No name". The ||=
shorthand is a way to check if the value on the left is falsy before assigning it to the value on the right. In this case, name
is declared but undefined, so has the value undefined
. In Javascript, undefined
is considered a falsy value, so as an primitive value it returns false
. Because the left expression is false, the right expression is executed.
This might become more clear if the name ||= "No name"
expression is pulled apart, into its non-shorthand components. That expression is equivalent to name || (name = "No name")
!
This is worth reiterating, the following two expressions are equivalent, and both assign "No name" to name
:
name ||= "No name"
name || (name = "No name")
This is easier to read, as it more closely resembles the typical OR expression. In essence, this shorthand is a quick way to check if the value of name
is falsy before deciding to assign it a value. This can be useful when you don't want to overwrite a variable or if you don't want to return undefined
and only return a legible string instead.
Using the ||=
is also completely different from assigning a variable to an OR expression. For instance, name = "No name" || "Other name
is valid, and will assign name to "No name"
, but it does so through a different means than the ||=
The Logical AND Assignment
The logical AND is much like the OR. Instead denoted as &&
, it is also an operator that takes in two values, one of the left and one on the right. In this case, both the left and right values must convert into truthy values for the second value to be returned. Otherwise the first value is returned. This evaluation is executed left to right. If the left value converts to falsy, the right value is never evaluated and the entire AND expression returns false. However if both execute as truthy, then the second value will be returned.
So take the example:
let name
name = '' && 'Bob'; // name is assigned ''
name = 'Bob' && 'Jill'; // name is assigned "Jill
In the first expression, ''
is an empty string and considered falsy. The entire && expression then returns the first value, which is falsely, and short circuits the entire expression. In the second expression, name
is assigned to 'Jill'
because both strings 'Bob'
and 'Jill'
return truthy, and so both are evaluated. Because both evaluate true, the second value is returned.
Now we go onto the logical AND assignment:
let name
let lastname = "Exists"
name &&= "Tywen"
lastname &&= "Kelly
When it comes to the logical AND assignment, denoted by &&=
, the expression only assigns name
to "Tywen"
if name is truthy. name
is actually falsy, as it is undefined, so name is not assigned the value "Tywen"
. lastname
on the other hand is assigned a truthy value of "Exists"
, so when it comes time to assign it with a logical AND assignment, it successfully assigns it to "Kelly"
.
This content originally appeared on DEV Community and was authored by tywenk
tywenk | Sciencx (2022-04-12T19:37:25+00:00) Javascript Shorthands: Ternary, Logical || and && Assignments. Retrieved from https://www.scien.cx/2022/04/12/javascript-shorthands-ternary-logical-and-assignments/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.