Skip to the workspace
Pebellslearn by building
Expressions & Operators  ›  Lesson

Ternary and Comma Operators

Conditional Operators 12 min

javascript / Ternary and Comma Operators

Explore each scene at your own pace.

01 · Ternary and Comma Operators

Ternary and Comma Operators

Ternary and Comma Operators

The conditional operator chooses one of two expressions. The comma operator evaluates expressions left to right and returns the last result.

Use condition ? oneValue : anotherValue when you need a value from a simple decision.

See the mechanism

Walk through the modelTernary and Comma OperatorsAuthored snapshots of the example; use Run below to test the code.
savedfalse
A boolean selects between two expressions.
1 of 3

Follow one example

javascript

Only the chosen conditional branch is evaluated. false chooses "Save article". In the parenthesized comma expression, count changes to 1 before the last expression produces 2. Commas separating function arguments or array elements are not this operator. Prefer separate statements when a comma expression makes code harder to follow.

Predict, change and check

Predict: If saved becomes true, will both strings be returned or only one?

Test your explanation: Flip saved and compare the label. Rewrite the comma expression as two statements and confirm count and result do not change.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

An expression is not a block of statements

The conditional operator evaluates one of its two result expressions and returns that selected value. A nested chain can hide precedence and branch intent, so extract a named helper or use statements when the policy becomes hard to scan.

The comma operator evaluates expressions from left to right and yields the final expression's value. Commas separating function arguments or array elements are syntax separators, not necessarily uses of that operator. Parenthesize the intended comma expression in an experiment so you are testing the operation you mean.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.