title: Tips for golfing in JavaScript

text:
# Question
Title: Tips for golfing in JavaScript
What general tips do you have for golfing in JavaScript? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to JavaScript (e.g. "remove comments" is not an answer).

> **Note:** Also see Tips for Golfing in ECMAScript 6 and above

# Answer
### Fancy For Loops

you can use the standard for loop in non-standard ways

```
for ( a; b; c )

```

is essentially equivalent to:

```
a;
while ( b )
{
  ...
  c;
}

```

so a good trick is to write your code with a `while` loop, and then split it into the `a,b,c` parts in a `for` loop.

A couple examples I've written:

```
for(x=y=n;!z;x--,y++)z=i(x)?x:i(y)?y:0
for(a=b=1;b<n;c=a+b,a=b,b=c);

```

### Chain your setters

If you're initializing or resetting multiple values, chain the value to all the variables that need it:

```
a=b=1;

```

### Implicit Casting

Don't check your types, just use them as they are. `parseInt()` costs `10` characters. If you need to cast out of a string, be creative:

```
a='30';
b='10';
c = a + b; //failure
c = parseInt(a) + parseInt(b) //too long

c = -(-a-b); //try these
c = ~~a+~~b;
c = +a+ +b;
c = a- -b;

```

### Avoid Semicolons

JavaScript has automatic semi-colon insertion. Use it often and well.

### One-liners

Save on brackets by shoving as much as possible into single lines, or parameters:

```
a( realParam1, realParam2, fizz='buzz' )

```

### Increment/Decrement operators

```
a = a - 1;
foo(a);

```

and

```
foo(a);
a = a - 1;

```

can easily be rewritten as

```
foo(--a);

```

and

```
foo(a--);

```

respectively.

### Use `this` or `self` instead of `window` in global context

self explanatory 2 character savings.

### Use bracket notation for repeat property access

This is definitely a balancing act between property name length and number of accesses. Instead of calling `a.longFunctionName()` with dot notation twice, it's shorter to save the name and call the function via bracket notation:

```
a.longFunctionName(b)
a.longFunctionName(c)
//42

```

-vs-

```
a[f='longFunctionName'](b)
a[f](c)
//34

```

this is especially effective with functions like `document.getElementById` which can be reduced to `d[e]`.

Note:

With bracket notation, the cost is `6 + name.length` characters the first time. Each subsequent access has a cost of `3` characters.

For dot notation, all accesses cost `name.length + 1` (+1 for the `.`) characters.

Use this method if `6 + name.length + (3 * (accesses - 1)) < accesses * (name.length + 1)`.

len = length of property name
i = minimum accesses to take advantage

```
len | i
========
1   | ∞
2   | ∞
3   | 7
4   | 4
5   | 3
6   | 3
7   | 3
8+  | 2

```

The number of accesses can also span multiple objects. If you access `.length` 4 or more times on different arrays, you can use the same variable holding the string `'length'`.
> 130 votes

# Answer
Splitting with numbers to save the quotemarks:

```
"alpha,bravo,charlie".split(",") // before
"alpha0bravo0charlie".split(0)   // after

```
> 152 votes

# Answer
Use the comma operator to avoid braces (also applies to C):

```
if(i<10)m+=5,n-=3;

```

Instead of

```
if(i<10){m+=5;n-=3}

```

which is one character longer.
> 66 votes

# Answer
# Shorter random number generation

If you need a random boolean (`0` or `1`):

```
new Date&1 // equivalent to Math.random()<0.5

```

If you need a random integer `0 <= n < 1337`:

```
new Date%1337 // equivalent to Math.floor(Math.random()*1337))

```

This works because a `Date` is stored internally in JavaScript as the amount of milliseconds since an epoch, so the `new Date` is being coerced into `123somebignumber456` when you try to do integer math on it.

Of course, these "random" numbers really won't be as random, especially if you call them multiple times in quick succession, so keep that in mind.
> 57 votes

# Answer
You can use the object literal form of get/set to avoid using the keyword `function`.

```
var obj = {
  get f(){
    console.log("just accessing this variable runs this code");
    return "this is actually a function";
  },
  set f(v){
    console.log("you can do whatever you want in here, passed: " + v);
  }
};

1 && obj.f; // runs obj.[[get f]]
obj.f = Infinity; // runs obj.[[set f]](Infinity)

```
> 40 votes

# Answer
This one is lesser known and lesser used, but can be impressive if used in the right situation. Consider a function that takes no arguments and always returns a different number when called, and the returned number will be used in a calculation:

```
var a = [
    Math.random()*12|0,
    Math.random()*11|0,
    Math.random()*10|0,
    /* etc... */
];

```

You might normally shorten this function using a single-letter variable name:

```
var r=Math.random,a=[r()*12|0,r()*11|0,r()*10|0,r()*9|0,r()*8|0,r()*7|0,r()*6|0,r()*5|0];

```

A better way to reduce the length is by abusing `valueOf`, which gives you a saving of 2 characters per invocation. Useful if you call the function more than 5 times:

```
var r={valueOf:Math.random},a=[r*12|0,r*11|0,r*10|0,r*9|0r*8|0,r*7|0,r*6|0,r*5|0];

```
> 39 votes

# Answer
### Taking advantage of short-circuit operators

Rather than long `if` statements or using ternary operators, you can make use of `&&` and `||` to shorten your code. For instance:

```
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);

return match ? decodeURIComponent(match[1].replace(/\+/g, ' ')) : null;

```

can become

```
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);

return match && decodeURIComponent(match[1].replace(/\+/g, ' '));

```

The `||` operator is often used in this way for setting defaults:

```
evt = evt || window.event;

```

This is the same as writing

```
if (!evt)
    evt = window.event;

```

### Creating repetitive strings using *Array*

If you want to initialize a long string of a particular character, you can do so by creating an array with a length of *n+1*, where *n* is the number of times you wish to repeat the character:

```
// Create a string with 30 spaces
str = "                              ";

// or
str = Array(31).join(" ");

```

The larger the string, the bigger the saving.

### Parsing numbers

Use `+` and `~` operators instead of `parseFloat()` or `parseInt()` when coalescing a string type that is *just a number* to a number type:

```
var num = "12.6";
parseFloat(num) === +num;  // *+* is **10** characters shorter than *parseFloat()*

var num2 = "12"
parseInt(num2) === +num2;   // *+* is **8** characters shorter than *parseInt()*

var num3 = "12.6"
parseInt(num3) === ~~num3;  // *~~* is **7** characters shorter than *parseInt()*

var num4 = "12.6"
parseInt(num4) === num4|0;  // *|0* is **7** characters shorter than *parseInt()*

```

Be wary though, other types can be coalesced with these operators (for instance, `true` would become `1`) an empty string or a string containing just white space would become `0`. This could be useful in certain circumstances, however.
> 35 votes

# Answer
**Unicode shortcuts**

If you use a hell of a built-in property at a big golfing challenge you can alias every property to a one character equivalent:

```
[Math,Number,S=String,Array].map(b=>
    Object.getOwnPropertyNames(b).map((p,i)=>
        b.prototype[S.fromCharCode(i+248)]=b[p]
    )
)

```

After executing the code above you can use it like this:
`"foo".Č(/.*/,'bar') // replaces foo with bar`

**This costs 118 bytes, so it might not be useful in certain situations**

It may be browser dependent and i'm not sure if it's shorter than `with(Array){join(foo),...}` or defining variables as used properties `with(Array){j=join,m=map...}` but still it is worth mentioning.

```
    Math        Number              String              Array

ø   toSource    prototype           prototype           prototype
ù   abs         NaN                 quote               join
ú   acos        POSITIVE_INFINITY   substring           reverse
û   asin        NEGATIVE_INFINITY   toLowerCase         sort
ü   atan        MAX_VALUE           toUpperCase         push
ý   atan2       MIN_VALUE           charAt              pop
þ   ceil        MAX_SAFE_INTEGER    charCodeAt          shift
ÿ   clz32       MIN_SAFE_INTEGER    contains            unshift
Ā   cos         EPSILON             indexOf             splice
ā   exp         isFinite            lastIndexOf         concat
Ă   floor       isInteger           startsWith          slice
ă   imul        isNaN               endsWith            filter
Ą   fround      toInteger           trim                isArray
ą   log         parseFloat          trimLeft            lastIndexOf
Ć   max         parseInt            trimRight           indexOf
ć   min         length              toLocaleLowerCase   forEach
Ĉ   pow         name                toLocaleUpperCase   map
ĉ   random      arguments           normalize           every
Ċ   round       caller              match               some
ċ   sin                             search              reduce
Č   sqrt                            replace             reduceRight
č   tan                             split
Ď   log10                           substr
ď   log2                            concat
Đ   log1p                           slice
đ   expm1                           fromCharCode
Ē   cosh                            fromCodePoint
ē   sinh                            localeCompare
Ĕ   tanh                            length
ĕ   acosh                           name
Ė   asinh                           arguments
ė   atanh                           caller
Ę   hypot
ę   trunc
Ě   sign
ě   cbrt
Ĝ   E
ĝ   LOG2E
Ğ   LOG10E
ğ   LN2
Ġ   LN10
ġ   PI
Ģ   SQRT2
ģ   SQRT1_2

```
> 33 votes

# Answer
Combine nested for loops:

```
// before:
for(i=5;i--;)for(j=5;j--;)dosomething(i,j)

// after:
for(i=25;i--;)dosomething(0|i/5,i%5)

```

Example with different values for `i`/`j`:

```
// before:
for(i=4;i--;)for(j=7;j--;)dosomething(i,j)

// after:
for(i=28;i--;)dosomething(0|i/7,i%7)

```
> 31 votes

# Answer
Sneak variable initialization into the prompt() call for getting user input

```
n=prompt(i=5);     // sets i=5 at the same time as getting user input

```

instead of using

```
n=prompt();i=5;

```

As a side-effect, it displays the input value in the prompt window while saving 1 character.
> 30 votes

# Answer
### Use `^` instead of `!=` or `==` when comparing to an integer

```
//x!=3?a:b
  x^3?a:b

//x==3?a:b
  x^3?b:a

```

### Replace calls to built-in Math functions with shorter expressions

```
//Math.ceil(n)
  n%1?-~n:n

//Math.floor(n)
  ~~n
  0|n

//Math.abs(n)
  n<0?-n:n

//Math.round(n)
  n+.5|0

//Math.min(x,y)
  x<y?x:y

//Math.max(x,y)
  y<x?x:y

```
> 28 votes

# Answer
# Array sum / product / quotient

**ES5**: 17 bytes

```
eval(a.join('+'))

```

**ES6**: 15 bytes

```
eval(a.join`+`)

```

Of course you can swap the `+` for anything you want, e.g., `*` for product or `/` for quotient.
> 25 votes

# Answer
# Abuse literals

The recent sample: Check whether `"c"` is uppercase or lowercase, doesn't matter if not letter

```
"c"<{} // returns false, lower case
"C"<{} // returns true, upper case

```
> 25 votes

# Answer
## Exception abusing

in case string/character literals are prohibited, you can use a try catch block:

```
try{something0}catch(e){str=e.message.split(0)[0]}

```

now `str` equals `"something"`

if more strings are needed you can chain it with a number (e.g. zeros)

```
try{something0foo0bar0}catch(e){arr=e.message.split(0)}

```

now `arr` equals `["something", "foo", "bar", " is not defined"]`
> 24 votes

# Answer
If you need to check for NaN, don't use `isNaN(x)`, but use `x!=x`, which is shorter and also works.

```
if(isNaN(x)){
if(x!=x){

```

Note that this only works if `typeof(x) === "number"`; if it's a string for example, `isNaN("string")` returns `true`, but `"string" != "string"` returns `false`. Thanks to Cyoce for pointing this out!
> 22 votes

# Answer
Converting a `while` loop into a `for` loop is often equivalent:

```
while(i--);
for(;i--;);

```

But the second form can have variable initialization combined:

```
i=10;while(i--);
for(i=10;i--;);

```

Notice the second form is one character shorter than the first form.
> 21 votes

# Answer
If you're initializing a variable to `1` in every iteration of a loop (for example, resetting a variable in an outer loop for an inner loop), like the following (from my answer to this question):

```
for(j=n-2;p=1,j++<=n;r|=p)for(i=1;++i<j;)p=j%i?p:0;
          ^^^^

```

Since the result of a condition like `j++<=n` is `1` whenever its true, you can just assign the condition directly to the variable (because when it becomes false, the loop will stop executing and will no longer matter):

```
for(j=n-2;p=j++<=n;r|=p)for(i=1;++i<j;)p=j%i?p:0;
          ^^^^^^^^

```

You can usually **save 2 characters** using this method. Regards to `@ugoren` for the idea in the comments to that answer.

---

For another example, I also applied this trick to my answer here with the expression `w=r=++c<S.length` in my outer for loop, saving a total of 4 characters.
> 17 votes

# Answer
If you can accept Spidermonkey (for now) specific scripts, you can use ECMAScript 6 arrow functions. Insteading of writing code like the following.

```
a.map(function(x){return x*2}) // function? return?

```

You can shorten it like this.

```
a.map(x=>x*2)

```
> 17 votes

# Answer
# Rounding

I know that alternatives to `Math.floor()` have been posted, but what about the others?

## Flooring:

```
Math.floor(x) //before
0|x           //after

```

## Rounding:

```
Math.round(x) //before
0|x+.5        //after

```

## Ceiling:

```
Math.ceil(x) //before
x%1?-~x:x    //after - credits to @Tomas Langkaas

```
> 15 votes

# Answer
Use a bitwise operation to round a number toward zero:

```
// do this
T=Math.random()*6+1|0

// or do this
T=~~(Math.random()*6+1)

```

(Source: Random dice tipping)

Operator precedence determines which will be shorter in your program.
> 14 votes

# Answer
**Looping Tip I**

You can save `1` character when looping by changing the `i` on the last time used:

```
//not so god
for(i=0;i<3;i++){
  alert(i);
}

//best
for(i=0;i<3;){
  alert(i++);
}

```

**Note:** works with `--` too (but modify the loop accordingly to avoid infinite looping)

---

**Looping Tip II**

There are certain scenarios where you can save one character by playing with the incrementing operator and values:

```
for(i=0;i++<9;)
for(i=0;++i<10;)

```

**Note:** you need to pay attention when for example `0 to -1`. and `9 to 10, 99 to 100`, so play around until you find a way to save the character
> 14 votes

# Answer
Very simple one, even so, no one had mentioned it.

If you're using `Math.min()` or `Math.max()` you can save 6 chars by doing this:

```
Math.min(a,b)  // 13 chars
a<b?a:b        //  7 chars

Math.max(a,b)
a>b?a:b

```
> 13 votes

# Answer
### Free commas!

Often you'll want to include a comma in a string, perhaps like so:

```
f=(x,y,z)=>x+","+y+z

```

By abusing the string representation of arrays, this can be shortened by two bytes:

```
f=(x,y,z)=>[x,y]+z

```

This particular instance only works if you have three variables you want to concatenate as shown. You can use the same trick with two, but you need to be careful. There are three variants you might try:

```
f=(x,y)=>[x,y]
f=(x,y)=>[x,]+y
f=(x,y)=>x+[,y]

```

The first one will return an actual array rather than a string, which defeats the purpose. The second one *looks* like it will work, but in fact most modern browsers will remove the trailing comma when parsing the array. The third one will work though, at the same byte count as the second.

---

To put this to good use, say you have a function which creates the range `[0...n]`:

```
f=x=>x?[...f(x-1),x]:[0]

```

If returning a string with a separator is allowed, you might do something like this, saving a few bytes:

```
f=x=>x?f(x-1)+" "+x:0

```

However, you can save another byte with an array literal:

```
f=x=>x?f(x-1)+[,x]:0

```

Note that depending on how you arrange the recursion, you may end up with a leading or trailing separator, so you'll need to make sure your output format is allowed by the challenge.

Example usage
> 13 votes

# Answer
# Prefer `.map` over `.reduce`

Consider the following code for summing an array:

```
a.reduce(function(x,y){return x+y})

```

Pretty long, right? What if I told you that you could get rid of the `return`? Well, you can:

```
a.map(function(x){t+=x},t=0)    // 7 bytes saved

```

(Although an even shorter way is `eval(a.join("+"))`.)

How about reducing by multiplication, where you have to specify the starting number anyway?

```
a.reduce(function(x,y){return x*y},1)  // Looooong
a.map(function(x){t*=x},t=1)    // An easy 9 bytes shorter

```

(Again, `eval(a.join("*"))` works as well.)

Here, let's try one that doesn't work with `eval(a.join())`:

```
a.reduce(function(x,y){return x+f(y)})
a.map(function(x){t+=f(x)},t=0)

```

Note that this doesn't work *quite* as well with ES6, although it's still a little shorter:

```
a.reduce((x,y)=>x+f(y))
a.map(x=>t+=f(x),t=0)

```

**Note:** in all of the `.map` versions, you will need to call `t` afterwards to get the actual value.
> 12 votes

# Answer
## Converting an array of strings into numbers

Take the array `["32", "0x30", "0o10", "7.642", "1e3"]`. The simple way to convert this to numbers would be `.map(n=>+n)` or `.map(Number)`.

However, assuming you know everything is a valid number, you can simply use `.map(eval)`, saving at least a byte.
> 11 votes

# Answer
In cases where you are using the ternary operator to chose between two *numbers*, and the conditional is either a *boolean* or *number* `1 or 0`, you can do math operations instead:

```
(x ? num1 : num2) conclusions:

    1)if num1 equals num2, there ARE savings
    2)if num1 is (+1) or (-1) than num2, there ARE savings
    3)if either num1 or num2 equals to 0, there ARE savings
    4)it is MORE LIKELY to find greater savings on num1>num2 instead of num1<num2
    5)in method (*A) and (*B), savings are NOT GUARANTEED

    a)num1>num2
        i)(num1==(num2+1))
            ex1: (x?5:4) to (x+4)
            ex2: (x?8:7) to (x+7)
        ii)num2==0
            ex1: (x?3:0) to (x*3)
            ex2: (x?7:0) to (x*7)
        iii)
            (*A) or (*B) //one might be shorter

    b)num1<num2
        i)((num1+1)==num2)
            ex1: (x?4:5) to (5-x)
            ex2: (x?7:8) to (8-x)
        ii)num1==0
            ex1: (x?0:3) to (!x*3)
            ex2: (x?0:7) to (!x*7)
        iii)
            (*A) or (*B) //one might be shorter

    c)num1==num2
        i)
            ex1: (x?5:5) to (5)
            ex2: (x?-3:-3) to (-3)

    (*A) use ((x*(num1-num2))+num2)
        ex1: (x?8:4)   to ((x*4)+4)
        ex2: (x?4:8)   to ((x*-4)+8)

        ex3: (x?6:-4)  to ((x*10)-4)
        ex4: (x?-4:6)  to ((x*-10)+6)

        ex5: (x?4:-6)  to ((x*10)-6)
        ex6: (x?-6:4)  to ((x*-10)+4)

        ex7: (x?-5:-9) to ((x*4)-9)
        ex8: (x?-9:-5) to ((x*-4)-5)

    (*B) use ((!x*(num2-num1))+num1)
        ex1: (x?8:4)   to ((!x*-4)+8)
        ex2: (x?4:8)   to ((!x*4)+4)

        ex3: (x?6:-4)  to ((!x*-10)+6)
        ex4: (x?-4:6)  to ((!x*10)-4))

        ex5: (x?4:-6)  to ((!x*-10)+4)
        ex6: (x?-6:4)  to ((!x*10)-6)

        ex7: (x?-5:-9) to ((!x*-4)-5)
        ex8: (x?-9:-5) to ((!x*4)-9)

```

**Note:** In addition to this, you will need to remove the unnecessary `0-`, `+0`, `+-` etc.

**Note2:** there is an isolated case where `(x) !== (x?1:0)`, as `x` must be `typeof === "number"` for it to work. However, in the case of `(-x)` it works just fine.

**Note3:** In case you don't find savings, simply use the former `(x?y:z)`

Previously I thought method B couldn't ever beat A, however exceptions do exist:

```
(x?97:100) //original

(-3*x+100)
(3*!x+97)

```

I created a github project that makes the simplification for us (**jsFiddle demo**)
> 9 votes

# Answer
**Transforming to a Boolean**:

```
if(b){b=true}else{b=false}
b=b?true:false;
b=b?!0:!1;
b=!!b;

```

**Note:** This changes `0`, `""`,`false`, `null`, `undefined` and `NaN` to `false` (everything else to `true`)
> 9 votes

# Answer
**How to compare a number with help of how numbers turn into booleans:**

If you are going to check if something is equal to a *positive number*, you can subtract that amount and reverse what was inside the `if` and `else` blocks:

```
//simplified examples:
x==3?"y":"n"; <- 13 Chars
x-3?"n":"y"; <- 12 Chars

//expanded examples:
if(x==3){
    yes();
}else{
    no();
}

if(x-3){
    no();
}else{
    yes();
}

```

And in case you are wanting to compare with a *negative number* (\*different than `-1`), you just simply need to *add* this number instead of subtracting.

\*well, you can surely use `x.indexOf(y) + 1`, but in the special case of `-1` you have the opportunity to use `~x.indexOf(y)` instead.
> 9 votes

# Answer
Something worth noting is that you can use a string in place of zero in some instances to save a couple of bytes here and there in loops:

```
s='';for(i=0;i++<9;)s+=i
for(i=s='';i++<9;)s+=i
// s="123456789", i=10

```
> 9 votes

# Answer
**tl;dr:** Use ES6 features!

### Arrow functions

Doc: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/arrow\_functions
Example:

```
s = x => x*x
// s = function (x) {
//   return x * x;
// }

```
> 9 votes

# Answer
Instead of writing `true` you can use `!0`.
> 9 votes

# Answer
# Converting a number from hexadecimal

Instead of using the lengthy `parseInt` to convert a number from hexadecimal:

```
parseInt(a,16)

```

Add `"0x"` to the beginning, then convert to a number with a usual technique:

```
+("0x"+a)   // 5 bytes saved

```

Even better solution, abusing order of operations:

```
"0x"+a-0    // another byte saved

```

Note that this last one will not work in all situations, depending on the surrounding operators.

In ES6, you can also use this trick to convert from octal or binary:

```
"0b"+a-0   // binary
"0o"+a-0   // octal

```
> 9 votes

# Answer
# 2 to a power

If for some reason you need to calculate 2 to the `n`th power,

`1<<n` is shorter than `Math.pow(2,n)`.

If you needed to calculate 2 to the `n+1`th power,

`2<<n` is even shorter than `1<<n+1`

Likewise for `4<<n` for `n+2`, `8<<n` for `n+3`, `16<<n` for `n+4`, etc.

*(sorry if this is too obvious)*
> 9 votes

# Answer
Use Mozilla's nonstandard "expression closures" feature to save many characters in a script that only needs to work in the SpiderMonkey/Firefox or Rhino engines. For example,

```
function foo(){return bar}

```

becomes

```
function foo()bar

```

See the Stack Overflow page for more such tricks.
> 8 votes

# Answer
for a given array, we know a `for..in` loop might lead to errors because stuff might be added to the Array.Prototype, so we revert to a normal `for` loop:

**So instead of this iteration:**

```
for (var i=0; i<arr.length; i++ )

```

**lets do this:**

```
for (var i=arr.length; i--; )

```

if we just want to iterate the Array not caring it goes backwards
> 8 votes

# Answer
Use `if(~a.indexOf(b))` instead of `if(a.indexOf(b)!=-1)`
> 8 votes

# Answer
# Conditionally reverse an array with `.sort`

Let's say you have an array, `l`, and you want to reverse it if and only if `someBoolean`.

The naïve way to do it would be `if(someBoolean)l.reverse()`

Instead, you can abuse the way that JavaScript's `sort` function works.

```
if(someBoolean)l.reverse() // before
someBoolean&&l.reverse()   // golfier before
l.sort(_=>someBoolean)     // after
                      ^^^^

```
> 8 votes

# Answer
## Determining if an array is empty

The empty array is truthy in JavaScript, i.e. `[]?b:c` returns `b`. This leaves us to find our own ways to determine if an array is empty. The most obvious way is `.length`:

```
a.length?b:c

```

However, this can be shortened by 2 bytes with the `in` operator:

```
0 in a?b:c

```

Note: unlike in Python, `x in y` checks whether `y` has a *key* `x`; it's a shorthand for `y.hasOwnProperty(x)`.

This is, I believe, the shortest code that unconditionally detects whether `a` is empty. However, there are a few alternatives that work in various scenarios:

```
a[0]?b:c

```

This works iff the first item in `a` is guaranteed to be truthy. For example, `a=[1];a[0]` returns `1`, which is truthy; `a=[];a[0]` returns `undefined`, which is falsy; but `a=[0];a[0]` returns 0, which is also falsy. But in general, this trick works on arrays of chars or positive numbers.

```
a+""?b:c

```

When arrays are casted to strings, the brackets are left out. `[1,2,3]+""` returns the string `"1,2,3"`. So casting `a` to a string will return the empty string (falsy) for the empty array, and a truthy string otherwise.

Caveat: If `a` contains a single array which contains either nothing or a single array containing... etc., e.g. `[[]]`, `[[[[[[]]]]]]`, it will still be casted to the empty string.

```
a+a?b:c

```

This is practically exactly the same as the above example, but a byte shorter. When `+` is called on two arrays, JS stupidly converts them both to strings and concatenates *those*. So `a+a` returns exactly the same thing as `a+""`, but doubled.
> 8 votes

# Answer
Comparing numbers by absolute value:

```
a*a<b*b // 7 bytes

```

Vastly shorter than `Math.abs` (8 bytes without counting `()`), and like calling the function this will allow casting strings to numbers on the fly.

Sorting by arrays of multiple values, comparing them all one by one (e.g. finding minimum time durations in `01:23:45` notation):

```
a.map(v=>v.split`:`).sort(([h,m,s],[g,n,a])=>h-g||m-n||s-a)[0].join`:`

```

This example sorts `00:00:00` \< `01:00:00` \< `01:00:01` \< `22:59:59` \< `23:00:00` and finds the smallest element. This works because `||` short-circuits for any value that isn't `false`like and so the expression `h-g||m-n||s-a` will evaluate the next value in the chain only when the last difference was `0`.
> 8 votes

# Answer
Sometimes declaring a variable (or more) as function parameters can save some strokes by avoiding the `var` keyword. This use case is fairly rare though:

`function f(){var i}` =\> `function f(i){}`

Also you can use short circuit operators to avoid if statements:

`if(a)b` =\> `a&&b`

`if(!a)b` =\> `a||b`

To coerce to a number: `str-0`
> 7 votes

# Answer
**Repeated characters**

Be creative when trying to repeat the same character:

```
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
s="a";while(s.length<32)s+=s
for(s="a";s.length<32;s+=s)
for(s="aa",i=4;i--;s+=s)
s="aaaaaaaa",s+=s,s+=s
s="aaaaaaaa",s+=s+s+s
Array(33).join("a")

```

With ES6, this becomes even shorter:

```
'a'.repeat(32)

```

**Note:** It is unlikely that you use it to form a string, but the idea can be applied to form large numbers too
> 7 votes

# Answer
# Use shorthands instead of primitives

Most of these are done by any sane minifier, but not all.

* **2 bytes saved**

```
true
!0

```
* **3 bytes saved**

```
false
!1

```
* **5 bytes saved**

```
Infinity
1/0

```
* **5 bytes saved**

```
undefined
0[0]   (any digit works)

```
> 7 votes

# Answer
Initialize arrays with `[]` instead of `Array()`, and add to arrays with `[.length]`:

```
a=[];       // initialize a new array
a[0]=15;    // insert element to end of array
a[1]=30;    // insert another element to end of array

```
> 6 votes

# Answer
Some extra tricks that I don't see very often, that are more JS-specific:

* Use array literals and indexing as a sort of `switch` as an expression. You can leave out "unnecessary" elements and they'll default to `undefined` (which is a falsy value, by the way). E.g. `[,1,,-1][i%4]` would evaluate to either 1 or -1 depending on whether i is 1,5,9,13,... or 3,7,11,15,... (and we don't care about the other cases).
* Similarly, use object literals when you want arbitrary strings for the keys.
* This one is common to all C-style languages: (ab)use the fact that that `&` and `|` works just as well as `&&` and `||` with boolean values, albeit with different precedence. Keep in mind that the single-character variants aren't short-circuiting though!
* `-~x` is the same as `x+1`, and `~-x` is the same as `x-1`. Sometimes the {bitwise,arithmetic} negation variants are useful to avoid extra parens; for instance, `4*~-n` rather than `4*(n-1)`.
* `~9` could be used as a two-character literal for the value `-10` (I've never had a use for this, but it's a fun curiosity).
> 6 votes

# Answer
There's a few other ideas that come to mind:

**Ternary operators with functions**

Ternary operators also work well as a substitute for if..then..else statements with functions...

```
if(a==b){
   c();
}else{
   if(a==d){
       e();f();
   }
   g();
}

```

can be replaced with

`(a==b)?c():(((a==d)&&(e()|f()))|g())`

You can take this further by abusing functions that don't take parameters:

`a==b?c():g(a==d&&f(e()))`

If `a`, `b`, and `d` are numbers, you can use subtraction to test for 0.

`a-b?g(a-d||f(e())):c()`

**Decimal Base Exponents**

Another is the reduction of decimal base exponents... for example `1000000` can be replaced with `1e6`
> 6 votes

# Answer
**You can use `-~s` instead of `+s+1`, and `~-s` instead of `+s-1`,** if `s` is a string or a number between `-(2^31)-1` and `2^31`.
> 6 votes

# Answer
Use valueOf to make shorter function calls. Instead of:

```
function f(){...}
f()

```

use

```
f={valueOf:function(){...}}
+f

```

If you call the function `f` frequently enough, you will save characters because `+f` is 1 shorter than `f()`.

If you use`f` even more than that, you can use `__defineGetter__`:

```
__defineGetter__('f',function(){...})
f

```

This trick also works for a function that takes 1 argument.

```
function f(v){...}
f(x)

```

Becomes

```
__defineSetter__('f',function(v){...})
f=x

```

But now it will always return `v`.

---

Edit: I forgot to mention this, but it only works for a function that doesn't take arguments.
> 6 votes

# Answer
# `document.getElementById`

This one's a HUGE byte-saver.

```
document.getElementById('a').innerHTML="foo"; //before
a.innerHTML="foo"; //after

```
> 6 votes

# Answer
Use `with` to import methods and properties from objects into the local scope.

It becomes more apparent with longer class names or repeated use of the same one:

```
a=Math.max(1,2),b=Math.min(2,7),c=Math.sqrt(100)
with(Math)a=max(1,2),b=min(2,7),c=sqrt(100)

```
> 6 votes

# Answer
Another thing I came across is forcing a multidimensional array into a single-dimensional array like this:

```
[[1,2],[3,4]].join().split(",") // ["1", "2", "3", "4"]

```

It does convert everything into strings, so basically only numbers/strings are possible, but it can come in handy. Calculating with strings automatically converts it into numbers anyway.

**EDIT:** As Austin Hyde pointed out, you can flatten one level like this:

```
[].concat.apply([],[[1,2],[3,4]])

```

Although it only takes it down one level, the data types remain.
> 5 votes

# Answer
Treat strings like you do C Strings.

Given `s="hello"`

```
s[0]

```

is equivalent to

```
s.charAt(0)

```

and

```
s.split("")[0]

```
> 5 votes

# Answer
# Abuse uninitialized variables, mostly for `null` and `undefined`

* `undefined` varies, some better than others

+ One-time use (**5 bytes saved**):

    ```
    undefined
    1..a       (any digit+letter works)

    ```
    + Multiple uses (**8 per use - 5 bytes saved**, **10 bytes for 2 uses**)

    ```
    undefined;undefined
    var u;u;u

    ```
    + Existing declaration (**8 per use - 5 bytes saved**, **5 bytes for 1 use**, **13 bytes for 2 uses**)

    ```
    var x;undefined
    var x,u;u

    var x;undefined;undefined
    var x,u;u;u

    ```
* `null` varies, generally better replaced in larger golfs

+ If there is a declaration *anywhere*, replace it unless `null` is specifically required (**3 per use - 2 bytes saved**).

    ```
    var x;null
    var x,n;n

    ```
    + Single uses:

    - If no variable declaration exists, do not change.
        - If any `undefined` exists (in any form), declare an unused variable (**5 bytes saved if one of each**).

        ```
        v==null;undefined
        var u;v==u;u

        ```
        - If more than two such tests exist, declare an unused variable (two are equal).

        ```
        a==null;b==null;c==null
        var u;a==u;b==u;c==u

        ```
        - Otherwise, keep as `null`
    + Multiple uses:

    - Declare an unused variable, unless `null` is specifically required (2 is equivalent).

        ```
        null;null;null
        var u;u;u;u

        ```
* Prefer to avoid these tests when possible. Aim for implicit boolean tests (`if(0);`)
> 5 votes

# Answer
When it comes to comparing strings against eachother, you’d normally use

```
x=='*'

```

If it is the case that `x` only has a few *fixed options*, e.g. `x` can *only* be one of the lowercase letters *or* the asterisk (`*`), then you can use JavaScript’s string comparison like this:

```
x<'a'

```

In the case of *limited options*, this will be `true` if and only if `x=='*'` and `false` otherwise, saving *one amazing byte*! This is based on the Unicode table.

For an actual example, see this revision of an answer of mine.
> 5 votes

# Answer
# `setInterval` Hacks

Pass a string instead of a function to setInterval.

```
setInterval(function(){console.log(0)},1) //before
setInterval('console.log(0)',1) //after

```

You can also omit the last argument if you don't care about the speed at which your interval will execute. NOTE: This does not work in Firefox...

```
setInterval('console.log(0)',1) //before
setInterval('console.log(0)') //after
setInterval`console.log(0)` //after - ES6 only

```
> 5 votes

# Answer
# Stack Ternary Operators

Need to test many conditions, try this:

```
a ? b : c ? d : e ? f : g

```

# Use the comma operator

Using an arrow function, and need to return something else than what your doing? Feel no need to break out the `{b;return a}` and instead use the comma operator:

```
   f=>{f.map(b=>...);return a}
   f=>(f.map(b=>...),a)

```

# Take advantage of =

Assignment without `var` can be vital to shave off bytes. Since it returns the value, you can:

Assign variables in function calls:

```
Array(100).fill(100);p=100
Array(p=100).fill(p)

```

Stack variable assignment:

```
a=1,b=1,c=1
a=b=c=1

```

Assign variables in control structures:

```
if(b=1) {...}

```

Since `1` is truthy (If tested against a boolean it will convert to `true`), the block will run
> 5 votes

# Answer
# Use atob() and btoa() to compress/decompress strings

```
alert('adifonoiewnfqowinfiodnasfoinqeiwnfqoiwnfoiansdfoinqowfe') //before
alert(btoa('iØ¢z"{ ßª"ø¨vv¬~§©è°ú¨    ß¢&§±×èz¨Á÷')) //after

```

Great for some challenges. Only works on strings with `a-zA-Z0-9` and no other chars.
> 5 votes

# Answer
# Prefer `Array#map()` to `Array#forEach()`

Self-explanatory, a flat **4 bytes saved**

```
a.forEach(function(e){/* ... */})
a.map(function(e){/* ... */})

```
> 4 votes

# Answer
Instead of checking if something is a string like this:

```
var a = "aString";
if (typeof a === 'string') {
    runSomething();
}

```

You can do this:

```
var a = "aString";
a===''+a&&runSomething();

```
> 4 votes

# Answer
If you are ever in a situation where you have an array `a` and you need to get its last element as an array of itself, use `Array#slice()`:

```
[a[a.length-1]]    // 15
a.slice(-1)        // 11

```
> 4 votes

# Answer
If you need to do something different depending on several different values for a string, instead of:

```
if(v=='hello'){
  j=1
}else if(v=='goodbye'){
  j=2
//...

```

consider:

```
j={hello:1,goodbye:2,...}[v]

```
> 4 votes

# Answer
# Removing something from a string

When you want to remove a certain substring from a string, split by that and join.

```
.replace(/h/g,'') // 17 bytes
.split`h`.join`` // 16 bytes
.replaceAll('h','') // 19 bytes

```

Sadly the ES2021 replaceAll is longer.
> 4 votes

# Answer
**Less/Greater than "10/100/1000..." vs "9/99/999...":**

```
//for(i=0;i<20;i++){
    if(i<10){}else{}
    if(i>9){}else{}
//}

```

**Note:** Just remember to swap what is inside the `if` with the `else`
> 3 votes

# Answer
For strings and arrays, instead of using `a=b.length>a.length?b:a` to set **`a`** to **`b`** if `b.length > a.length`, you can use `a=b[a.length]?b:a`.

**Note:** If **`b`** is an array and contains either **`0`** or **`false`**, you'll have to use `a=b[a.length]!=null?b:a` (still one character shorter).
> 3 votes

# Answer
# Return `1` for `true`, `0` for `false` as much as possible

This should be relatively self-explanatory.

```
function f(x){return x?(d(x),!1):!0}
function f(x){return x?(d(x),0):1}
function f(x){return !x&&d(x)&0}
if(f(v)){/* ... */}

// ES6 versions
let f=x=>x?(d(x),!1):!0
let f=x=>x?(d(x),0):1
let f=x=>!x&&d(x)&0
if(f(v)){/* ... */}

```
> 3 votes

# Answer
# If returning void, see if it is shorter to return something useful. This is kinda language-agnostic here.

This isn't an easy apply-anywhere thing, either, though. Word of warning, make sure your parentheses are balanced.

In ES6, in this example, **6 bytes saved**

```
let l=x=>console.log(m+x),x=1,a;l(a=f(x));l(a=g(a));l(h(a))
let l=x=>(console.log(m+x),x),x=1;l(h(l(g(l(f(x))))))

```

In ES5, it is only **1 byte saved**

```
function l(x){console.log(m+x)}var x=1,a;l(a=f(x));l(a=g(a));l(h(a))
function l(x){console.log(m+x);return x}var x=1;l(h(l(g(l(f(x))))))

```
> 3 votes

# Answer
**Use Bitwise as Logic Operators When Dealing With Booleans**

```
a = 1 //although this would usually be a boolean expression
b = 0 //same
if(a&&b)c()
if(a&b)c()

```

Then, use `&&` lazy evaluation to make a chain of ampersands:

```
a&b&&c()
if(a&&b)c()

```

**Saves 3 characters**
> 3 votes

# Answer
When stringifying dates, `.toJSON` saves 5 bytes over `.toISOString`. Apparently this was supported as far back as Firefox 4, but this answer is only the sixth on PPCG to mention it.
> 3 votes

# Answer
# Shortening Promise Chains with `async`/`await`

Sometimes you can shorten longer promise chains with `async`/`await`. The main benefit is from getting rid of the beginning of the arrow function in each `then` callback. `.then(x=>x` (10) gets replaced with `await(` (-4), but you first pay with `async` (+6). So to make up for the initial overhead of 6 bytes, you'd need at least two `then` chains to get any benefit.

```
+-------------+----------------+
| then chains | async overhead |
+-------------+----------------+
| 0           | +6             |
| 1           | +2             |
| 2           | -2             |
| 3           | -4             |
| …           | …              |
+-------------+----------------+

```

## Example 1

```
x=>x().then(y=>y.foo()).then(z=>z.bar())
async x=>await(await(x()).foo()).bar()

```

## Example 2

```
u=>fetch(u).then(r=>r.text()).then(t=>/\0/.test(t))
async u=>/\0/.test(await(await fetch(u)).text()))

```
> 3 votes

# Answer
1. Checking if a string includes a character, e.g. 0:

```
if(s.indexOf(0)!=-1)
if(~s.indexOf(0))    // -3
if(s.includes(0))    // -3
if(s.match(/0/))     // -4
if(/0/.exec(s))      // -5

```

`exec` is shorter than `match`.

2. Ceiling a division:

```
Math.ceil(a/b)
(a+b-1)/b|0    // -3

```

Even shorter (if you don't mind editing a):

```
--a/b+1|0     // -5
-~(--a/b)     // -5 too

```
3. String to array

```
// s is a string
Array.from(s)
[...s]        // -7

```
> 3 votes

# Answer
# Length of deprecating array +1

```
1+X.length
X.push(0)   // 1 byte shorter

```
> 3 votes

# Answer
**Adding Values with Implicit Casting**

Improved zzzzBov solution:

```
//not so good
-(-a-b)==c;

//best
a- -b==c;
a-+-b==c;

```

We save `2` characters by using these solutions.
> 2 votes

# Answer
Convert ints to strings by adding an empty string

For example:

```
39323+""

```

Returns:

```
"39323"

```

**Update**:

Adding `[]` works too
> 2 votes

# Answer
# If iterating through own properties, prefer Object.keys.

**15 bytes saved**

```
for(let p in o)if(o.hasOwnProperty(e)){/* ... */}
for(let p of Object.keys(o)){/* ... */}
Object.keys(o).map(p=>{/* ... */})

```

This is also the case for ES5, where it is **7 bytes saved**.

```
for(var p in o)if(o.hasOwnProperty(e)){/* ... */}
Object.keys(o).map(function(p){/* ... */})

```

If you do that more than once, alias it as a function.

In this ES6 example, **6 bytes saved**. It still saves bytes in ES5, but only if used 3 times or more.

```
Object.keys(o).map(p=>{/* ... */})Object.keys(o).map(p=>{/* ... */})
i=f=>Object.keys(o).map(f);i(p=>{/* ... */});i(p=>{/* ... */})

```
> 2 votes

# Answer
# `Array#concat()` and the spread operator

This largely depends on the situation.

---

## Combining multiple arrays.

Prefer the concat function unless cloning.

**0 bytes saved**

```
a.concat(b)
[...a,...b]

```

**3 bytes wasted**

```
a.concat(b,c)
[...a,...b,...c]

```

**3 bytes saved**

```
a.concat()
[...a]

```

**6 bytes saved**

```
// Concatenate array of arrays
[].concat.apply([],l)
[].concat(...l)

```

---

## Prefer using an already existing array to `Array#concat()`.

Easy **4 bytes saved**

```
[].concat(a,b)
a.concat(b)

```
> 2 votes

# Answer
# Function

If you need a function in as few bytes as possible, and any function will do (perhaps you just want to access some of the goodies from `Function.prototype`), then here are some options (starting with large ones):

```
Function.prototype
[].map
Date
CSS     (available in modern browsers)
Map     (ES6: available in Node and modern browsers)
Set     (ES6: available in Node and modern browsers)
URL     (available in very old browsers, but not in Node)

```

So if you want a reference to the `call` function, you can get it like this:

```
c=URL.call

```
> 2 votes

# Answer
If you are using the same function more than once, it's often useful to reference the function to a new function name. I.e:

Instead of:

```
Math.sqrt(4)
Math.sqrt(16)
Math.sqrt(100)

```

you can do:

```
r=Math.sqrt
r(4)
r(16)
r(100)

```
> 2 votes

# Answer
## Square root hack

Use `(x+2)**(1/2)` instead of `Math.sqrt(x+2)`.
> 2 votes

# Answer
# Abusing template literals

You can often save two bytes on parentheses by replacing

```
a.join('+')

```

with

```
a.join`+`

```

This works for most properties that take in a single string.

*This has been used in other answers, but there isn't an answer dedicated to this specifically.*
> 2 votes

# Answer
You can produce `undefined` with `0[0]` to save 5 bytes. This is 2 bytes shorter than the more traditional `void 0` method of creating `undefined`.
> 2 votes

# Answer
When using regexps, if you need `.` to exclude `\n`, so you can't use the `/s` flag, you can uniquely (other regex engines do not allow this) write `[^]` instead of `[\s\S]` saving 3 bytes.
> 2 votes

# Answer
Instead of `a>b&&(A[x]=y)`, write `A[a>b&&x]=y`, so long as `A[false]` isn't used
> 2 votes

# Answer
# Test Equality to Zero

Instead of

```
num==0

```

You can use

```
!num

```
> 2 votes

# Answer
## Avoid `typeof`

`typeof x === 'number'` is pretty verbose if you need to distinguish your input values by type. (Granted, this is rare in most coding challenges). `typeof x=='number'` is barely better, you still have an operator and a constant that are pretty heavy on byte count.

Instead, coerce the input to the desired type and use `===` to check whether the result is the same type (and value) as the input:

```
Number(x)===x

```

or better yet

```
+x===x

```

| `typeof` expression | equivalent `===` check | golfed |
| --- | --- | --- |
| `typeof x === 'boolean'` | `Boolean(x) === x` | `!!x===x` |
| `typeof x === 'string'` | `String(x) === x` | `""+x===x` |
| `typeof x === 'number'` | `Number(x) === x` | `+x===x` |
| `typeof x === 'bigint'` | `BigInt(x) === x` | `BigInt(x)===x` |
| `typeof x === 'object' && x !== null` | `Object(x) === x`<sup>1</sup> | `Object(x)===x`<sup>1</sup> |
| `typeof x === 'undefined'` | `void x === x` | `x===[][0]`<sup>2,3</sup> |
| `x === undefined || x === null` | `x == null`<sup>2</sup> | `x==null` |

There exist no coercion functions for `function`s or `symbol`s. You'll have to keep using `typeof` for them.

<sub>1: `Object(x) === x` also detects function objects
2: that's a different trick, but I wanted to include it for completeness
3: thanks to comment by @noodle man</sub>
> 2 votes

# Answer
You can check if a value is \*truish by simply passing it:

```
if(val){...}

```

> \*everything different than `0`, `0n`, `""`, `false`, `null`, `undefined` and `NaN` is evaluated to *true* !

This method can be applied with many other functions and operators:

* **ternary operator** `val?"true":"false";`
* **for loop** `for(;val;){...}`
* **while loop** `while(val){...}`
* etc...
> 1 votes

# Answer
# ES6-specific: avoid `Function#bind()`

Self-explanatory, **7 bytes saved**

```
f.bind(null,x,...xs)
_=>f(x,...xs)

```

# Use sloppy mode to avoid variable declarations

Here, **8 bytes saved**

```
a.forEach(e=>{let b=e+1,c=d(b)+2;f(e);g(b);h(c);i(b,c)})
a.forEach(e=>{f(e);g(b=e+1);h(c=d(b)+2);i(b,c)})

// Even better, reuse variables and use `Array#map()`
// Drops an additional 6 bytes
a.map(e=>{f(e++);g(e);h(b=d(e)+2);i(e,b)})

```

This also holds in ES5. Here, **8 bytes saved**

```
a.forEach(function(e){let b=e+1,c=d(b)+2;f(e);g(b);h(c);i(b,c)})
a.forEach(function(e){f(e);g(b=e+1);h(c=d(b)+2);i(b,c)})

// Even better, reuse variables and use `Array#map()`
a.map(function(e){f(e++);g(e);h(b=d(e)+2);i(e,b)})

```
> 1 votes

# Answer
This is one of my favorites - ES6

```
'da,dad,sa'.split``
 ["d", "a", ",", "d", "a", "d", ",", "s", "a"]

'da,dad,sa'.split`,`
["da", "dad", "sa"]

```
> 1 votes

# Answer
Use the simplest shortening method available - your variable declaration!

```
var myName = "Jack";

```

Obviously is very long compared to:

```
m="Jack"

```

It's a whole 12 characters shorter. You have all 64 of these single-character variable names available:

```
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_

```

And also - never use spaces or semicolons in your variable naming - changing `m = "Mum";` to `m="Mum"` saves another three characters.
> 1 votes

# Answer
# Remove duplicates from array

```
a.filter(e=>!(t[e]=e in t))

```

```
let unique= (a,t={})=> a.filter(e=>!(t[e]=e in t));

// "stand-alone" version working with global t:
// a1.filter((t={},e=>!(t[e]=e in t)));

// Test data
let a1 = [5,6,0,4,9,2,3,5,0,3,4,1,5,4,9];
let a2 = [[2, 17], [2, 17], [2, 17], [1, 12], [5, 9], [1, 12], [6, 2], [1, 12]];
let a3 = ['Mike', 'Adam','Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl'];

// Results
console.log(JSON.stringify( unique(a1) ))
console.log(JSON.stringify( unique(a2) ))
console.log(JSON.stringify( unique(a3) ))
```

**O(n)** performance; we assume your array is in `a` and `t={}`. Explanation here

And shorter but slower version (which not work with 2D arrays)

```
[...new Set(a)]

```

```
let unique = a => [...new Set(a)];

// Test data
let a1 = [5, 6, 0, 4, 9, 2, 3, 5, 0, 3, 4, 1, 5, 4, 9];
let a3 = ['Mike', 'Adam', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl'];

// Results
console.log(JSON.stringify(unique(a1)))
console.log(JSON.stringify(unique(a3)))
```
> 1 votes

# Answer
# For ES6 arrow functions with 2 parameters, nest functions

```
f=(x,k)=>x+k
f=x=>k=>x+k

```

Only works in some cases. E.g. for recursive functions, this doesn't help because calling is one byte longer:

```
f(1,2)
f(1)(2)

```
> 1 votes

# Answer
### output

sometimes you can use `throw` instead of `alert` to save 1 byte

```
throw !0
alert(!0)

```

Do note that the program terminates, so you can't use it for loops.
> 1 votes

# Answer
# Compressing Long Strings

If you have a very long, repetitive string, you can compress it using something similar to:

```
``.replace(/./gs,p=>p.charCodeAt().toString(2).padStart(7,0)).match(/.{n}/g).map(p=>+("0b"+p))

```

The ```` should contain any code points between 0 and 127, with some needing to be escaped. These are: `0x00` (`\0` or `\x00`, depending on whether a digit is following), `0x0d` (`\r`), `0x5c` (`\\`), and `0x60` (`\``). In some very rare cases you may need to escape a `$` if it is followed by a `{`.

You should replace `n` with the number of bits the output should be grouped into, and you can put any code you want in the final `map` and use `+("0x"+p)` to get the decimal value wherever necessary.

This adds roughly 100 bytes of overhead, compared to `atob`/`btoa`'s 8. This method fits just under 7 bits per character in the string (due to escaping), and takes advantage of the fact that JS lets you put pretty much any code points into a string.

In order for this to be shorter, the data compressed needs to be one of:

* Binary or numeric data, which is difficult to work with using `atob` and `btoa`
* A string that has few distinct characters and is longer than 100 or so characters

In order to create a compressed string, convert each chunk of the string to binary using whatever encoding you want, then break it into chunks 7 bits wide. You may need to add some padding, which will be ignored if it is under 7 bits. Then, convert these into code points and paste them into the string.
> 1 votes

# Answer
I have adapted to my needs the **Unicode shortcuts** method by **@bebe**.

The problem which many have faced with the original solution is due to the fact that some of the functions/properties belong to a class prototype while others to a class itself. These need to be handled separately.

The minified code now takes 132 bytes:

```
[Number,S=String,Array].map(r=>{f=(r=>Object.getOwnPropertyNames(r).map((e,t)=>r[S.fromCharCode(t+248)]=r[e])),f(r),f(r.prototype)})

```

Of course, you can drop *Number* and *Array* if unused from the initial array to save a couple of bytes. *String* is used in the code itself so removing it doesn't help a lot.

Part of the problems came from *Math* having no protype thus requiring its special handling. Besides the name in the initial array it also takes another 5 bytes to skip prototype handing. So use the variant below only if you need *Math*:

```
[Number,S=String,Array,Math].map(r=>{f=(r=>Object.getOwnPropertyNames(r).map((e,t)=>r[S.fromCharCode(t+248)]=r[e])),f(r),r.E||f(r.prototype)})

```

I use the same code for **Node.js** (v12.19.0) and **Chrome** (90.0.4430.212 x64).

```
Code Char Number          Number.prototype String        String.prototype  Array    Array.prototype Math
248  ø    length            constructor    length        length            length    length         abs
249  ù    name              toExponential  name          constructor       name      constructor    acos
250  ú    prototype         toFixed        prototype     anchor            prototype concat         acosh
251  û    isFinite          toPrecision    fromCharCode  big               isArray   copyWithin     asin
252  ü    isInteger         toString       fromCodePoint blink             from      fill           asinh
253  ý    isNaN             valueOf        raw           bold              of        find           atan
254  þ    isSafeInteger     toLocaleString               charAt                      findIndex      atanh
255  ÿ    parseFloat                                     charCodeAt                  lastIndexOf    atan2
256  Ā    parseInt                                       codePointAt                 pop            ceil
257  ā    MAX_VALUE                                      concat                      push           cbrt
258  Ă    MIN_VALUE                                      endsWith                    reverse        expm1
259  ă    NaN                                            fontcolor                   shift          clz32
260  Ą    NEGATIVE_INFINITY                              fontsize                    unshift        cos
261  ą    POSITIVE_INFINITY                              fixed                       slice          cosh
262  Ć    MAX_SAFE_INTEGER                               includes                    sort           exp
263  ć    MIN_SAFE_INTEGER                               indexOf                     splice         floor
264  Ĉ    EPSILON                                        italics                     includes       fround
265  ĉ                                                   lastIndexOf                 indexOf        hypot
266  Ċ                                                   link                        join           imul
267  ċ                                                   localeCompare               keys           log
268  Č                                                   match                       entries        log1p
269  č                                                   matchAll                    values         log2
270  Ď                                                   normalize                   forEach        log10
271  ď                                                   padEnd                      filter         max
272  Đ                                                   padStart                    flat           min
273  đ                                                   repeat                      flatMap        pow
274  Ē                                                   replace                     map            random
275  ē                                                   search                      every          round
276  Ĕ                                                   slice                       some           sign
277  ĕ                                                   small                       reduce         sin
278  Ė                                                   split                       reduceRight    sinh
279  ė                                                   strike                      toLocaleString sqrt
280  Ę                                                   sub                         toString       tan
281  ę                                                   substr                                     tanh
282  Ě                                                   substring                                  trunc
283  ě                                                   sup                                        E
284  Ĝ                                                   startsWith                                 LN10
285  ĝ                                                   toString                                   LN2
286  Ğ                                                   trim                                       LOG10E
287  ğ                                                   trimStart                                  LOG2E
288  Ġ                                                   trimLeft                                   PI
289  ġ                                                   trimEnd                                    SQRT1_2
290  Ģ                                                   trimRight                                  SQRT2
291  ģ                                                   toLocaleLowerCase
292  Ĥ                                                   toLocaleUpperCase
293  ĥ                                                   toLowerCase
294  Ħ                                                   toUpperCase
295  ħ                                                   valueOf
296  Ĩ                                                   replaceAll (*)

```

**Notes:**

*replaceAll* (marked with an asterisk) exists only for *Chrome*.

Some comments where criticizing the usage of non-standard alphabet. If you manage to find another consistent range of Unicode characters that **can** be used as property names in JS then feel free to improve this answer. I couldn't find better than the original.
> 0 votes

# Answer
If `f` returns `0` and `1`, then `f(0)|f(1)` can be `f(f(1))`
> 0 votes

# Answer
# Pass expression rather than function

```
g`x+y`

```

is shorter than

```
g(x=>y=>x+y)

```

if `g` is used for 2 times

```
eval(z,x=p+1,y=q-1)

```

is 9 bytes longer than

```
z(p+1,q-1)

```

and

```
eval(z)

```

is only 1 byte longer than

```
z(x,y)

```

Recent use here
> 0 votes

# Answer
# Last value of a comma-separated string

```
a = "1,2,3,4,5"
a.split`,`.at(-1) // 17 bytes
eval(a)           // 7 bytes

```

If the input is array, `at` is shorter, byt `eval` is still shorter than `slice`:

```
a = [1,2,3,4,5]
eval(a+'')  // 10 bytes
a.slice(-1) // 11 bytes
a.at(-1)    //  8 bytes

```

Since it's sometimes easier to build string than array (`[...a,b]` vs `a+[,b]`) changing to string might be useful
> 0 votes

# Answer
# Add elements to Array

The `concat` is more useful than `push` in many situations because it returns whole array e.g. we want from `d=[{a:1,b:2,c:3},{a:7,b:8,c:9}]` generate 'pivot object' `p={"a":[1,7],"b":[2,8],"c":[3,9]}`

```
let p={}, d=[{a:1,b:2,c:3},{a:7,b:8,c:9}];

d.map(x=> Object.keys(x).map(k=> p[k]= (p[k]||[]).concat(x[k]) ))

console.log(JSON.stringify(p));
```
> -1 votes

# Answer
The `9**999` is `Infinity` shortcut (2 characters shorter)

```
console.log( 9**999===Infinity )
```
> -1 votes

# Answer
**Converting a string to an int/float by subtracting a empty array**

Before(22 bytes)

```
parseFloat("12.52463")

```

After(13 bytes, saved 9 bytes)

```
"12.52463"-[]

```
> -2 votes

---
Tags: code-golf, tips, javascript
---


title: A Lazy Bag of Bread

text:
# Question
Title: A Lazy Bag of Bread
I work at a bakery that serves Wheat, Rye, Barley, Grain, and French bread, but the baker's a little weird - he stacks the loaves in random order, and sometimes just leaves some shelves at the end empty.

Each day, the same customer comes in and asks for one of each loaf of bread, but the tricky thing is, he's a germophobe, so when I fill his bag, I can't take loaves from two adjacent shelves in consecutive selections.

It takes one second to walk between adjacent shelves. It's a busy store; for any random configuration of loaves, I'd like to minimize the time it takes to get one of each unique loaf. I can start and end at any shelf.

If today's ordering is `W B W G F R W`, a possible path is `0, 3, 5, 1, 4`, for a total of 12 seconds: `abs(3-0) + abs(5-3) + abs(1-5) + abs(4-1) = 12`

(`1, 2, 3, 4, 5` doesn't work, because bread is picked consecutively from adjacent shelves.)

If it's `B W B G B F B R B W B F`, a possible path is `1, 3, 5, 7, 10`, for a total of 9 seconds.

The manager always makes sure there is a possible solution, so I don't need to worry about catching bad inputs. He usually sends me the order in a file, but if I want, I can type it to STDIN or read it a different way. I'd like the program to print out the indices of the best path, as well as its time, according to default I/O rules.

In short:

1. 5 types of bread.
2. Loaf orders appears as strings of random order and length.
3. Must select one of each unique loaf.
4. Cannot make adjacent consecutive selections.
5. Minimize the distance between selection indices.
6. Don't need to worry about invalid inputs.
7. Default I/O rules apply.

This is , shortest byte count wins.

# Answer
# JavaScript (ES6), 114 bytes

*Saved 1 byte thanks to @Oliver*

Takes input as an array of characters. Outputs a comma-separated string where the first value is the total time and the next ones describe the path.

```
a=>(b=g=(r,s=o='',c,p)=>s[c>b|4]?o=(b=c)+r:a.map((v,i)=>s.match(v)||(d=p<i?i-p:p-i)<2||g([r,i],s+v,~~c+d,i))&&o)``

```

Try it online!

### Commented

```
a => (                          // a[] = input array
  b =                           // b = best score so far (initially a non-numeric value)
  g = (                         // g = recursive function taking:
    r,                          //   r = path
    s =                         //   s = string of collected loaves of bread
    o = '',                     //   o = final output
    c,                          //   c = current cost
    p                           //   p = index of the last visited shelf
  ) =>                          //
    s[c > b                     // if the final cost is not greater than our best score
            | 4] ?              // and we've successfully collected 5 loaves of bread:
      o = (b = c) + r           //   update the current output and the best score
    :                           // else:
      a.map((v, i) =>           //   for each loaf of bread v at shelf i in a[]:
        s.match(v) ||           //     if we've already collected this kind of bread
        (d =                    //     or the distance d
          p < i ? i - p : p - i //     defined as the absolute value of p - i
        ) < 2 ||                //     is less than 2: stop recursion
        g(                      //     otherwise, do a recursive call to g() with:
          [r, i],               //       r updated with the index of the current shelf
          s + v,                //       s updated with the current loaf of bread
          ~~c + d,              //       c updated with the last distance
          i                     //       i as the index of the last shelf
        )                       //     end of recursive call
      )                         //   end of map()
      && o                      //   return the current output
  )``                           // initial call to g() with r = [""]

```
> 3 votes

# Answer
# Python 2, ~~212~~ 210 bytes

```
lambda s:min((sum(h(p)),p)for b in combinations(range(len(s)),5)for p in permutations(b)if(len(set(s[i]for i in p))==5)&all(d>1for d in h(p)))
h=lambda p:[abs(y-x)for x,y in zip(p,p[1:])]
from itertools import*

```

Try it online!

2 bytes thx to Jonathan Frech.
> 0 votes

# Answer
# Python3, 244

```
def f(l):
 q=[(0,0,[],[])]
 L,C=0,0
 for a,r,b,c in q:
  if C and r>=C:continue
  if not{*l}-{*c}:L=b;C=r;continue
  for i,A in enumerate(l):
   if i not in b and A not in c and(c==[]or abs(b[-1]-i)!=1):q+=[(i,r+abs(a-i),b+[i],c+[A])]
 return L

```

Try it online!
> 0 votes

---
Tags: code-golf, sequence
---


title: Solve an Ice Maze

text:
# Question
Title: Solve an Ice Maze
Ice mazes have been one of my favorite staples of Pokémon games since their debut in Pokémon Gold and Silver. Your task will be to make a program that solves these types of problems.

Ice mazes primarily consist of, as the name suggests, ice. Once the player moves in a direction on ice they will continue to move in that direction until they collide with some obstacle. There is also soil which can be moved across freely and will stop any player moving across it. The last obstacle is stone. Stone cannot occupy the same space as the player and if the player attempts to move into it they will stop moving before they can.

You will receive a two dimensional container of values, such as an list of lists or a string separated by newlines, containing 3 distinct values for each of the 3 types of flooring (Ice, Soil, and Stone). You will also receive two pairs (or other equivalent two value containers) that indicate a start and goal coordinate in the maze. These may be zero or one indexed.

You must output a list of moves (4 distinct values with a bijection onto N,E,S,W) that would cause the player to arrive at the end when carried out.

Input will always have a closed perimeter of stone around the maze so you do not have to worry about the player exiting the maze

This is so the fewest bytes wins

## Test Cases

Here `.` will represent ice, `~` will represent soil, and `O` will represent a stone. Coordinates are 1 indexed. Each letter in the solution represents the direction beginning with that letter (e.g. `N`= North)

---

### Input

```
OOOOO
OO.OO
O...O
OOOOO

Start : 3,3
End   : 3,2

```

### Output

```
N

```

---

### Input

```
OOOOOOOOOOOOOOOOO
O........O.....OO
O...O..........OO
O.........O....OO
O.O............OO
OO.......O.....OO
O.............OOO
O......O.......~O
O..O...........~O
O.............OOO
O.......O......OO
O.....O...O....OO
O..............OO
OOOOOOOOOOOOOO~~O
OOOOOOOOOOOOOOOOO

Start : 15,12
End   : 16,8

```

### Output

```
N,W,N,E,N,E,S,W,N,W,S,E,S,E,N,E,N

```

---

### Input

```
OOOOOOOOOOOOOOOO
O~~~~~OOOOO~~~~O
O~~O~OOOOOOO~~OO
O...O..........O
O........O.....O
O..............O
OO.............O
O.............OO
O....~....O....O
O..............O
O..............O
OOOOOOOOOOOOOOOO

Start : 2,2
End   : 14,3

```

### Output

```
E,S,S,W,N,E,N

```

---

### Input

```
OOOOOOOOOOOOOOOOOOO
O~~~~~~~OOOOOOOOOOO
O~~~~...OOOOOOOOOOO
OO~O~..OOOOOOOOOOOO
O..OO.............O
O..............O..O
O....O............O
O.O............~..O
O........OOOO.....O
O.......OOOOO.....O
O.......O~~~O.....O
O.......~~~~~.....O
O.......~~~~~.....O
O..........O......O
O..O..~...........O
O...............O.O
O.....O...........O
O.................O
OOOOOOOOOOOOOOOOOOO

Start : 2,2
End   : 11,11

```

### Output

```
E,E,E,E,E,S,S,E,N,W,S,E,N,N,N

```

# Answer
## Mathematica, 247 bytes

```
(p=x#[[##&@@x]];m={c,v}Switch[p[c+v],0,m[c+v,v],1,c+v,_,c];g=Cases[Array[List,Dimensions@#],c_/;p@c<2,{2}];a=cm[c,#]&/@{{1,0},{-1,0},{0,1},{0,-1}};e=Flatten[Table[#->c,{c,a@#}]&/@g,1];Normalize/@Differences@FindPath[Graph[e],#2,#3][[1]])&

```

With line breaks:

```
(
p=x#[[##&@@x]];
m={c,v}Switch[p[c+v],0,m[c+v,v],1,c+v,_,c];
g=Cases[Array[List,Dimensions@#],c_/;p@c<2,{2}];
a=cm[c,#]&/@{{1,0},{-1,0},{0,1},{0,-1}};
e=Flatten[Table[#->c,{c,a@#}]&/@g,1];
Normalize/@Differences@FindPath[Graph[e],#2,#3][[1]]
)&

```

My immediate idea was to represent the ice and soil positions as nodes in a graph with directed edges corresponding to legal moves, then use `FindPath`. One might think that determining the legal moves would be the easy part and finding the solution would be the hard part. For me, it was the opposite. Open to suggestions on how to compute the edges.

First argument `#` is a 2D array where `0` represents ice, `1` represents soil, and `2` represents stone.

Second argument `#2` and third argument `#3` are the starting and ending points, respectively, in the form `{row,column}`.

is the 3 byte private use character `U+F4A1` representing `\[Function]`.

## Explanation

```
p=x#[[##&@@x]];

```

Defines a function `p` which takes a list `x` of the form `{row,column}` and outputs `#[[row,column]]`; i.e., the ice/soil/stone value at that coordinate.

```
m={c,v}Switch[p[c+v],0,m[c+v,v],1,c+v,_,c]

```

Defines a function `m` which takes a starting position `c` and direction vector `v` and recursively determines where you would end up. If `c+v` is ice, then we continue sliding from that point, so it returns `m[c+v,v]`. If `c+v` is soil, then we move to `c+v` and stop. Otherwise (if `c+v` is stone or out of bounds), you don't move. Note that this is only intended to be called on ice or soil positions.

```
g=Cases[Array[List,Dimensions@#],c_/;p@c<2,{2}];

```

Defines the list `g` of ice and soil positions (`p` value less than `2`).

```
a=cm[c,#]&/@{{1,0},{-1,0},{0,1},{0,-1}};

```

Defines a function `a` which takes a starting position `c` and returns the results of moving in the `{1,0}`, `{-1,0}`, `{0,1}`, and `{0,-1}` directions. There may be some redundancy. Again, this assumes that `c` corresponds to ice or soil.

```
e=Flatten[Table[#->c,{c,a@#}]&/@g,1];

```

Defines the list `e` of directed edges representing legal moves. For each position `#` in `g`, compute the table of edges `#->c` for each `c` in `a@#`. Then since we'll end up with a sublist for each position `#`, I flatten the first level. There may be some loops and multiple edges.

```
Normalize/@Differences@FindPath[Graph[e],#2,#3][[1]]

```

`Graph[e]` is the graph where the nodes are the legal positions (ice or soil) and the edges represent legal moves (possibly bumping into a stone and not moving). We then use `FindPath` to find a path from `#2` to `#3` represented as a list of nodes. Since `FindPath` can take additional arguments to find more than one path, the result will actually be a list containing a single path, so I take the first element using `[[1]]`. Then I take the successive `Differences` of the coordinates and `Normalize` them. Thus up is `{-1,0}`, down is `{1,0}`, right is `{0,1}` and left is `{0,-1}`.

## Test cases
> 4 votes

# Answer
# JavaScript (ES6) 180 ~~183~~

```
(m,[x,y],[t,u],o=~m.search`
`,s=[[x-y*o,[]]],k=[])=>eval("for(i=0;[p,l]=s[i++],k[p]=t-u*o-p;)[-1,o,1,-o].map(d=>k[q=(M=p=>+m[p+=d]?m[p]<8?M(p):p:p-d)(p)]||s.push([q,[...l,d]]));l")

```

Using a BFS, like I did to solve this related challenge

**Input**
The maze map is a multiline string, using `O` or `0` for stone, `8` for soil and any nonzero digit less than 8 for ice (`7` look good).
Start and end position are zero based.

**Output**
A list of offset, where -1 is `W`, 1 is `E`, negative less than -1 is `N` and a positive greater than 1 is `S`

*Less golfed*

```
(m,[x,y],[t,u])=>{
  o=~m.search`\n`
  s=[[x-y*o,[]]]
  k=[]
  for(i=0; [p,l]=s[i++], k[p]=1, t-u*o != p;)
  {
    [-1,o,1,-o].map(d=>(
      M=p=>+m[p+=d] ? m[p]<8 ? M(p) : p : p-d,
      q=M(p),
      k[q]||s.push([q,[...l,d]])
    ))
  }
  return l
}

```

**Test**

```
Solve=
(m,[x,y],[t,u],o=~m.search`
`,s=[[x-y*o,[]]],k=[])=>eval("for(i=0;[p,l]=s[i++],k[p]=t-u*o-p;)[-1,o,1,-o].map(d=>k[q=(M=p=>+m[p+=d]?m[p]<8?M(p):p:p-d)(p)]||s.push([q,[...l,d]]));l")

function Go(maze) {
  var map = maze.textContent;
  var [sx,sy, dx,dy] = map.match(/\d+/g)
  --sx, --sy // zero based
  --dx, --dy // zero based
  map = map.split('\n').slice(1).join('\n') // remove first line
  var result = Solve(map.replace(/\./g, 7).replace(/~/g, 8), [sx,sy], [dx,dy])
  S.textContent = result
  Animate(maze, map, result, sx, sy)
}

function Display(maze, map, pos) {
  var row0 = maze.textContent.split('\n')[0]
  map = [...map]
  map[pos] = '☻'
  maze.textContent = row0+'\n'+map.join('')
}

function Animate(maze, map, moves, x, y) {
  console.log('A',moves)
  var offset = map.search('\n')+1
  var curPos = x + offset * y
  var curMove = 0
  var step = _ => {
    Display(maze, map, curPos)
    if (curMove < moves.length)
    {
      curPos += moves[curMove]
      if (map[curPos] == 'O')
      {
        curPos -= moves[curMove]
        ++curMove
      }
      else
      {
        if (map[curPos] == '~') {
          ++curMove
        }
      }
      setTimeout(step, 100)
    }
    else
      setTimeout(_=>Display(maze,map,-1),500)
  }
  step()
}
```

```
td {
  border: 1px solid #888;
}
```

```
Select maze<pre id=S></pre>
<table cellspacing=5><tr>
<td valign=top><input type=radio name=R onclick='Go(M1)'><br>
<pre id=M1>3,3 to 3,2
OOOOO
OO.OO
O...O
OOOOO</pre></td>
<td valign=top><input type=radio name=R onclick='Go(M2)'><br>
<pre id=M2>15,12 to 16,8
OOOOOOOOOOOOOOOOO
O........O.....OO
O...O..........OO
O.........O....OO
O.O............OO
OO.......O.....OO
O.............OOO
O......O.......~O
O..O...........~O
O.............OOO
O.......O......OO
O.....O...O....OO
O..............OO
OOOOOOOOOOOOOO~~O
OOOOOOOOOOOOOOOOO</pre></td>
<td valign=top><input type=radio name=R onclick='Go(M3)'><br>
<pre id=M3>2,2 to 14,3
OOOOOOOOOOOOOOOO
O~~~~~OOOOO~~~~O
O~~O~OOOOOOO~~OO
O...O..........O
O........O.....O
O..............O
OO.............O
O.............OO
O....~....O....O
O..............O
O..............O
OOOOOOOOOOOOOOOO</pre></td>
<td valign=top><input type=radio name=R onclick='Go(M4)'><br>
<pre id=M4>2,2 to 11,11
OOOOOOOOOOOOOOOOOOO
O~~~~~~~OOOOOOOOOOO
O~~~~...OOOOOOOOOOO
OO~O~..OOOOOOOOOOOO
O..OO.............O
O..............O..O
O....O............O
O.O............~..O
O........OOOO.....O
O.......OOOOO.....O
O.......O~~~O.....O
O.......~~~~~.....O
O.......~~~~~.....O
O..........O......O
O..O..~...........O
O...............O.O
O.....O...........O
O.................O
OOOOOOOOOOOOOOOOOOO</pre></td>
</tr></table>
```
> 4 votes

# Answer
# Python3, 439 bytes

```
def f(b,s,S,e,E):
 q=[(s,S,[[(s,S)]],'')]
 for x,y,d,p in q:
  if(x,y)==(e,E):return p
  for D,X,Y in[('E',0,1),('W',0,-1),('N',-1,0),('S',1,0)]:
   if'~'==b[x][y]and(T:=[(x+X,y+Y)])not in d and'O'!=b[x+X][y+Y]:q+=[(*T[0],d+[T],p+D)]
   elif'.'==b[x][y]:
    T,Q,W=[],x,y
    while 1:
     if(S:=b[Q+X][W+Y])in'.~':
      T+=[(Q+X,W+Y)];Q+=X;W+=Y
      if'~'==S:break
     else:break
    if(U:=sorted(T))not in d and U:q+=[(Q,W,d+[U],p+D)]

```

Try it online!
> 1 votes

---
Tags: code-golf, grid, path-finding, maze
---