Prefix vs Postfix Operator

avatar


image.png

Image Source

The postfix/prefix operation which usually involves either increment or decrement is a popular topic in every programming language. Both of these operators are used to increment or decrement the value of variable by 1 but there is a sligh difference in working of these two operators. Postfix operator is when operator comes after the variable. For example: a++, a--. Prefix operator is when operator comes before the variable. For example: ++a, --a. We will see a simple example to see the basic difference between these two in JavaScript.

image.png

In line number 7 of the above picture we have printed the postfix increment value. We have defined the value of a to be 3 and postfix increment will increment the value of variable a by 1 but it returns the original value which is 3. Whereas, in line number 10, the prefix operator increments the value of x by 1 and returns the new value which is 4. The same goes with other operator like subtraction and multiplication. The code as in the picture is here:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Prefix and Postfix</title>
<script>
    var a=3;
    document.write("<h3>" + "The postfix operation value is: " + a++ + "</h3>");
   
    var x=3;
    document.write("<h3>" + "The prefix operation value is: " + ++x + "</h3>");
</script>
</head>
<body>
</body>
</html>

The browser also shows the desired output:

image.png

So that's the basic difference between the prefix and postfix operator.



0
0
0.000
0 comments