Skip to content

Instantly share code, notes, and snippets.

@herberthamaral
Created February 24, 2012 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save herberthamaral/1900797 to your computer and use it in GitHub Desktop.
Save herberthamaral/1900797 to your computer and use it in GitHub Desktop.
wtf.js
console.log(999999999999999)
//999999999999999
console.log(9999999999999999)
//10000000000000000 ==> WTF??
console.log(9999999999999999+1)
//10000000000000000
console.log(9999999999999999+2)
//10000000000000002 ==> WTF^2??
console.log(false || 'http')
//http
console.log(true || 'http')
//true
@elvisgs
Copy link

elvisgs commented Feb 24, 2012

Nos exemplos 2 a 4 parece ser overflow, mas realmente não faz sentido mesmo considerando que o maior número possível em js é 2^53.

A explicação dos 2 últimos exemplos é short-circuit evaluation; é bastante usado com optional parameters/settings.

function myFunc(param1, param2, settings) {
  var defaultSettings = { ... };

  param1 = param1 || 'foo';
  param2 = param2 || 'bar';
  settings = $.extend(defaultSettings, settings || {});
}

@herberthamaral
Copy link
Author

O estranho do short-circuit é que ele se comporta de forma diferente mesmo com variáveis do mesmo "tipo" (bool).

@elvisgs
Copy link

elvisgs commented Feb 24, 2012

É um dos perigos de se usar short-circuit em js, pq é a característica de truthy/falsy do valor que é considerada.

// suponha que uma string vazia seja um valor válido como parâmetro
function func(param) {
  param = param || 'noop';
  console.log(param);
}

func(''); // 'noop'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment