Logo
30 Apr 2014 | 1 min. (111 words)

Default negative variables to zero in javascript

If you need to default a value to 0 if its negative, you could do:

var i = -45;
if (i<0){
    i = 0;
}
console.log(i); //0

However, a shorter way of doing this would be to use Math.max() passing 0 as one of the parameters:

var i = -45;
i = Math.max(0,i);
console.log(i); //0

Likewise Math.min() can be used to set a maximum value:

var i = 999;
i = Math.min(500,i);
console.log(i); //500

Or combine the two to set an available range. For example a percentage variable could be sanitised to ensure its between 0 and 100:

function sanitisePercentage(i){
    return Math.min(100,Math.max(0,i));   
}

console.log(sanitisePercentage(50));    //50
console.log(sanitisePercentage(99999)); //100
console.log(sanitisePercentage(-123));  //0

View Demo

javascript negative-number
Twitter Facebook Google+

Namespacing jQuery event handlers

How to better manage jQuery event handlers…

Understanding jQuery data() storage

It is a common misunderstanding that .data('key') is simply a shortcut for .attr('data-key')…

Related Links

  • LinkedIn
  • Twitter
  • Stack Overflow
  • GitHub

Stack Exchange

profile for Curt on Stack Exchange, a network of free, community-driven Q&A sites
Follow @curtistimson

Recent Posts

  • Adding a body class in GatsbyJs to prevent flashing content
  • ReactJs Snapshot unit testing and mocking components
  • Access user details and email address from Auth0 with NodeJs
  • Hosting Hugo on Netlify
  • Dopetrope Hugo Theme
Theme Bleak by zutrinken Published with Hugo
Menu