Thursday, 3 July 2014

Chapter 9: JavaScript Modulus / Increment / Decrement

Modulus

In JavaScript we have modulus or remainder operator. The one is little different. Probably the classic example is using it to do something like calculating a year. So in this case I create a variable called year that is equal to 2003 and I can’t variable named remainder and I set that equal to year % 4. The Percent here is modulus or remainder operator. What it means is divide the variable year ( 2003) by 4. This don’t give me the result. Give me the remainder. In this case 4 will go to year 500 times, and the remainder would be 3.
Example:
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<div id="demo">
<h1>This is a heading.</h1>
<p>This is a paragraph.</p>
</div>
<script>
var year = 2003;
var reminder = year%4;

console.log(reminder);


</script>
</body>
</html>




Increment and Decrement
Next we have shorthand for adding to a variable. We already saw this but let’s explain in wider.
How you know we can use this:
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<div id="demo">
<h1>This is a heading.</h1>
<p>This is a paragraph.</p>
</div>
<script>
var a = 10;

console.log(a = a + 1);

</script>
</body>
</html>
or we can use that:

<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<div id="demo">
<h1>This is a heading.</h1>
<p>This is a paragraph.</p>
</div>
<script>
var a = 10;

console.log(a += 1);

</script>
</body>
</html>

OR

<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<div id="demo">
<h1>This is a heading.</h1>
<p>This is a paragraph.</p>
</div>
<script>
var a = 10;
var increment = ++a;

console.log(increment);

</script>
</body>
</html>

The result of all would be variable a + 1;

The above example is used to increment the variable a.
But we can use it also to decrement it.
Example:
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<div id="demo">
<h1>This is a heading.</h1>
<p>This is a paragraph.</p>
</div>
<script>
var a = 10;
var b = 20;
var c = 30;

console.log(--a);
console.log(b = b - 1);
console.log(c -= 1);

</script>
</body>

</html>