IsNaN() - JavaScript | MDN
Maybe your like
- Skip to main content
- Skip to search
Cette page a été traduite à partir de l'anglais par la communauté. Vous pouvez contribuer en rejoignant la communauté francophone sur MDN Web Docs.
View in English Always switch to English
isNaN() Baseline Widely availableCette fonctionnalité est bien établie et fonctionne sur de nombreux appareils et versions de navigateurs. Elle est disponible sur tous les navigateurs depuis juillet 2015.
- Learn more
- See full compatibility
- Report feedback
La fonction isNaN() permet de déterminer si une valeur est NaN. On notera que cette fonction utilise des règles de conversion différentes de Number.isNaN(), définie avec ECMAScript 2015 (ES6).
Dans cet article
- Exemple interactif
- Syntaxe
- Description
- Exemples
- Spécifications
- Compatibilité des navigateurs
- Voir aussi
Exemple interactif
function milliseconds(x) { if (isNaN(x)) { return "Not a Number!"; } return x * 1000; } console.log(milliseconds("100F")); // Expected output: "Not a Number!" console.log(milliseconds("0.0314E+2")); // Expected output: 3140Syntaxe
jsisNaN(valeurÀTester);Paramètres
valeurÀTesterLa valeur dont on souhaite déterminer si elle est NaN.
Valeur de retour
true si la valeur fournie vaut NaN, sinon, la méthode renverra false.
Description
La nécessité d'avoir isNaN()
À la différence des autres valeurs JavaScript, il est impossible d'utiliser les opérateurs d'égalité faible et stricte (== et ===) afin de déterminer si une valeur est ou n'est pas réellement NaN. En effet NaN == NaN et NaN === NaN renvoient false tous les deux. C'est pour cela qu'il est nécessaire d'avoir la fonction isNaN().
Les origines de NaN
La valeur NaN est générée lorsqu'une opération arithmétique résulte en une valeur indéfinie ou non représentable. De telles valeurs ne représentent pas nécessairement des dépassements de condition. NaN peut également être le résultat d'une conversion numérique pour les valeurs qui n'ont pas de valeurs numériques correspondantes (par exemple lorsqu'on souhaite convertir la chaîne "toto" en un nombre).
Par exemple, lorsqu'on divise zéro par zéro, on obtient NaN. En revanche, lorsqu'on divise d'autres nombres par zéro, on n'obtient pas ce résultat.
Comportement étrange de isNaN()
Depuis les premières spécifications pour isNaN(), son comportement sur les arguments non-numériques a toujours été source de confusion. Lorsque l'argument passé à la fonction n'est pas du type Number, la valeur est d'abord convertie en une valeur du type Number. La valeur résultante est ensuite utilisée lors du test afin de déterminer si c'est NaN. Ainsi pour valeurs non numériques qui sont converties en une valeur non-NaN numérique (notamment la chaîne vide, les valeurs booléennes qui donnent zéro ou un), la fonction renverra false, ce qui pourrait être inattendu (en effet, la chaîne vide n'est pas un nombre). Ici, la confusion provient du fait que « not a number » a un sens particulier pour les valeurs numériques représentées selon IEEE-754. Cette fonction doit plutôt être vue comme la réponse à la question « est-ce que cette valeur, lorsqu'elle est convertie en une valeur numérique, correspond à la valeur IEEE-754 "Not A Number" ? ».
La version ECMAScript ES2015 ajoute la méthode Number.isNaN(). Number.isNaN(x) permettra de tester de façon plus fiable si x vaut NaN ou non. Si on ne dispose pas de cette méthode, on peut également utiliser l'expression (x != x) afin de tester de façon plus certaine si x vaut NaN ou non (en effet le résultat de cette expression n'aura pas les faux positifs de isNaN). Sous cet angle, isNaN() peut être vu comme :
jsvar isNaN = function (valeur) { return Number.isNaN(Number(valeur)); };Ou encore, en utilisant le fait que NaN est la seule valeur différente d'elle-même :
jsvar isNaN = function (valeur) { var n = Number(valeur); return n !== n; };NaN est « empoisonné »
Cette fonction peut être utilisée afin de déterminer si la valeur courante peut faire partie d'une expression arithmétique. En effet, si un des composants d'une expression arithmétique vaut NaN, le résultat de l'expression sera NaN également (on dit alors que NaN « empoisonne » l'expression). La méthode isNaN() permet alors de vérifier, avant de construire une expression, que les valeurs utilisées n'empoisonneront pas l'expression.
On peut par exemple construire une fonction dont on souhaite qu'elle incrémente l'argument et que la valeur qu'elle renvoie ne puisse pas être NaN. Le code de cette fonction pourrait être :
jsfunction incrément(x) { if (isNaN(x)) { x = 0; } return x + 1; } // En utilisant des notations raccourcies, // on pourrait écrire une fonction équivalente function incrémentCourt(x) { isNaN(x) ? 1 : x + 1; } incrément("blabla"); // 1 incrément(1); // 2 incrément(NaN); // 1Exemples
jsisNaN(NaN); // true isNaN(undefined); // true isNaN({}); // true isNaN(true); // false isNaN(null); // false isNaN(37); // false // strings isNaN("37"); // false : "37" est converti vers le nombre 37 qui n'est pas NaN isNaN("37.37"); // false : "37.37" est converti vers le nombre 37.37 qui n'est pas NaN isNaN("37,25"); // true : la virgule n'est pas considérée comme un séparateur décimal isNaN("123ABC"); // true : "123ABC" converti en 123 par parseInt mais en NaN par Number isNaN(""); // false : la chaîne vide est convertie en 0 qui n'est pas NaN isNaN(" "); // false : une chaîne de blancs est convertie en 0 qui n'est pas NaN // dates isNaN(new Date()); // false isNaN(new Date().toString()); // true // Voici le résultat « faux-positif » qui fait que isNaN n'est pas entièrement fiable isNaN("blabla"); // true : "blabla" est converti en un nombre // Si on souhaite convertir cette valeur en nombre, cela échoue // et on obtient NaNSpécifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification# sec-isnan-number |
Compatibilité des navigateurs
Voir aussi
- NaN
- Number.isNaN()
Help improve MDN
Was this page helpful to you? Yes No Learn how to contributeCette page a été modifiée le 2 déc. 2025 par les contributeurs du MDN.
View this page on GitHub • Report a problem with this content Filter sidebar- JavaScript
- Tutoriels
- Guide JavaScript
- Introduction
- Types et grammaire
- Contrôle du flux et gestion des erreurs
- Boucles et itération
- Fonctions
- Expressions et opérateurs
- Numbers and strings
- Representing dates & times
- Expressions rationnelles
- Collections indexées
- Collections avec clés
- Manipuler les objets
- Using classes
- Utiliser les promesses
- Tableaux typés en JavaScript
- Itérateurs et générateurs
- Resource management
- Internationalization
- Modules JavaScript
- Intermédiaire
- Language overview
- Structures de données en JavaScript
- Différents tests d'égalité
- Rattachement des propriétés
- Fermetures (closures)
- Avancé
- L'héritage et la chaîne de prototypes
- Métaprogrammation
- Gestion de la mémoire
- Références
- Objets natifs
- AggregateError
- Array
- ArrayBuffer
- AsyncDisposableStack
- AsyncFunction
- AsyncGenerator
- AsyncGeneratorFunction
- AsyncIterator
- Atomics
- BigInt
- BigInt64Array
- BigUint64Array
- Boolean
- DataView
- Date
- decodeURI()
- decodeURIComponent()
- DisposableStack
- encodeURI()
- encodeURIComponent()
- Error
- escape() Obsolète
- eval()
- EvalError
- FinalizationRegistry
- Float16Array
- Float32Array
- Float64Array
- Function
- Generator
- GeneratorFunction
- globalThis
- Infinity
- Int8Array
- Int16Array
- Int32Array
- InternalError Non standard
- Intl
- isFinite()
- isNaN()
- Iterator
- JSON
- Map
- Math
- NaN
- Number
- Object
- parseFloat()
- parseInt()
- Promise
- Proxy
- RangeError
- ReferenceError
- Reflect
- RegExp
- Set
- SharedArrayBuffer
- String
- SuppressedError
- Symbol
- SyntaxError
- Temporal
- TypedArray
- TypeError
- Uint8Array
- Uint8ClampedArray
- Uint16Array
- Uint32Array
- undefined
- unescape() Obsolète
- URIError
- WeakMap
- WeakRef
- WeakSet
- Expressions et opérateurs
- Addition (+)
- Affectation après addition (+=)
- Assignement (=)
- Expression async function
- Expression async function*
- await
- ET binaire (&)
- Affectation après ET binaire (&=)
- NON binaire (~)
- OU binaire (|)
- Affectation après OU binaire (|=)
- OU exclusif binaire (^)
- Affectation après OU exclusif binaire (^=)
- class
- L'opérateur virgule
- L'opérateur conditionnel
- Décrémentation (--)
- L'opérateur delete
- Affecter par décomposition
- Division (/)
- Affectation après division (/=)
- Égalité (==)
- Exponentiation (**)
- Affectation après exponentiation (**=)
- L'opérateur function
- Expression function*
- Supérieur strict (>)
- Supérieur ou égal (>=)
- Opérateur de groupement
- import.meta
- import.meta.resolve()
- import
- L'opérateur in
- Incrémentation (++)
- Inégalité (!=)
- instanceof
- Décalage binaire à gauche (<<)
- Affectation après décalage à gauche (<<=)
- Inférieur strict (<)
- Inférieur ou égal (<=)
- ET logique (&&)
- Affectation après ET logique (&&=)
- NON logique (!)
- OU logique (||)
- Affectation après OU logique (||=)
- Multiplication (*)
- Affectation après multiplication (*=)
- L'opérateur new
- new.target
- null
- Affectation après coalescence des nuls (??=)
- Opérateur de coalescence des nuls (Nullish coalescing operator)
- Initialisateur d'objet
- Précédence des opérateurs
- Chaînage optionnel (optional chaining)
- Accesseurs de propriétés
- Reste (%)
- Affectation après reste (%=)
- Décalage binaire à droite (>>)
- Affectation après décalage à droite (>>=)
- Syntaxe de décomposition
- Égalité stricte (===)
- Inégalité stricte (!==)
- Soustraction (-)
- Affectation après soustraction (-=)
- super
- L'opérateur this
- L'opérateur typeof
- Négation unaire (-)
- Plus unaire (+)
- Décalage binaire à droite non-signé (>>>)
- Affectation après décalage à droite non signé (>>>=)
- L'opérateur void
- yield
- yield*
- Instructions et déclarations
- async function
- async function*
- await using
- bloc
- break
- class
- const
- continue
- debugger
- do...while
- vide
- export
- Expression statement
- for
- for await...of
- for...in
- for...of
- function
- function*
- if…else
- import
- Import attributes
- label
- let
- return
- switch
- throw
- try...catch
- using
- var
- while
- with Obsolète
- Fonctions
- Fonctions fléchées
- Valeurs par défaut des arguments
- L'opérateur get
- Définir une méthode
- Paramètres du reste (Rest parameters)
- L'opérateur set
- arguments
- arguments[@@iterator]()
- callee Obsolète
- length
- Classes
- constructor
- extends
- Propriétés privées
- Champs de classe publics
- static
- Static initialization blocks
- Expressions rationnelles
- Backreference: \1, \2
- Capturing group: (...)
- Character class escape: \d, \D, \w, \W, \s, \S
- Character class: [...], [^...]
- Character escape: \n, \u{...}
- Disjunction: |
- Input boundary assertion: ^, $
- Literal character: a, b
- Lookahead assertion: (?=...), (?!...)
- Lookbehind assertion: (?<=...), (?<!...)
- Modifier: (?ims-ims:...)
- Named backreference: \k<name>
- Named capturing group: (?<name>...)
- Non-capturing group: (?:...)
- Quantifier: *, +, ?, {n}, {n,}, {n,m}
- Échappement des propriétés Unicode
- Wildcard: .
- Word boundary assertion: \b, \B
- Erreurs
- AggregateError: No Promise in Promise.any was resolved
- Error: Permission denied to access property "x"
- InternalError: too much recursion
- RangeError: argument is not a valid code point
- RangeError: BigInt division by zero
- RangeError: BigInt negative exponent
- RangeError: form must be one of 'NFC', 'NFD', 'NFKC', or 'NFKD'
- RangeError: invalid array length
- RangeError: invalid date
- RangeError: precision is out of range
- RangeError: radix must be an integer
- RangeError: repeat count must be less than infinity
- RangeError: repeat count must be non-negative
- RangeError: x can't be converted to BigInt because it isn't an integer
- ReferenceError: "x" is not defined
- ReferenceError: assignment to undeclared variable "x"
- ReferenceError: can't access lexical declaration 'X' before initialization
- ReferenceError: must call super constructor before using 'this' in derived class constructor
- ReferenceError: super() called twice in derived class constructor
- SyntaxError: 'arguments'/'eval' can't be defined or assigned to in strict mode code
- SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
- SyntaxError: "use strict" not allowed in function with "x" parameter
- SyntaxError: "x" is a reserved identifier
- SyntaxError: \ at end of pattern
- SyntaxError: a declaration in the head of a for-of loop can't have an initializer
- SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
- SyntaxError: arguments is not valid in fields
- SyntaxError: await is only valid in async functions, async generators and modules
- SyntaxError: await/yield expression can't be used in parameter
- SyntaxError: cannot use `??` unparenthesized within `||` and `&&` expressions
- SyntaxError: character class escape cannot be used in class range in regular expression
- SyntaxError: continue must be inside loop
- SyntaxError: duplicate capture group name in regular expression
- SyntaxError: duplicate formal argument x
- SyntaxError: for-in loop head declarations may not have initializers
- SyntaxError: function statement requires a name
- SyntaxError: functions cannot be labelled
- SyntaxError: getter and setter for private name #x should either be both static or non-static
- SyntaxError: getter functions must have no arguments
- SyntaxError: identifier starts immediately after numeric literal
- SyntaxError: illegal character
- SyntaxError: import declarations may only appear at top level of a module
- SyntaxError: incomplete quantifier in regular expression
- ReferenceError: invalid assignment left-hand side
- SyntaxError: invalid BigInt syntax
- SyntaxError: invalid capture group name in regular expression
- SyntaxError: invalid character in class in regular expression
- SyntaxError: invalid class set operation in regular expression
- SyntaxError: invalid decimal escape in regular expression
- SyntaxError: invalid identity escape in regular expression
- SyntaxError: invalid named capture reference in regular expression
- SyntaxError: invalid property name in regular expression
- SyntaxError: invalid range in character class
- SyntaxError: invalid regexp group
- SyntaxError: invalid regular expression flag "x"
- SyntaxError: invalid unicode escape in regular expression
- SyntaxError: JSON.parse: bad parsing
- SyntaxError: label not found
- SyntaxError: missing : after property id
- SyntaxError: missing ) after argument list
- SyntaxError: missing ) after condition
- SyntaxError: missing ] after element list
- SyntaxError: missing } after function body
- SyntaxError: missing } after property list
- SyntaxError: missing = in const declaration
- SyntaxError: missing formal parameter
- SyntaxError: missing name after . operator
- SyntaxError: missing variable name
- SyntaxError: negated character class with strings in regular expression
- SyntaxError: new keyword cannot be used with an optional chain
- SyntaxError: nothing to repeat
- SyntaxError: numbers out of order in {} quantifier.
- SyntaxError: octal escape sequences can't be used in untagged template literals or in strict mode code
- SyntaxError: parameter after rest parameter
- SyntaxError: private fields can't be deleted
- SyntaxError: property name __proto__ appears more than once in object literal
- SyntaxError: raw bracket is not allowed in regular expression with unicode flag
- SyntaxError: redeclaration of formal parameter "x"
- SyntaxError: reference to undeclared private field or method #x
- SyntaxError: rest parameter may not have a default
- SyntaxError: return not in function
- SyntaxError: setter functions must have one argument
- SyntaxError: unterminated string literal
- SyntaxError: super() is only valid in derived class constructors
- SyntaxError: tagged template cannot be used with optional chain
- SyntaxError: Unexpected '#' used outside of class body
- SyntaxError: Unexpected token
- SyntaxError: unlabeled break must be inside loop or switch
- SyntaxError: unparenthesized unary expression can't appear on the left-hand side of '**'
- SyntaxError: use of super property/member accesses only valid within methods or eval code within methods
- SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
- ReferenceError: deprecated caller or arguments usage
- TypeError: 'x' is not iterable
- TypeError: "x" is (not) "y"
- TypeError: "x" is not a constructor
- TypeError: "x" is not a function
- TypeError: "x" is not a non-null object
- TypeError: "x" is read-only
- TypeError: already executing generator
- TypeError: BigInt value can't be serialized in JSON
- TypeError: calling a builtin X constructor without new is forbidden
- TypeError: can't access/set private field or method: object is not the right class
- TypeError: can't assign to property "x" on "y": not an object
- TypeError: can't convert BigInt to number
- TypeError: can't convert x to BigInt
- TypeError: can't define property "x": "obj" is not extensible
- TypeError: can't delete non-configurable array element
- TypeError: can't redefine non-configurable property "x"
- TypeError: can't set prototype of this object
- TypeError: can't set prototype: it would cause a prototype chain cycle
- TypeError: invalid 'in' operand "x"
- TypeError: class constructors must be invoked with 'new'
- TypeError: cyclic object value
- TypeError: derived class constructor returned invalid value x
- TypeError: getting private setter-only property
- TypeError: Initializing an object twice is an error with private fields/methods
- TypeError: invalid 'instanceof' operand 'x'
- TypeError: invalid Array.prototype.sort argument
- TypeError: invalid assignment to const "x"
- TypeError: Iterator/AsyncIterator constructor can't be used directly
- TypeError: matchAll/replaceAll must be called with a global RegExp
- TypeError: More arguments needed
- TypeError: "x" has no properties
- TypeError: property "x" is non-configurable and can't be deleted
- TypeError: Reduce of empty array with no initial value
- TypeError: setting a property that has only a getter
- TypeError: WeakSet key/WeakMap value 'x' must be an object or an unregistered symbol
- TypeError: X.prototype.y called on incompatible type
- URIError: malformed URI sequence
- Warning: -file- is being assigned a //# sourceMappingURL, but already has one
- Warning: unreachable code after return statement
- Divers
- Aperçu des technologies JavaScript
- Execution model
- Grammaire lexicale
- Protocoles d'itération
- Mode strict
- Gabarits de chaînes de caractères
- Virgules finales
- Fonctionnalités dépréciées
Tag » Arduino Isnan Function
-
Arduino: Read Temperature From DHT11 Module - C# Corner
-
Isnan() | Cộng đồng Arduino Việt Nam
-
Using Isnan - Programming Questions - Arduino Forum
-
Simple Code Question - Programming Questions - Arduino Forum
-
Problems With Isnan And Serial - Arduino Forum
-
Isnan - C++ Reference
-
NaN, IsNaN() & NaN() | Codementor
-
[Solved] Error: 'isnan' Was Not Declared In This Scope Isnan(n)
-
Arduino - Math Library
-
[SOLVED] DHT11/DHT22 - Failed To Read From DHT Sensor
-
DHT11/DHT22 Temperature And Humidity Sensor Using Arduino IDE
-
Function For Opposite Of Isnan? - - MathWorks
-
Getting NAN-Readings From DHT-11 Sensor - Stack Overflow