DEV Community

Judith ☁ Oiku
Judith ☁ Oiku

Posted on

2 1

Understanding increment / decrement PREFIX or POSTPREFIX operator

Key:

Increment or Decrement operator can appear in two forms, the POSTPREFIX x++ or x-- and PREFIX ++x or --x and it can be quite confusing.

Understanding how both works will enable you know how to apply them in your project.

POSTPREFIX

This returns the value of its operand BEFORE adding 1 to it - Increment

This returns the value of its operand BEFORE subtracting 1 from it - Decrement


// increment 

let x = 2

const r1 = x++ = 2 //it returned the valued the value before adding 1, meanwhile x is 3 

const r2 = x++ + 2 = 5 
Enter fullscreen mode Exit fullscreen mode

// decrement

let x = 5

const r3 = x-- = 5 //it returned the value before subtracting 1, x= 4

const r4 = x-- + 2 = 6
Enter fullscreen mode Exit fullscreen mode

PREFIX

This returns the value of its operand AFTER adding 1 to it - Increment

This returns the value of its operand AFTER subtracting 1 from it - Decrement

let x = 5

const r5 = ++x = 6 //it returned the value after adding 1

const r6 = ++x + 2 = 9
Enter fullscreen mode Exit fullscreen mode
let x = 5

const r7 = --x = 4 //it returned  the value after subtracting 1

const r8 = --x + 2 = 5
Enter fullscreen mode Exit fullscreen mode

Let's mix both and see how it works

let x = 1

const a = x++ + x++= 3 

const b = ++x + ++x = 9

const c = x++ + ++x = 12

const d = ++x + x++ = 16
Enter fullscreen mode Exit fullscreen mode

try it out on your favorite code editor or you can view it on codepen

https://codepen.io/ojudith/pen/MWwZQxB

AWS Q Developer image

Your AI Code Assistant

Implement features, document your code, or refactor your projects.
Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay