---
title: "Top 5 JavaScript oneliners"
description: "JavaScript is such a beautiful language, where everything can be minified to one line! Practical notes and code examples on."
url: "https://h3manth.com/scribe/top-5-javascript-oneliners/"
canonical_url: "https://h3manth.com/scribe/top-5-javascript-oneliners/"
markdown_url: "https://h3manth.com/scribe/blog/top-5-javascript-oneliners.md"
publishDate: "2012-07-01T00:00:00.000Z"
author: "Hemanth HM"
category: "javascript"
tags: ["javascript"]
word_count: 309
reading_time_minutes: 2
x_markdown_tokens: 613
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# Top 5 JavaScript oneliners

> JavaScript is such a beautiful language, where everything can be minified to one line! Practical notes and code examples on.

JavaScript is such a beautiful language, where everything can be minified to one line ;)

But in this post I have tried to collect five (most useful for me so far) JavaScript functions.

**Shuffle array:**

```javascript
function shuf(a) {
  for (var j = a.length - 1; j > 0; j--) {
    var k = Math.floor(Math.random() * (j + 1));
    if (k != j) {
      var l = a[k];
      a[k] = a[j];
      a[j] = l;
    }
  }
  return a;
}

// Sample:
shuf([1, 2, 3, 4])
// [2, 4, 3, 1]
```

**Update 0:** Thanks to Weltschmerz for making shuffle more better!

```javascript
function shuffle(ar) { 
  return ar.slice().sort(function() { 
    return Math.random() > 0.5 ? 1 : -1; 
  }); 
}
```

**Check if mail id is valid:**

```javascript
function is_email(id) {
  return (/^([\w!.%+\-\*])+@([\w\-])+(?:\.[\w\-]+)+$/).test(id);
}

// Sample:
is_email('user@gmail.com')  // true
is_email('A@b@c@example.com')  // false
```

PS: trying to fix it to allow `user@[IPv6:2001:db8:1ff::a0b:dbd0]` as this is a valid mail id now!

**Check if object is empty:**

```javascript
function is_empty(obj) {
  if (obj instanceof Array) {
    return obj.length === 0;
  } else if (obj instanceof Object) {
    for (var i in obj) return false;
    return true;
  } else {
    return !obj;
  }
}

// Sample:
is_empty([])   // true
is_empty({})   // true
is_empty([1])  // false
```

**Check if it's a scalar object!**

```javascript
function is_scalar(obj) {
  return (/string|number|boolean/).test(typeof obj);
}

// Sample:
is_scalar(1)   // true
is_scalar({})  // false
```

**Check the sign of the number:**

```javascript
Math.sign = function(num) { 
  return (num > 0) - (num < 0); 
}
```

Do share your fav one liners or functions in JavaScript! Happy Hacking!

**UPDATE 1:** As many argued these are not (simple) one liners, here are few more:

```javascript
Array.prototype.each = Array.prototype.forEach;
Array.prototype.clone = function() { return this.slice(0); };
Array.prototype.min = function() { return Math.min.apply(Math, this); };
Array.prototype.max = function() { return Math.max.apply(Math, this); };
```
