JavaScript Conditional (Ternary), typeof, delete, void and await Operators
The remaining JavaScript operators: the conditional ?: operator and when nested ternaries hurt, typeof and its eight answers, what delete really removes (and why it leaves holes in arrays), void and why void 0 exists, and a first look at await. Ends Part 4 with a review quiz.
kvi5hnuCode Sprout team member8 min readOn this page
Part 4 finishes with the operators that don't fit a family: the conditional operator, the only operator with three operands, and four keyword operators: typeof, delete, void and await. They're small, but each comes with its own interview favorite.
The conditional operator: ?:
condition ? valueIfTruthy : valueIfFalsy evaluates the condition, then evaluates and returns only one of the other two operands:
const age = 20;
console.log(age >= 18 ? "adult" : "minor");
const n = -5;
console.log(n > 0 ? n : -n); // absolute value
const ran = [];
const left = () => { ran.push("left"); return 1; };
const right = () => { ran.push("right"); return 2; };
console.log(true ? left() : right(), ran); // right() never runs
adult
5
1 [ 'left' ]
It's often called "the ternary operator", since it's the only ternary one. Its value is the main reason to prefer it over if: if is a statement and produces no value, while ?: is an expression. You can use it inside a template literal, as an argument, in a return, or to initialize a const:
const label = `${count} ${count === 1 ? "item" : "items"}`;
const shipping = total >= 50 ? 0 : 4.99;
return isValid ? save(data) : reportErrors(data);
With if, the const case would need a let declared first and assigned in two branches.
Chained conditionals
The operator is right-associative (article 30), so conditionals can be chained like an else if ladder:
const sizeLabel = (count) =>
count === 0 ? "none"
: count === 1 ? "one"
: count < 10 ? "a few"
: "many";
console.log(sizeLabel(0), sizeLabel(1), sizeLabel(4), sizeLabel(50));
none one a few many
Laid out one condition per line, this reads well. What doesn't read well is nesting in the middle operand (a ? b ? x : y : z) or chains several levels deep on one line. When a conditional needs a comment to be understood, switch to if/else, switch, or a lookup object.
typeof
typeof value returns a string naming the value's type. Article 9 introduced it; here's the complete picture of its eight possible answers:

const samples = [undefined, null, true, NaN, 10n, "hi", Symbol("id"), () => {}, class Cart {}, [], new Date()];
for (const value of samples) {
console.log(typeof value);
}
undefined
object
boolean
number
bigint
string
symbol
function
function
object
object
Things to remember:
typeof nullis"object", a bug from the first version of JavaScript that can't be fixed without breaking the web. Test fornullwithvalue === null.- Functions, including classes, get
"function", even though they're objects. - Arrays, dates, regular expressions, maps and plain objects are all
"object". UseArray.isArray,instanceoforObject.prototype.toString.call(value)to tell them apart. typeofis the only way to touch an undeclared name without aReferenceError(article 29), which is why feature checks are written liketypeof window !== "undefined". It does not protect against the temporal dead zone:typeof xthrows ifxis aletdeclared later in the same scope (article 27).typeofbinds tightly:typeof a + bis(typeof a) + b. Writetypeof (a + b)when you mean the sum.
A safe helper for "is this a non-null object?" combines two checks:
const isObject = (v) => typeof v === "object" && v !== null;
console.log(isObject({}), isObject([]), isObject(null), isObject("text"));
true true false false
Is there any other value where typeof is surprising?
One, in browsers only: typeof document.all is "undefined", even though document.all exists and is an object. It's a deliberate compatibility hack from the early web, written into the specification, so that old code testing if (document.all) to detect Internet Explorer takes the standards path in modern browsers. You'll never need document.all; just don't be surprised by it in trivia questions.
delete
delete obj.prop removes a property from an object. Afterwards the property doesn't exist at all, which is different from setting it to undefined:
const point = { x: 1, y: 2 };
console.log(delete point.x, "x" in point, point);
const other = { x: 1, y: 2 };
other.x = undefined; // the property still exists
console.log("x" in other, Object.keys(other));
true false { y: 2 }
true [ 'x', 'y' ]
delete returns true when the property is gone afterwards, which includes deleting a property that never existed. It returns false (or throws, in strict mode) when the property can't be deleted.
What delete can't do
// 1. It only removes own properties. Inherited ones show through again.
const proto = { color: "red" };
const car = Object.create(proto);
car.color = "blue";
delete car.color;
console.log(car.color);
// 2. Non-configurable properties can't be deleted: false, or TypeError in strict mode.
const frozen = Object.freeze({ k: 1 });
console.log(Reflect.deleteProperty(frozen, "k"));
(function () {
"use strict";
try {
delete frozen.k;
} catch (err) {
console.log(err.name);
}
})();
// 3. Variables can't be deleted. In strict code, trying is a SyntaxError.
try {
new Function('"use strict"; let total = 1; delete total;');
} catch (err) {
console.log(err.name);
}
red
false
TypeError
SyntaxError
Reflect.deleteProperty(obj, key) is the function form: it returns true or false instead of throwing, in every mode.
delete on arrays leaves holes
Deleting an array element removes the index but doesn't shift the remaining elements or change the length. The result is a sparse array with a hole:
const letters = ["a", "b", "c"];
delete letters[1];
console.log(letters, letters.length, 1 in letters);
const fixed = ["a", "b", "c"];
fixed.splice(1, 1); // removes and shifts
console.log(fixed, fixed.toSpliced(0, 1)); // toSpliced (ES2023) returns a new array instead
[ 'a', <1 empty item>, 'c' ] 3 false
[ 'a', 'c' ] [ 'c' ]
To remove array elements, use splice, filter or the non-mutating toSpliced (part 7).
Better tools for removing data
- To create an object without some properties, without changing the original, use rest destructuring:
const { password, ...publicData } = user;(article 28). - For data that is added and removed constantly, a
Mapis designed for it:map.delete(key)is fast and returns whether the key existed. Frequently deleting properties from plain objects can make engines switch them to a slower internal representation.
void
void expression evaluates the expression and returns undefined, whatever the expression's value was:
console.log(void 0, void "hello", void (1 + 1));
undefined undefined undefined
It has three real-world appearances:
void 0as a guaranteedundefined. In old JavaScript, the globalundefinedcould be overwritten, so libraries wrotevoid 0. Since ES5, the globalundefinedis read-only, but minifiers still outputvoid 0because it's shorter thanundefined.javascript:void(0)links. An old way to make a link that does nothing when clicked. Use a<button>instead: it's accessible and needs no hack.- Discarding a value on purpose. In an arrow function,
() => void doSomething()returnsundefinedeven ifdoSomethingreturns a value, andvoid promisemarks a promise you intentionally don't wait for (some linters, like typescript-eslint'sno-floating-promises, accept this as "handled").
await
await is a unary operator that waits for a promise to settle without blocking the thread, then evaluates to its fulfillment value, or throws its rejection reason. It works inside async functions and at the top level of modules:
async function main() {
const value = await Promise.resolve("loaded");
console.log(value);
try {
await Promise.reject(new TypeError("bad input"));
} catch (err) {
console.log(err.name);
}
}
main();
loaded
TypeError
As a unary operator, it has high precedence, so await getUser().name awaits the name property of the promise; you want (await getUser()).name (article 30). Promises, async/await and their error handling are covered properly in part 13.
Operators at a glance
You've now seen every JavaScript operator. A one-line reminder of each group:
| Group | Operators | Article |
|---|---|---|
| Access and calls | . ?. [] () new | 29 |
| Arithmetic | + - * / % ** ++ -- unary + - | 31 |
| Bitwise | & | ^ ~ << >> >>> | 32 |
| Equality | === !== == != | 21, 23 |
| Relational | < > <= >= in instanceof | 33 |
| Logical | && || ! ?? | 34 |
| Assignment | = += and others, &&= ||= ??= | 35 |
| Other | ?: typeof delete void await , | 37, 30 |
Common questions
Is cond ? a : b faster than if?
No; engines compile them similarly. Choose based on whether you need a value (?:) or an action (if).
Can I omit the else part of a conditional, like cond ? x?
No, all three operands are required. For "value or nothing", use cond ? x : undefined, or cond && x when the falsy value of cond is acceptable as the result (article 34).
Does delete free memory?
Not directly. It removes a property, which removes one reference to the value. If nothing else refers to that value, the garbage collector can reclaim it later. Setting a variable or property to null has the same effect on reachability.
Why does typeof return "object" for arrays?
Arrays are objects with special handling of numeric keys and length. typeof only distinguishes primitive types, functions and "everything else". Array.isArray exists precisely because typeof can't tell.
Summary
cond ? a : breturns one of two values and evaluates only that one; use it for values,iffor actions, and keep chains flat.typeofreturns one of eight strings; remembertypeof null === "object", classes are"function", and only undeclared names (not TDZ variables) are safe to test.delete obj.propremoves an own, configurable property entirely; on arrays it leaves a hole, so usesplice,toSplicedorfilter. Use rest destructuring orMapwhen removing data often.void expralways givesundefined;void 0is a short, safeundefined.awaitunwraps a promise inside async code and has unary-operator precedence.
Practice Questions
Rewrite this with a conditional expression:
let fee;
if (isMember) {
fee = 0;
} else {
fee = 5;
}
Answer
const fee = isMember ? 0 : 5;. It also lets fee be a const.
What does typeof typeof null return, and why?
Answer
"string". typeof null is the string "object", and typeof of any string is "string".
After this code, what are list.length, list[0] and list.includes(undefined)?
const list = [10, 20, 30];
delete list[0];
Answer
3, undefined and true. The length doesn't change, reading a hole gives undefined, and includes treats holes as undefined. (indexOf(undefined) would return -1, because indexOf skips holes.)
Why might code from a minifier contain void 0 === x?
Answer
void 0 always evaluates to undefined and is three characters shorter than undefined. The minifier rewrites x === undefined that way to save bytes; the behavior is the same.
What's wrong with this line inside an async function?
const name = await fetchUser().name;
Answer
Calls and property access bind tighter than await, so fetchUser().name is evaluated first, which reads .name from the promise (undefined), and then await undefined gives undefined. Write const name = (await fetchUser()).name;.
Review quiz
You've finished Part 4. Check your understanding with the Expressions and Operators review quiz: 25 questions, mostly "what does this print?", on property access and optional chaining, precedence and evaluation order, arithmetic and +, bitwise operators, comparisons, in, instanceof, logical and assignment operators, eval, typeof and delete.
Previous: JavaScript eval(): Direct vs Indirect eval, Strict Mode and Safer Alternatives
Next: JavaScript Statements: Expression Statements, Blocks, Empty Statements and Declarations

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.