JavaScript Expressions: Primary Expressions, Literals, Initializers and Property Access
What an expression is, the simplest ones (literals, keywords, identifiers), array and object initializers, function expressions, dot vs bracket property access, optional chaining with ?., ?.[] and ?.(), function and method calls, losing this, and new.
kvi5hnuCode Sprout team member9 min readOn this page
An expression is any piece of code that produces a value. 42 is an expression. So are price, price * 2, user.name, getTotal() and new Date(). A statement, by contrast, does something: let total = 0;, if (...) {...}, return x;. Statements often contain expressions, and many expressions can stand alone as statements (a function call on its own line is an expression statement).
Part 4 of the course covers every kind of expression and every operator. This first article covers the expressions that don't need an operator: the building blocks everything else is made of.
Primary expressions
The simplest expressions stand on their own and contain no smaller expressions. There are three kinds (the semicolons matter here: without them, the regular expression line would be read as a division continuing the template literal above it, article 8):
// 1. Literals: values written directly in the code
3.14;
"ready";
`template`;
/^\d+$/; // a regular expression literal (part 11)
10n; // a BigInt literal
// 2. Some reserved words
true;
false;
null;
this; // its value depends on where it's used (part 8)
// 3. Identifiers: names of variables, constants and functions
total;
Math;
undefined; // actually a read-only property of the global object (article 18)
When JavaScript meets an identifier, it looks it up through the scope chain (article 27). If no such variable exists anywhere, evaluating it throws a ReferenceError. The one exception is typeof, which returns "undefined" for undeclared names instead of throwing:
console.log(typeof undeclaredThing);
try {
undeclaredThing;
} catch (err) {
console.log(err.name);
}
undefined
ReferenceError
Array initializers
An array initializer (or array literal) is a comma-separated list of expressions inside square brackets. Each element is itself an expression, and it's evaluated every time the initializer runs, so the same literal can produce a different, brand-new array each time:
const makePair = (n) => [n, n * n];
console.log(makePair(3), makePair(4));
console.log(makePair(2) === makePair(2)); // two separate arrays
const grid = [[1, 2], [3, 4]]; // nested initializers
console.log(grid[1][0]);
const withHole = [1, , 3]; // an omitted element makes a hole
console.log(withHole.length, 1 in withHole);
console.log([1, 2,].length, [,].length); // one trailing comma is ignored
[ 3, 9 ] [ 4, 16 ]
false
3
3 false
2 1
Holes (missing elements) create sparse arrays, which behave oddly with some array methods. Part 7 covers them; in practice, avoid writing them. A single trailing comma is fine and common in multi-line arrays, because it keeps diffs clean when you add an element.
Object initializers
An object initializer (object literal) lists name: value pairs inside curly braces. Like array elements, the values are expressions evaluated each time:
const point = { x: 2, y: -1 };
const box = {
topLeft: { x: 0, y: 0 }, // nested object
size: 10 * 2, // any expression
};
Modern object literals can do much more: shorthand properties ({ x, y }), computed keys ({ [key]: value }), methods, getters and spread ({ ...defaults }). Part 6 covers them in full.
One parsing trap to remember: at the start of a statement, { begins a block, not an object. That's why destructuring assignment needs parentheses (article 28), and why an arrow function that returns an object literal needs them too: () => ({ ok: true }).
Function definition expressions
A function expression creates a function as a value, the same way an object literal creates an object:
const square = function (n) { return n * n; };
const cube = (n) => n ** 3; // arrow function expression
const factorial = function fact(n) { // a named function expression
return n <= 1 ? 1 : n * fact(n - 1);
};
console.log(square(4), cube(2), factorial(5), typeof fact);
16 8 120 undefined
The name fact in a named function expression is visible only inside that function, which makes it handy for recursion and for readable stack traces. Function declarations, arrow functions and the differences between them get a whole part of their own (part 8).
Property access: dot and brackets
There are two ways to read a property:
expression . identifier
expression [ expression ]
const product = { name: "Lamp", "sale price": 29, 2026: "model year" };
console.log(product.name);
console.log(product["sale price"]); // not a valid identifier: brackets required
console.log(product[2026], product["20" + "26"]);
const field = "name";
console.log(product[field]); // brackets evaluate the expression
console.log(product.field); // dot looks for a property literally called "field"
console.log(product.color); // a missing property gives undefined
Lamp
29
model year model year
Lamp
undefined
undefined
Use the dot when you know the name while writing the code and it's a valid identifier. Use brackets when the name is computed at run time, contains spaces or punctuation, starts with a digit, or is a symbol (article 19).
The last two lines show the classic beginner bug: product.field doesn't use the variable field; it looks for a property whose name is literally "field".
Keys are converted to strings
Inside brackets, the key is converted to a string (unless it's a symbol). Numbers become their decimal text, which is why arr[0] and arr["0"] are the same element. Objects become "[object Object]", a common source of mysterious bugs:
const visits = {};
const alice = { id: 1 }, bob = { id: 2 };
visits[alice] = 5;
visits[bob] = 9; // overwrites! both keys are "[object Object]"
console.log(visits[alice], Object.keys(visits));
9 [ '[object Object]' ]
If you need objects as keys, use a Map (part 11), which compares keys by identity.
Reading from null or undefined throws
null and undefined are the only values with no properties at all. Reading any property from them throws a TypeError, the most common runtime error in JavaScript ("Cannot read properties of undefined"):
const getSize = (item) => item.size;
try {
getSize(undefined);
} catch (err) {
console.log(err.name);
}
TypeError
Every other value can be read from, even primitives: "hi".length and (5).toFixed(1) work because JavaScript temporarily wraps the primitive in an object (article 14). Note the parentheses around 5: in 5.toFixed(1) the dot would be read as a decimal point, which is a SyntaxError.
Optional chaining: ?., ?.[] and ?.()
Optional chaining (ES2020) reads a property only if the value on its left is not null or undefined. Otherwise the whole expression evaluates to undefined instead of throwing:
const order = { id: 7, customer: null, items: ["pen"] };
console.log(order.customer?.name); // customer is null: undefined, no error
console.log(order.items?.[0]); // bracket form
console.log(order.customer?.address.city); // short-circuits the whole chain
const handlers = { onSave: () => "saved" };
console.log(handlers.onSave?.()); // call only if it exists
console.log(handlers.onLoad?.());
undefined
pen
undefined
saved
undefined

Short-circuiting covers the rest of the chain
In order.customer?.address.city, the plain .address and .city after the ?. would normally throw on null. They don't, because when ?. finds null/undefined, it skips everything to its right in the same chain. It doesn't evaluate anything further, including side effects:
let reads = 0;
let cache; // forgot to initialize
console.log(cache?.[reads++]); // short-circuits: reads++ never runs
console.log(reads);
try {
cache[reads++]; // a normal access evaluates reads++, then throws
} catch (err) {
console.log(err.name, reads);
}
undefined
0
TypeError 1
Two consequences:
- Only the value just before
?.is checked. Inorder.customer?.address.city, ifcustomerexists but has noaddress,.citystill throws. Put a?.at each level that may legitimately be missing:order.customer?.address?.city. - Parentheses end the chain.
(order.customer?.address).cityevaluates the parenthesized part toundefinedfirst, then reads.cityfrom it, and throws.
Three forms with method calls
These look similar but check different things:
| Expression | Throws when |
|---|---|
obj.run() | obj is nullish, or obj.run is not a function |
obj?.run() | obj exists but obj.run is not a function (a nullish obj gives undefined) |
obj.run?.() | obj is nullish, or obj.run exists but isn't a function |
?.() only checks for null and undefined. If the property holds something else, like a string, the call still throws a TypeError.
Where optional chaining isn't allowed
for (const code of ["config?.theme = 'dark'", "new config?.Builder()", "config?.tag`text`"]) {
try {
eval(code);
} catch (err) {
console.log(code.padEnd(24), err.name);
}
}
const config = { theme: "light" };
console.log(delete config?.theme, config); // delete is allowed
config?.theme = 'dark' SyntaxError
new config?.Builder() SyntaxError
config?.tag`text` SyntaxError
true {}
You can't assign through ?., construct with it, or use it with tagged templates. delete obj?.prop is allowed (and does nothing if obj is nullish).
Invocation expressions
A call is an expression followed by parentheses with zero or more argument expressions: f(1), Math.max(a, b), list.sort(). Evaluation happens in a fixed order:
- The function expression (before the parentheses) is evaluated.
- The arguments are evaluated, left to right.
- If the function value isn't callable, a
TypeErroris thrown. - Otherwise the function runs, and the call's value is whatever it returns (
undefinedwithout areturn).
Step 3 comes after step 2, so arguments with side effects run even when the call fails:
const log = [];
const arg = (v) => { log.push(`arg ${v}`); return v; };
const notAFunction = 42;
try {
notAFunction(arg(1), arg(2));
} catch (err) {
log.push(err.name);
}
console.log(log.join(", "));
arg 1, arg 2, TypeError
Method calls and this
When the function expression is a property access, as in cart.add(item), the call is a method call, and inside the function this refers to the object before the dot (cart). The link exists only at the moment of the call. If you take the method out of its object and call it on its own, this is lost:
class Counter {
count = 0;
increment() { return ++this.count; }
}
const counter = new Counter();
console.log(counter.increment()); // a method call: this is counter
const inc = counter.increment; // just the function, no object attached
try {
inc();
} catch (err) {
console.log(err.name); // this is undefined inside the class code
}
const bound = counter.increment.bind(counter);
console.log(bound());
1
TypeError
2
This is behind many bugs with callbacks, such as setTimeout(counter.increment, 100) or button.addEventListener("click", obj.handle). The fixes (bind, arrow functions, class fields with arrows) are covered in part 8.
Object creation expressions
An object creation expression is a call prefixed with new. It creates a new object and runs a constructor to initialize it:
new Date(2026, 0, 1)
new Map()
new Error("disk full")
With no arguments, the parentheses are optional: new Map works. But mixing that with a method call is confusing, because new without parentheses binds to the whole member expression on its right:
console.log(new Date(0).getTime()); // (new Date(0)).getTime()
try {
eval("new Date.getTime()"); // new (Date.getTime)(): not a constructor
} catch (err) {
console.log(err.name);
}
0
TypeError
Always write the parentheses: new Map(). Constructors and classes are covered in part 9.
Common questions
What's the difference between an expression and a statement?
An expression produces a value and can appear wherever a value is expected: as an argument, on the right of =, inside ${}. A statement performs an action and can't be used as a value: you can't write const x = if (a) {...}. That's why the ternary operator (a ? b : c), an expression, exists alongside if, a statement. Part 5 covers statements.
Is obj?.a.b the same as obj?.a?.b?
No. obj?.a.b protects only against obj being nullish. If obj exists but obj.a is undefined, reading .b throws. obj?.a?.b protects both levels.
Does ?. check whether the property exists?
No. It checks whether the value on its left is null or undefined. A missing property already gives undefined with a plain dot, without throwing; the throwing happens on the next access. obj?.prop only helps when obj itself may be nullish.
Why does 5.toString() fail but 5..toString() works?
After 5, the first dot is read as part of the number (a decimal point). In 5..toString(), the first dot completes the number 5. and the second is property access. Writing (5).toString() is clearer.
Is obj["key"] slower than obj.key?
For a constant string, engines treat them the same. Computed keys in hot loops can be a little slower, but choose by readability: dots when you can, brackets when you must.
Summary
- Expressions produce values; primary expressions are literals,
true/false/null/this, and identifiers (an unknown identifier throwsReferenceError, except withtypeof). - Array and object initializers create a new array or object every time they're evaluated; avoid holes like
[1, , 3]. - Dot notation needs a fixed, valid identifier; brackets take any expression, converted to a string key (objects become
"[object Object]"). - Reading a property of
nullorundefinedthrows aTypeError; a missing property is justundefined. ?.,?.[]and?.()stop onnull/undefinedand short-circuit the rest of the chain, side effects included. They can't be used for assignment,newor tagged templates.- Calls evaluate the function, then the arguments, then check callability. A method call sets
thisto the object before the dot, and extracting the method loses it. - Write
new Thing()with parentheses.
Practice Questions
What does this code print, and why?
const tags = {};
tags[["a", "b"]] = 1;
console.log(Object.keys(tags));
Answer
[ 'a,b' ]. The array key is converted to a string, and an array's string form joins its elements with commas.
Given this object, which of these throw: user.profile.photo, user.profile.photo.url, user.profile.photo?.url, user.account?.id?
const user = { profile: {} };
Answer
Only user.profile.photo.url throws: photo is undefined, and reading .url from it is a TypeError. The first gives undefined (a missing property), and the other two are protected by ?..
Starting from this code, what is n after list?.at(n++), and after list?.at(n++) ?? n++?
let n = 0;
const list = null;
Answer
After the first, n is 0: the chain short-circuits before the argument is evaluated. After the second, n is 1: the chain gives undefined, so ?? evaluates its right side n++.
Why does this code fail when sayHi uses this.name?
const greet = person.sayHi;
greet();
Answer
greet is the bare function. Called without an object before a dot, this is undefined (in strict code, which includes classes and modules), so this.name throws. Call it as person.sayHi() or bind it: person.sayHi.bind(person).
Rewrite this code with optional chaining.
if (options && options.onDone) {
options.onDone(result);
}
Answer
options?.onDone?.(result);. The first ?. handles a missing options, the second a missing callback.
Previous: Destructuring in JavaScript: Arrays, Objects, Defaults, Renaming and Nested Patterns
Next: JavaScript Operator Precedence, Associativity and Evaluation Order

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.