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

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: @curtcode
  • Stack Overflow
  • GitHub: @curtiscde

Stack Exchange

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

Recent Posts

  • Displaying latest posts on your GitHub profile
  • Using Codecov within a monorepo
  • Displaying Strava stats using webhooks & GitHub Actions
  • Filtering duplicate data points on Chart.js
  • Next.js Typerite Template Boilerplate
Theme Bleak by zutrinken Published with Hugo
Menu