Skip to content

Instantly share code, notes, and snippets.

@YannPl
Last active August 29, 2015 14:10
Show Gist options
  • Select an option

  • Save YannPl/07ae7d6f8434e51089f8 to your computer and use it in GitHub Desktop.

Select an option

Save YannPl/07ae7d6f8434e51089f8 to your computer and use it in GitHub Desktop.
Type check in JavaScript
typeof []; // object
typeof {}; // object
typeof ''; // string
typeof new Date() // object
typeof 1; // number
typeof function () {}; // function
typeof /test/i; // object
typeof true; // boolean
typeof null; // object
typeof undefined; // undefined
// OTHER EXAMPLES FROM MOZILLA DOCS
// Pour les nombres
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // Bien que littéralement ce soit "Not-A-Number"...
typeof Number(1) === 'number'; // cette forme ne doit pas être utilisée !
// Les chaînes de caractères
typeof "" === 'string';
typeof "bla" === 'string';
typeof (typeof 1) === 'string'; // typeof renvoie toujours une chaîne
typeof String("abc") === 'string'; // cette forme ne doit pas être utilisée !
// Les booléens
typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(true) === 'boolean'; // cette forme ne doit pas être utilisée !
// Les symboles
typeof Symbol() === 'symbol'
typeof Symbol('foo') === 'symbol'
typeof Symbol.iterator === 'symbol'
// Indéfini
typeof undefined === 'undefined';
typeof blabla === 'undefined'; // pour une variable indéfinie
// Les objets
typeof {a:1} === 'object';
// Utiliser la méthode Array.isArray ou Object.prototype.toString.call
// afin de différencier les objets des tableaux
typeof [1, 2, 4] === 'object';
typeof new Date() === 'object';
// Les expressions suivantes sont source de confusion
// à ne pas utiliser sous cette forme
typeof new Boolean(true) === 'object';
typeof new Number(1) === 'object';
typeof new String("abc") === 'object';
// Les fonctions
typeof function(){} === 'function';
typeof class C {} === 'function';
typeof Math.sin === 'function';
typeof /s/ === 'function'; // Chrome 1 à 12 : Non conforme à ECMAScript 5.1
typeof /s/ === 'object'; // À partir de Firefox 5 : Conforme à ECMAScript 5.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment