Concept Flow - Unary operators
Start with a value
Apply unary operator
Evaluate result
Use result in expression or output
Unary operators take one value and perform an operation on it, producing a new value.
let x = 5; let y = -x; let z = ++x; console.log(y, x, z);
| Step | Code Line | Variable States | Operation | Result/Output |
|---|---|---|---|---|
| 1 | let x = 5; | x=undefined -> x=5 | Assign 5 to x | x=5 |
| 2 | let y = -x; | x=5, y=undefined | Negate x | y = -5 |
| 3 | let z = ++x; | x=5, y=-5, z=undefined | Pre-increment x (x=x+1) | x=6, z=6 |
| 4 | console.log(y, x, z); | x=6, y=-5, z=6 | Output values | Prints: -5 6 6 |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| x | undefined | 5 | 5 | 6 | 6 |
| y | undefined | undefined | -5 | -5 | -5 |
| z | undefined | undefined | undefined | 6 | 6 |
Unary operators act on one value. Examples: -x (negation), ++x (pre-increment), x++ (post-increment). Pre-increment changes value before use; post-increment after. Used to quickly change or check a single variable. Common in expressions and loops.