text:
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

I was actually wondering, is it allowed to put variables in global (saves var)? And should JavaScript golf code be a function or output something directly? I honestly think this can make much difference.

@primvdb: It is allowed, but you have to be careful because it can cause side-effects if a function is called multiple times and it is manipulating global variables, or if it is a recursive function.

This link has a bunch of tips relevant here.

I have discovered probably the most useless tip: a private class element doesn’t require a space before the private identifier in cases where it is preceded by a keyword: (class{static #x = 1;get #y(){};set #y(z){}}) can be rewritten as (class{static#x = 1;get#y(){};set#y(z){}}). This makes for some nice obfuscation, too, but I can’t think of a practical example in code golf.

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'.

c = ~~a-~~b should be c = ~~a+~~b.  Also, you can implicitly cast to integer using |0, for example Math.random()*6|0.

It's cheaper to coerce a string to a number with the unary plus operator. If a and b are strings, you can do +a+b to convert to number and add them.

Where can I add https://github.com/jed/140bytes/wiki/Byte-saving-techniques ?

I swear I'm going to use d- -b in my code someday...

+a+b doesn't work (at least on mine...) //
a="1",b="1",+a+b //
gives "11"

For "Use Array-Access for repeat function calls" if you're using the function more than twice on the same object, what's a bit shorter is to assign the function to a new member like a.f=a.longfunctionname;a.f(b);a.f(c);a.f(d)

Again, for loops and the stated while loop equivalent will differ in how they handle continue keywords.

@SuperJedi224, continue is far too many characters to be worthwhile. Avoid it.

@zzzzBov: In code golf, that is usually true, but that's still a point that's worth mentioning.

Instead using document.getElementById('X').something, just X.something works as well

Instead of ~~a+~~b, I think you can use ~-a-~b

top is shorter than self or this, and it works in local context too

Splitting with numbers to save the quotemarks:
"alpha,bravo,charlie".split(",") // before
"alpha0bravo0charlie".split(0)   // after

It works, and I've used it for multiple digits.

Lol this is actually pretty creative

in ES6 this doesn't matter anymore, you can just do .split\...``

"alpha,bravo,charlie".split\,``

I've also used "AlphaBravoCharlie".split(/(?=[A-Z])/) once. Only useful when you have a lot of words to split.

You could also do this: "alpha,bravo,charlie".split\,``

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.

Is the semicolon necessary at the end of the first sample?

@wjlafrance: It would only not be required if it's at the end of the one-liner.

This can also be written as i<10&&m+=5,n-=3

@pavi2410 That doesn't parse correctly due to precedence issues.

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.

Just remembered this answer while reading More falsehoods programmers believe about time: “21. If you create two date objects right beside each other, they’ll represent the same time. (a fantastic Heisenbug generator)”.

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)

the getter/setter part was really helpful. thx

Actually, even better is an object method, if you only use it <= 2 times. On the other hand, arrow functions are far better at cutting down characters, as they serve almost the same purpose, and classes are rarely useful in golfed code.

if support is important arrow functions aren't supported in fx. ie11

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];

Or, you could do it like either of these: let a=[5,6,7,8,9,10,11,12].map(x=>x*Math.random()|0) or let a=Array(7).map((_,i)=>i*Math.random()|0+5), 36 or 42 bytes saved, respectively.

Is it possible to replace r(), or make it shorter?

r={valueOf:Math.random} That's just genius :D

@Isiah, well yeah, you can do that now :-D

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.

+1 for Creating repetitive strings using Array - hadn't thought about that one.

To create repetitive strings, in ES6 you can use str.repeat(count)

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

I'm using google chrome, and these are all giving undefined.

It must be very firefox specific then. Sorry for the inconvenience.

Why are these all special characters? Why not just use printable ASCII? (easier to type, more reliable, and only 1 byte for golfing)

This doesn't really work for Math because it doesn't have a .prototype attribute. Removing Math, though, I managed to golf this down to a 114-byte snippet that assigns them all to single-byte letters. You can find it here.

You can also golf my solution to 106 bytes at the expense of moving all these properties to the range À-ÿ, which is still 1 byte each in the ISO-8859-1 encoding (which JS supports). In Firefox 50, this unfortunately puts the .localeCompare method on ×, but that shouldn't usually be an issue. source

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)

(I've edited a) minor typo, but very clever! Note that this will only work on nested loops of same length (unless I'm wrong).

@CamiloMartin No, the loops don't need to be of equal length. The resulting number of iterations is i*j and the division/modulus operators retrieve the individual values of i and j.

@user113215 You're right, awesome! :) I've edited the answer to include an example.

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.

This can also be applied to any function that doesn't accept arguments.

Even when the function accepts arguments it can be useful, as in [1,2,3].join('',i=5) in cases where it saves a pair of braces.

@DocMax: You could use comma operator for that - i=5,[1,2,3].join().

@GlitchMr: I could, but it doesn't save any characters. I agree that most of the time that will be cleaner. I think there may still be cases where my ordering might save a char, although I cannot come up with one at the moment (and I may well be wrong).

@DocMax Only if you are taking advantage of ASI.

a="in "+[1,i,3].join('',i=5)+" minutes"
saves 2 chars compared to
a="in "+([1,i,3].join(),i=5)+" minutes"

@imma a=\in ${i=5,[1,i,3].join``} minutes`saves 3 chars froma="in "+[1,i,3].join('',i=5)+" minutes"`

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

Alternatively, you can simply use - instead of != for integers; For example, n!=1?a:b would be equivalent to n-1?a:b

For arrays, use Math.max(...a) though.

These wont work for negatives...

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.

+1, tired of using reduce and using up bytes

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

How does this work?

@Cowsquack String({}) gives "[object Object]".

wow. this is neat! thanks

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"]

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!

That's a genius use of this quirk. +1

Warning: these are not always equivalent: isNaN("string") returns true, whereas "string"!="string" returns false (obviously)

@Cyoce Good point, thanks! I edited my answer.

In many cases, you can even go for if(!x){, if you are detecting NaN explicitly.

More specifically, x!=x returns true only for NaN.

Casting x to number, +x!=+x, makes it equivalent to isNaN(x), yet still 2 characters shorter. Then, +"string"!=+"string" returns true.

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.

Or, even better, just use for loops. There's really no case where using a for loop results in larger code, as far as I have experienced.

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.

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)

And now this is standard modern JS so should be in https://codegolf.stackexchange.com/questions/37624/tips-for-golfing-in-ecmascript-6-and-above

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

Note that 0|x+1 simply adds 1 if the number you want to find the ceiling of is already an integer. A (mostly) safe alternative is 0|x+1-1e9, but this is only three bytes shorter.

@ETHproductions don't you mean 0|x+1-1e-9?

Oops, yeah. Thanks for pointing that out. (For some reason, I can't do @(your username)...)

Probably because my username chars are upside down :)

~~x also works for flooring, same length as your shorthand

For ceiling, x%1?-~x:x (9 characters) is a better alternative. However, like the flooring alternatives 0|x and ~~x, it only works for positive numbers.

I don't know if it's a known, safe and/or valid tip, but apparently for x <= 10 (including negative values), 10-(10-x|0) (11 bytes) seem to do a proper Ceiling. It saves 1 byte compared to Math.ceil(x) and could be useful if x is actually a whole expression that you can't afford to duplicate like in the x%1?-~x:x tip. Note : this tip transforms NaN into 10

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.

This can also be used to coalesce a string input into an integer, i.e., n=prompt()|0.

bitwise is also super fast compared to math.floor : http://jsperf.com/floor-vs-bitwise

@vsync: Weird.  I get math.floor to be about twice as fast as bitwise on Chrome 11.0.696.77.

very weird. for me they are both more or less same speeds & super fast in Chrome, but in FF the bitwise is a lot faster than Chrome, and Math.floor is terribly slow..almost should not be used I would say.

To keep the comments up-to-date, in current Fx they're both fast & about equal. Not that it's likely to be a bottleneck in the first place, compared to surrounding code...

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

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

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

You may not be able to do [x,]+y, but you can do [x,,]+y. Though it occurs to me that's the same amount of bytes as x+','+y, so nevermind.

you can save 1 byte:
f=x=>x?f(x-1)+" "+x:0 ==>
f=x=>x&&f(x-1)+" "+x

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.

Can you apply the same logic for ES6?

@SunnyPatel Yep, although it doesn't work out quite as well.

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.

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)

@ajax333221 void 0 (it isn't a function, but a keyword) is not a value, it simply returns undefined.

@CamiloMartin you are right, also I now see the point in this answer, however a must be either 1 or 0 for it to work

@ajax333221 Yes, actually the funny thing about code golfing to me is that most of the best tricks only work for that particular thing you're doing, and one feels so clever to find one of these corner cases with corner solutions :D By the way, you don't have to delete comments...

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)

it also changes the DOM method document.all to false but that isn't really relevant to code golf, lol

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.

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

I tried ""++ in the console earlier wondering if it would work, of course it has to be in a variable first. Thanks!

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;
// }

Arrow functions were already mentioned on Oct 13 '13 at 15:42. But that for..of is cool. Even shorter than for each..in.

The array comprehension syntax seems to be wrong. According to the documentation should be like in Python: b = [s(x) for (x of a)].

@manatwork The above samples run fine in Traceur's REPL

No idea about Traceur, but you mentioned ECMAScript and pointed to Mozilla documentation. And array comprehensions in none of them looks like you wrote it.

Array comprehensions were actually pulled midway through.

@Florent - consider deleting an answer which doesn't work?

@vsync I've removed the array comprehension part. Thanks.

Instead of writing true you can use !0.

Likewise, !1 for false.

Better yet, use 1 for true and 0 for false, unless you really need the literal values.

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

An additional alternative is 0|"0x"+a

2 to a power
If for some reason you need to calculate 2 to the nth power,
1<<n is shorter than Math.pow(2,n).
If you needed to calculate 2 to the n+1th 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)

and 2**nin ES6

@Cétia That’s ES7.

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

Nicely found, but var can be dropped here as well I guess. Secondly, I honestly don't think you'd add functions to Array.prototype when golfing.

var makes the counter a local and not global variable, and globals are considered bad

Oh well I don't know, but that was the reason of the downvote of my post here :)

Indeed globals are considered bad in general JavaScript programming.  But in code-golfing, it saves 4 characters which is never bad :-)  In code golfing, you're generally breaking a lot of readability and usability rules anyway to squeeze out the last character.

haha, then just compress your code then! your program might very well break if you use globals, so always ask yourself if you omit some var, would that effect something else far down the code

@vsync: It seems like you're missing the point of golfing. Golf code isn't supposed to be readable, flexible, reliable or even maintainable. It's not for practical application, but just for fun challenges. Coding standards don't matter at all - all that matters is making your code short.

Actually, reversing for loops saves 1 character, more in a few cases.

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.

That's not Javascript. That's a SPACE STATION!!!

ECMAScript 6 to the rescue! ->bar

ECMAScript 6: let foo = () => bar;, ironically shorter than the golfed code above.

ECMAScript 6: foo=_=>bar, even shorter.

that link is broken.

This doesn't work anymore.

Use if(~a.indexOf(b)) instead of if(a.indexOf(b)!=-1)

Also have a look at Array.prototype.includes as in 2017

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
                      ^^^^

Note that the last line l.sort(_=>someConstant) is implementation dependent. It works on Firefox, but not on V8 where this fails when there's >10 elements, or there's undefined values inside the array.

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.

Note that 0 in a and a[0] will fail for sparse arrays such as a = [,1,2]. Thus, !a.length is the most safe way to test for an empty array. When taking advantage of type casting to string, a==0 is another solution that directly returns a boolean value.

@TomasLangkaas but [0]==0 as well, so a==0 doesn't always work

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 falselike 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.

The standard string comparing sort will do just fine with this example

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

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

new could be dropped; the Array constructor called as a function does the same as if it's called as a constructor.  If the character to repeat is unimportant, it could be left out and it'll default to ",".

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)

Undefined is [][0]

@edc65 Thanks! Fixed.

5 bytes saved, undefined === []._

1/0 => Infinity

undefined is also probably [].a

(or any other 1ch identifier)

Or, if x is a variable that does not hold null or undefined, you can do x.a for undefined.

undefined without digits: [][[]]

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

note: I know this is obvious, but if we are going to insert elements too close to index 0, it might be good idea to write it like this a=[15,30];

You can also leave elements undefined (say if you want a 2 indexed version of the above -> a=[,,15,30];. Also, I think you're suggesting adding things to the array using a[a.length]=x, but a.push(x) is shorter...

Not a[a.length]. @Alconja is correct in suggesting a.push.

a.push(4) // returns index     a[a.length]=5 // returns new value     a=[...a,3] // returns array     [...a,3] // doesn't mutate

well it seems breaks and pre markdown isn't working :-(

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).

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

The question asks for tips which are somewhat specific to Javascript. The ternary operator is included in the tips for all languages.

Yes, but not all languages have the ternary operator, Pete... Besides, I put this in some six months ago...

Enough languages have it: there's no point mentioning it on lots of separate per-language tips pages. It's been on the generic tips for some 11.5 months; I've commented on it today because I commented on it in a new language tips page and the person who'd posted it  there mentioned that lots of other ones had it.

@PeterTaylor Sure, a lot of languages have a ternary operator... But how many have ternaries for top-level expressions or functions that return void? JS is nearly on a class of its own in that respect.

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.

Actually, it's also sometimes great for numbers if you want to not actually increment the number, where this has higher precedence than s+1

And multiplication.

s-1 will also coerce s to a number.

@Shaggy True. So will +s, s*n, -n, s/n, n-s, etc. where n is a Number (as opposed to a String).

Because ~ is a bitwise operator, it will treat NaN or undefined as 0, which may be useful in some cases.

@user202729 True, that is occasionally useful.

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 usef 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.

The var keyword is unnecessary. Same with the semicolons. n={valueOf:f} would be enough for that line.

Duly noted; edited

I had no idea this was possible in JS! But there's a typo in your last example; it should be __defineGetter__('f',function(){}) rather than __defineGetter('f',function(){})__.

@ETHproductions I guess I missed that. Fixed.

And it is even shorter in ES2015+: f={valueOf(){…}} or f={valueOf:_=>…}.

document.getElementById
This one's a HUGE byte-saver.
document.getElementById('a').innerHTML="foo"; //before
a.innerHTML="foo"; //after

If you are using jQuery, it should be $(a).html('foo')

How does this work?

@Annan See Do DOM tree elements with ids become global variables?.

@tsh This is unrelated to jQuery. $(a) is not necessary.

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)

Note: you don't need to initialize your variables while golfing. let a,b,c; would be unnecessary.

@Cyoce True, thanks for the tip!

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.

I use [[1,2],[3,4]].reduce(function(a,b){ return a.concat(b) })

@vsync: Isn't that longer?

yeah but if you need to use indexOf on the array later to find numbers in it...it won't find them if the array so made of strings, so this is more pure flattening

[].concat.apply([],[[1,2],[3,4]]) also works, but only flattens it one level. It's two characters longer, but works on any data type.

@Austin Hyde: Nice one, thanks.

Unless you just need to pass in an array, you can flatten it like this: [].concat([1,2],[3,4]), and if you need to pass in an array and you know the contents, this works too: [].concat(a[0],a[1]).

If you want to use ES6, you can use the spread operator and shorten that example to [...[1,2],...[3,4]]

It's terrible, and it only works with numbers, but: eval('['+[[1,2],[3,4,[5]]]+']') is quite short and does not convert the integers to strings.

You could also abuse implicit type casting to save a few bytes: ([[1,2],[3,4]]+"").split(",")

Or save some on the concat version by just doing [].concat([[1,2],[3,4]])

If you are using newer es stander, consider a.flat(1/0) which is 5 bytes shorter than (''+a).split , .

Treat strings like you do C Strings.
Given s="hello"
s[0]

is equivalent to
s.charAt(0)

and
s.split("")[0]

This is EcmaScript 5, but for code golf it's fine.

@xfix Yes, it's defined in EcmaScript 5, but Firefox has supported it from version 0.9.

Too bad JS doesn't support a[3]="d". Instead we have to use the obnoxiously long a=a.slice(0,3)+"d"+a.slice(4).

@ETHproductions try:  a=s.split('e').join('d');  And for this case (2 L's) -  s.split('ll').join('ld');

@yonatanmn That's a smart workaround, but I think it really only works when you know exactly what the string is.

Also, s.split``[0] or ...s[0]

what about '12345'.replace(/(..)./,'$1d')

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);)

Another way to get undefined easily is 1..a

Good catch - I fixed it

If you're restricted to non-alphanumeric characters, [].$ will also equal undefined

undefined without digits: [][[]]

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.

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

They all work in Firefox

@Toothbrush not the second tip. That only executes once before stopping.

You are right, but I'm sure it worked when I tried it.

You can pass additional arguments to setInterval which will be passed to the function argument when it is called. For example setInterval("f(x,y)",1e3) becomes setInterval(f,1e3,x,y) for a 3 byte saving.

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

I feel like most of these tips are already somewhere else in the thread (yes, this feels like a thread, not a question). Please remove the redundant ones.

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

Great for some restricted-source challenges. Only works on strings with a-zA-Z0-9 and no other chars.

+/ are allowed in the string as well. Also, you can sometimes use a .replace to add back in incompatible chars while still saving bytes.

One more thing: this doesn't work for strings of all lengths.

Oh, and JavaScript supports ISO-8859-1, so you can count every char in the compressed string as 1 byte.

Waaaait...... For real? I thought JS used UCS-2/UTF-16 for encoding. Is there an example of this working?

Here's what I did: 1. Create a .js file that contains some chars in the range 0xA0-0xFF and save it in the ISO-8859-1 encoding. 2. Create a .html file that calls the JS file via a <script src="myfile.js"> tag. 3. Open the HTML file in any browser. I'm not sure if this proves that JS supports ISO-8859-1, but that's the best method I can think of...

I verified it another way using Node.js. I took a JS file with ÿ somewhere in the source, converted it from UTF-8 into ISO-8859-1 using iconv -f UTF-8 -t ISO-8859-1, ran the file to make sure it worked, and verified the encoding with file -I.

Prefer Array#map() to Array#forEach()
Self-explanatory, a flat 4 bytes saved
a.forEach(function(e){/* ... */})
a.map(function(e){/* ... */})

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();

Nice! Can also be used for checking other types, such as numbers, n===+n, and booleans, b===!!b.

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

And, if you don't mind changing the original array, [a.pop()], at 9 characters.

[a.at(-1)] is 10 bytes without modify the array. It requires a more recently released interpreter though.

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]

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.

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

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).

a.length in b shorter

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)){/* ... */}

Don't get what's going on here but from your description +!!x is shorter and more concise.

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))))))

If you need to call a void-returning function repeatedly, it can be especially useful to return the function itself. For example, l=(x,y)=>c.lineTo(x,y);l(1,2);l(3,4);l(5,6);l(7,8) can be rephrased as l=(x,y)=>c.lineTo(x,y)||l;l(1,2)(3,4)(5,6)(7,8), saving 3 bytes. Example usage

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

You could use 0 and 1 instead of booleans. Again, semicolons are optional.

I know, these were just examples. Instead of true and false, there would most likely be expressions. I used variables to illustrate my point.

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.

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()))

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.

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

String to array

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

You can also use /0/.test(s)

Note that, if you need an actual boolean, and the pattern comes from an existing string with no regex special characters, x, then !!s.match(x) works (the argument is implicitly converted to a RegExp, and it returns falsy null  on failure), achieving the same effect as s.includes(x) while shaving off a character.

Length of deprecating array +1
1+X.length
X.push(0)   // 1 byte shorter

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.

+"10"+ +"5"===15

Note that the space is needed because the -- (decrement) operator takes precedence over subtraction. Also, @gion_13, what's the point? your solution has one extra character.

You can replace the space with a + (e.g. a-+-b)

In this case use a==c-b

Convert ints to strings by adding an empty string
For example:
39323+""

Returns:
"39323"

Update:
Adding [] works too

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=>{/* ... */})

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)

Can't see the point of all this. Concat works with multiple array parameters, does not need apply or spread. Example 1: a.concat(b,c,d,e,f)

Flatten: let f=l=>[].concat.apply(l.map(x=>Array.isArray(x)?f(x):x)) vs let f=l=>[...l.map(x=>Array.isArray(x)?f(x):x)]

Well...except my flatten shouldn't work. Here's a corrected version: let f=x=>[].concat(...l.map(x=>Array.isArray(x)?f(x):x)). The previous version would've done nothing.

It's still 6 bytes saved.

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

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)

Correct, but that is not JavaScript specific, is a generic tip added to Tips for golfing in  by Blazer more that 6 years ago.

Welcome to PPCG! As manatwork pointed out this tip has already be posted, so I recommend deleting it. But I hope you nevertheless stick around and answer some challenges. :)

4**.5;16**.5;100**.5 is even shorter.

Thanks for your replies. I will take a look at the general tips. Maybe I find something which has not yet been added ;) love code golfing though!

Square root hack
Use (x+2)**(1/2) instead of Math.sqrt(x+2).

a√b = a^(1/b) This can be applied to non-JavaScript languages.

Wouldn't it be shorter to use .5 instead of 1/2?

.5 would be shorter, but this way, it applies to 3rd, 4rth, etc.

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.

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.

Note that you can also use [].x, or, if you have a variable defined anywhere in the program/function (which is very likely), something like x.x, a.x, _.x, and so on, which is a byte shorter.

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.

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

Test Equality to Zero
Instead of
num==0

You can use
!num

This is very helpful in ternary expressions, you can replace num==0?result_a:result_b to num?result_b:result_a

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) === x1
Object(x)===x1

typeof x === 'undefined'
void x === x
x===[][0]2,3

x === undefined || x === null
x == null2
x==null

There exist no coercion functions for functions or symbols. You'll have to keep using typeof for them.
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

for undefined do [][] instead of void x

undefined could also be something like 1..a

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...

Or val&&.... Now, it is not equivalent to val == true. Example: 0 != true.

All these strings also evaluate to true: '0', ' ', ' 0', '0 '

The technical term for "truish" is "truthy".

Other falsy things: window.all and new Date("1970-01-01T00:00:00.000Z")

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)})

You don't ever need to initialize variables in code-golf unless you want them to be undefined, so getting rid of let saves 4 bytes off of the first line of both examples. 2. If you want to use .bind with customizable parameters, .bind is better: q=f.bind(0,x) vs. q=(..._)=>f(x,..._) (though if you only want one parameter, q=y=>f(x,y) is better).

@ETHproductions Updated

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"]

The first one [...'asdasd']

Did you copy and paste ? it, if done in the console and in code pen I get
["d", "a", ",", "d", "a", "d", ",", "s", "a"]
'da,dad,sa'.split``
(9) ["d", "a", ",", "d", "a", "d", ",", "s", "a"]

[...'da,dad,sa'] ...

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.

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)))

@manatwork So it is, I missed that when reviewing :/

You don't need a t, you can set properties of the array. only works with non-integers thoguh

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)

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.

You don't need the space in this instance: throw!0

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.

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.

If f returns 0 and 1, then f(0)|f(1) can be f(f(1))

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

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

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));

Instead of mapping the keys, you can do for(k in x) and, instead of the concatenation, you can do p[k]=[...p[k]||[],x[k]]. After wrapping that in {}s, it saves you 14 bytes. TIO

@Shaggy thanks :) - I don't know that tricks. May be you have also some suggestion to this?

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

console.log( 9**999===Infinity )

1/0 is a bit shorter

@James wow - it is not NaN (I don't know this)

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"-[]

This is covered by other answers already. The shortest version is +"12.52463".

@MartinEnder What about [restricted-source] questions? Maybe sometimes you can't use +.


text:
A BlackJack KOTH contest
BlackJack

As I had a blast working on the
  original KOTH challenge, I wanted to
  come up with another one. For me, the fun
  of these AI challenges is in refining
  a comparatively simple bot which plays
  a very simple game subtly. Due to the
  probabilistic nature of card games, I
  think that blackjack could be an
  interesting KOTH game just like TPD.

All the rules are derived from this website's description of BlackJack with shoes
Rules Regarding Cards & the Deck

Bots play at tables of four (4) competitors and one (1) dealer
One (1) shoe (a shuffled deck) is shared by all players and the dealer until it is exhausted, at which point a new randomly shuffled deck will be added and play will continue. The bots ARE NOT (at present) NOTIFIED of the addition of this new deck. Such notification may be added if lack of this feature causes sufficient distress/trouble.
There is a buy-in of 10 per round, and cards are free
Perfect/ideal hand has a score of 21
All face cards have a value of 10
All numeric cards are worth their number
Aces are worth 11 or 1. this will be dealt with automatically by the framework, not the bots.
As per the rules, all players' cards are dealt face-up and are visible. One of the dealer's cards is face-down and the other is face-up.

Scoring

Scores in excess of 21 which use an ace as 11 force the ace to reduce in value to 1
scores in excess of 21 which cannot be coerced below the threshold of 21 "bust" the bot

The Dealer

The dealer draws until he busts, or excedes a score of 17 at which point he is forced to stand

Betting and Chips

At the start of each round, a buy-in of 10 is charged, so there is a minimum stake of 10, and a minimum bet of 1. NOTE - the bet is the absolute value of the bet argument, so don't bother trying negative bets.
Bots which cannot afford the buy-in are removed from the contest
When making bets, bots cannot bet more than the chips they have
If the bet is possible, the chips bet are emmidiately removed from the bot and added to the stake
Winning a bet gives the bot 2x chips bet. However because the bet is subtracted from the bot's chips, the bot breaks even and then wins 1x the bet.
Bots win bets only if their score is greater than that of the dealer

Gameplay Breakdown
One Hand

When the game starts, each player is
iteratively dealt one card, and has
the $10 buy-in fee/minimum bet
subtracted from their chips.
The dealer draws
A second pass is made, and another card is dealt to all players.
The dealer draws
Then (in the same order as they were dealt to) each bot is executed as described in the "Programmer's Interface" section and must make a move or stand. Betting is considered a move. NOTE THAT BETTING DOES NOT AFFECT BOTS' ABILITY TO MAKE FURTHER MOVES. It is very possible to bet and then draw a card, and it is possible to draw multiple cards and them bet before standing.
When all the bots have busted or stood, the dealer plays to its threshold of 17
The scores of the bots are then compared to that of the dealer, bets are won and lost

One Round
Is considered to constitute five (5) hands. In-between hands, the list of contestants is sorted to remove players and then further processed to ensure that all the bots play the same number of hands (a provision for the fact that the number of entries will not devide evenly among four-bot tables).
Programmer's Interface and Legal Moves
As documented in the CardShark file:
#   DOCUMENTATION
#       INPUT SPECIFICATION
#          $ ./foo.bar <hand-score> <hand> <visible cards> <stake> <chips>
#          <hand-score>     is the present integer value of the player's hand.
#          <hand>           is a space-free string of the characters [1-9],A,J,Q,K
#          <visible cards>  every dealt card on the table. when new shoes are brought
#                           into play, cards drawn therefrom are simply added to this list
#                           NOTE: the first TWO (2) cards in this list belong to the dealer.
#                             one however will be "hidden" by a "#". the other is visible.
#                           !!! THE LIST IS CLEARED AT THE END OF HANDS, NOT SHOES !!!
#          <stake>          the  number of chips which the bot has bet this hand
#          <chips>          the number of chips which the bot has
#       SAMPLE INPUT
#          $ ./foo.bar 21 KJA KQKJA3592A 25 145
#
#       OUTPUT SPECIFICATION
#          "H"|"S"|"D"|"B"  (no quotes in output)
#          "H"              HIT - deal a card
#          "S"              STAND - the dealer's turn
#          "D"              DOUBLEDOWN - double the bet, take one card. FIRST MOVE ONLY
#          "B 15"           BET - raises the bot's stakes by $15.

As (now) documented in the Cards file:
#       class CARD
#           card is a container for representing paper playing cards in
#           otherwise fairly functional programming.
#           letter()
#               gets the letter used to identify the card in a string
#               LETTER MAPPINGS
#                   Ace     :   'A'
#                   Two     :   '2'
#                   Three   :   '3'
#                   Four    :   '4'
#                   Five    :   '5'
#                   Six     :   '6'
#                   Seven   :   '7'
#                   Eight   :   '8'
#                   Nine    :   '9'
#                   Ten     :   'T'
#                   Jack    :   'J'
#                   Queen   :   'Q'
#                   King    :   'K'
#                   "Hidden":   '#'

The source code for the scoring system is HERE
Sample Bots
Lim 17
#!/usr/bin/env python
import sys
s = sys.argv
if int(s[1]) < 17:
    print "H"
else:
    print "S"

Entry Languages
At present, Java, c/c++, Python and Lisp are supported. A reasonable effort will be made to include submissions in other languages, but remember that the final contest will be run on a Linux box.
Winner Selection
The winner would be the author of the bot which consistently accrued the most chips over a yet-to-be determined number of tables and rounds. The winner will be announced on June 3rd, but the announcement may be delayed if there are still submissions coming in. Contest extended indefinitely.

Question: does visible-cards include those in the players own hand?

Second question: do we know how many cards have been dealt that we can't see?

Answer to #1 - yes; Answer to #2 - the way this engine is implemented, there are no hidden cards. visible-cards is every card which has been dealt from every shoe consumed during the current round. visible-cards returns is cleared not on new shoes (because part of the old shoe is probably still in play) but is instead cleared on round termination. This is an architecture choice I made for simplicity, which can be revised if you find the lack of hidden cards problematic.

Update: check the rules link. The engine now implements hidden cards, but the only hidden card at present is one of the dealer's base cards.

How can bots distinguish which visible card is the dealers?

At present, the engine doesn't provide any assurance of card position in the dealing stack due to the dynamic size of tables (capped at 4). However, I'm going to take this as a feature request. Would it be more appropriate to give the dealers' cards a static position, or to change the input specification to explicitly include a dedicated separate argument? They're equally easy fixes.

Updated the spec, the first two cards in  now belong to the dealer, although one of the two will be "hidden" with a hash symbol.

BlackJackDavey
Boring, old fashioned c. Should compiler under ANSI or c99.
/* BlackJackDavey
 *
 * A entry for
 * http://codegolf.stackexchange.com/questions/2698/a-blackjack-koth-contest
 * copyright 2011
 *
 * Currently expects a slightly extended version of the spec. Two
 * expected changes:
 * - Tens will be represented as 'T'
 * - The visible card string will include '#' for those cards whose
 *     *backs* we can see (slight improvement in card counting technique)
 *
 * No disaster if neither feature is present, just sligtly degraded
 * performance.
 */
#include <stdio.h>
#include <string.h>

/* A full deck has a total value of 4*( (11*5) + (3*10) + ace ) where
 * ace is 11 or according to our need.
 **/
int fullWeight(const int current){
  int ace = (current>10) ? 1 : 11;
  return 4 * ( 11*5 + 3*10 + ace);
}
/* Return the value of a particular card in the context of our
 * current score
 */
int cardWeight(const char c, const int current){
 switch (c) {
 case '1': case '2': case '3': case '4': case '5':
 case '6': case '7': case '8': case '9':
   return (c - '0');
 case 'T': case 'J': case 'Q': case 'K':
   return 10;
 case 'A':
   return current>10 ? 1 : 11;
 }
 return 0;
}
/* returns the mean card *value* to be expected from the deck
 *
 * Works by computing the currently unknown value and diviing by the
 * number of remaining cards
 */
float weight(const char*known, const int current){
  int weight = fullWeight(current);
  int count=52;
  int uCount=0;
  const char*p=known;
  while (*p != '\0') {
    if (*p == '#') { /* Here '#' is a stand in for the back of a card */
      uCount++;
    } else {
      weight -= cardWeight(*p,current);
    }
    count--;
    p++;
    if ( count==0 && *p != '\0') {
      count += 52;
      weight += fullWeight(current);
    }
  }
  return (1.0 * weight)/(count+uCount);
}

int main(int argc, char*argv[]){
  int score=atoi(argv[1]);
  const char*hand=argv[2];
  const char*visible=argv[3];
  int stake=atoi(argv[4]);
  int chips=atoi(argv[5]);

  /* If current stake is less than 10, bet all the rest because a loss
     does not leave us enough to continue */
  if (chips < 10 && chips > 0) {
    printf("B %d\n",chips);
    return 0;
  }
  /* First round stategy differs from the rest of the game */
  if (strlen(hand)==2 && stake==10) {
    switch(score){
    case 10:
    case 11: /* Double down on particularly strong hands */
      if (chips >= 10) {
    printf("D\n");
    return 0;
      }
      break;
    default:
      break;
    };
  }
  /* In future rounds or when first round spcialls don't apply it is
     all about maximizing chance of getting a high score */
  if ((score + weight(visible,score)) <= 21) {
    /* if the oods are good for getting away with it, hit */
    printf("H\n");
    return 0;
  }
  /* Here odd are we bust if we hit, but if we are too low, the dealer
     probably makes it.*/
  printf("%c\n", score>14 ? 'S' : 'H');
  return 0;
}

The strategy here is documented in the comments, but is very straight ahead. Additional bets are made in only two cases (not enough stake for the next round, or double down), and this may need to change.
The game differs some from the guides offered for casino gamblers in that there is no specific information about the dealer's showing card (or can we could on that being the last entry in visible?), so some of the magic numbers are guesses.
May need some modest diddling depending on the answer to two questions in the comments.
Name from the game, my first name, and the old folk ballad.

The ten card IS represented by the T character. Will update the contest post with the list.

Linear Bet
#!/usr/bin/env python
from __future__ import division
import sys
s = sys.argv

c=150    # chip modifier
f=15     # stand score

if int(s[1]) < f:
    print "H"
else:
    if int(s[4]) == 10:
        print "B", (int(s[1])/21)*c
    else:
        print "S"

This bot is a modification of the 17 strategy. This bot draws until it exceeds a score of 15 (f) and then bets int(c*(score/21)) chips. This way the bot will bet aggressively wherever possible.

 JustAnotherCardCounter, Python
import sys
s = sys.argv

if s[0] <= 11 and len(s[1]) == 2:
  print("D") # another card is always safe here
elif s[0] <= 11:
  print("H") # same
elif s[0] == 21:
  print("B ", s[4]) # can't lose, so go all out
  print("S") # and wait for the cash to roll in
cardset = s[2]
prevcardset = ""
cards = {
"A": 0,
"2": 0,
"3": 0,
"4": 0,
"5": 0,
"6": 0,
"7": 0,
"8": 0,
"9": 0,
"T": 0,
"J": 0,
"Q": 0,
"K": 0}
# here i go, cheating fate (again)
for card in "A23456789TJQK":
  cards[card] += (cardset.count(card) - prevcardset.count(card))
counts = list(cards.values()) # get the values
if (counts[:20 - s[0]] * 4/3) >= counts[20 - s[0]: # here's where the magic happens
  print("H")
else:
  if s[4] * (1 - s[0]/21) < 10:
    print("B ", s[4]) #we'll go out on a loss regardless, might as well try and get more when we win
    print("S")
  else:
    print("B ", (s[4]*(s[0]/21)) # we can afford to stay low, so we keep ourselves in the game.
    print("S")

This bot does what it says on the tin. Effectively a combination of LinearBet and some of BlackJackDavey.
Probably won't do well.
Feel free to tell me where this breaks (if it does).

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes