Why avoid increment ( ++ ) and decrement ( -- ) operators in JavaScript?
My view is to always use ++ and -- by themselves on a single line, as in:
i++;
array[i] = foo;
instead of
array[++i] = foo;
Anything beyond that can be confusing to some programmers and is just not worth it in my view. For loops are an exception, as the use of the increment operator is idiomatic and thus always clear.
my add to cart and increment and decrement button are not working
Add missing () after function like below:
$(document).ready(function(){
//Write here
})
Correct spelling for 'parsint' to 'parseInt'.
$(document).ready(function() {
$('.addtoCartbtn').click(function (e) {
e.preventDefault();
var product_id= $('.prod_id').val();
var product_qty= $('.qty-input').val();
alert(product_id);
alert(product_qty);
});
$(".increment-btn").click(function (e) {
e.preventDefault();
var inc_value=$(".qty-input").val();
var value= parseInt(inc_value,10);
value= isNaN(value) ? '0': value;
if(value < 10){
value++;
$(".qty-input").val(value);
}
});
$('.decrement-btn').click(function (e) {
e.preventDefault();
var dec_value= $('.qty-input').val();
var value= parseInt(dec_value,10);
value= isNaN(value) ? '0': value;
if(value > 1){
value--;
$('.qty-input').val(value);
}
});
});
The unexpected ++ error in jslint
The longstanding best practice: use i += 1
instead, following jslint's advice.
As for why it is a better practice than ++
, according to Crockford:
The increment
++
and decrement--
operators make it possible to write in an extremely terse style. In languages such as C, they made it possible to write one-liners that:for (p = src, q = dest; !*p; p++, q++) *q = *p;
Most of the buffer overrun bugs that created terrible security vulnerabilities were due to code like this. In my own practice, I observed that when I used++
and--
, my code tended to be too tight, too tricky, too cryptic. So, as a matter of discipline, I don’t use them any more.
Edit: Included comment from Nope as this answer continues to get views.
How to make buttons that increment and decrement a value when clicked?
The document.write
is the problem. It only works before the browser is done loading the page completely. After that, document.write
doesn't work. It just deletes all of the existing page contents.
Your first document.write
is executed before you the page has loaded completely. This is why you should see the 0
next to the two buttons.
Then however, the page has loaded. Clicking on a button causes the event handler to be executed, so document.write
will be called, which doesn't work at that point, because the page already has loaded completely.
document.write
shouldn't be used anymore. There are many modern ways of updating the DOM. In this case, it would create a <span>
element and update it's content using textContent
.
Moreover, use addEventListener
instead of inline event listeners:
var x = 0;var span = document.querySelector('span'); // find the <span> element in the DOMvar increment = document.getElementById('increment'); // find the element with the ID 'increment'var decrement = document.getElementById('decrement'); // find the element with the ID 'decrement'
increment.addEventListener('click', function () { // this function is executed whenever the user clicks the increment button span.textContent = x++;});
decrement.addEventListener('click', function () { // this function is executed whenever the user clicks the decrement button span.textContent = x--;});
<button id="increment">increment</button><button id="decrement">decrement</button><span>0</span>
Are increment/decrement operators considered bad form in Javascript?
If I understand correctly, the reason it's in JSLint is because there's a significant difference between ++i
and i++
, and many developers don't necessarily appreciate the implications of being specific about when the addition is done, in relation to other operations around it.
for example:
var i = 0;
if(i++) {
//does this get run or not?
}
if(--i) {
//and what about this one?
}
This is why Crockford considers it bad practice, and prefers the more explicit +=1
.
However, in general, I don't have this kind of issue with ++
; I'm perfectly happy to use it, and I would ignore JSLint telling me not to (most of the time!).
This is the important thing about JSLint -- it doesn't tell you about actual errors; everything it tells you is a suggestion. Some of them are excellent suggestions (eg you should never ever use with
); some are good suggestions that indicate poor code; and some of them are only a problem some of the time and should be considered individually. As a developer it is more important that you need to know why it's making its suggesting than it is to actually fix them. Once you understand the reasons for them being pointed out, you are in a position to decide for yourself whether a given instance of it in your code is a problem or not and how to fix it.
Hope that helps.
Toggle Increment and decrement count on single element click
You need to delegate the click event. At the beginning $(".notliked") returns 0 elements and so it's never executed.
In order to increment/decrement the text value you can use:
.text( function ) like:
$count.text(function(idx, txt) {
// convert text to number and increment by one
return +txt + 1;
});
The snippet:
$(document).on('click', ".notliked", function() { var $this = $(this); $this.removeClass('notliked'); $this.addClass('liked') $count = $('.likes-count'); $count.text(function(idx, txt) { return +txt + 1; });
});
$(document).on('click', ".liked", function() { var $this = $(this); $this.removeClass('liked'); $this.addClass('notliked'); $count = $('.likes-count'); $count.text(function(idx, txt) { return (+txt == 0) ? 0 : (+txt - 1); });
});
.heart {color: #fff;height:50px;cursor:pointer;width:50px;background-color: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="likes-count"> 0 </span>
<div class="liked heart">Click</div>
Related Topics
How to Run Gulp Tasks Sequentially One After the Other
Regex for JavaScript to Allow Only Alphanumeric
JavaScript Scroll Event for Iphone/Ipad
Using JavaScript's Atob to Decode Base64 Doesn't Properly Decode Utf-8 Strings
Handling Errors in Promise.All
Declaring Multiple Variables in JavaScript
How to Check If a String Contains Text from an Array of Substrings in JavaScript
How to Compare Software Version Number Using JS? (Only Number)
Emberjs: How to Load Multiple Models on the Same Route
Display Date/Time in User's Locale Format and Time Offset
How to Order Events Bound with Jquery
Difference Between 'Return Await Promise' and 'Return Promise'
How to Replace While Loops with a Functional Programming Alternative Without Tail Call Optimization
Hot and Cold Observables: Are There 'Hot' and 'Cold' Operators