Esta tradução está incompleta. Por favor, ajude a traduzir este artigo.

O JavaScript possui comparações estritas e conversão de tipos. Uma comparação estrita (e.g., ===) somente é verdade se os operandos forem do mesmo tipo e de conteúdo correspondente. A comparação abstrata mais comumente utilizada (e.g. ==) converte os operandos no mesmo tipo antes da comparação. Para comparações abstratas relacionais (e.g., <=), os operandos são primeiro convertidos em primitivos, depois para o mesmo tipo, depois comparados.

Strings são comparadas baseadas na ordenação lexicografica padrão, usando valores Unicode.

Características de comparação:

  • Duas strings são estritamente iguals quando elas possuem a mesma sequência de caracteres, o mesmo tamanho, Duas string são estritamente iguals quando elas possuem a mesma sequência de caracteres, o mesmo tamanho, e os mesmos caracteres em posições correspondentes.
  • Dois números são estritamente iguais quando eles são numericamente iguais (tem o mesmo valor numérico). NaN não é igual a nada, incluindo NaN. Zeros positivos e negativos são iguals entre si.
  • Dois operadores Boleanos são estritamente iguais se ambos são true ou ambos são false.
  • Dois objetos distintos nunca são iguais para comparações estritas ou abstratas.
  • Uma expressão comparando Objetos somente é verdadeira se os operandos referenciarem o mesmo Objeto.
  • Os tipo Null e Undefined são estritamente iguais entre eles mesmos e abstratamente iguais entre si.

Operadores de Igualdade 

Igualdade (==)

O operador de igualdade converte o operando se ele não for do mesmo tipo, então aplica a comparação estrita. Se ambos os operandos são objetos, então o JavaScript compara referencias internas que são iguais quando os operandos se referem ao mesmo objeto em memória.

Sintaxe

x == y

Examples

1    ==  1         // verdade
'1'  ==  1         // verdade
1    == '1'        // verdade
0    == false      // verdade
0    == null       // falso
var object1 = {'key': 'value'}, object2 = {'key': 'value'}; 
object1 == object2 // falso
0    == undefined  // falso
null == undefined  // verdade

Desigualdade (!=)

O operador de desigualdade retorna true (verdade) se os operandos não são iguais. Se os dois operandos não são do mesmo tipo, o JavaScript tenta converter os operandos para o tipo apropriado para a comparação. Se ambos os operandos são objetos, então o JavaScript compara referências internas que não são iguais quando os operandos se referem a objetos diferentes na memória.

Sintaxe

x != y

Examplos

1 !=   2     // verdade
1 !=  '1'    // falso
1 !=  "1"    // falso
1 !=  true   // falso
0 !=  false  // falso

Identidade / igualdade estrita (===)

O operador de identidade retorna true (verdade) se os operandos são estritamente iguais (veja acima) sem conversão de tipo

Sintaxe

x === y

Examplos

3 === 3   // verade
3 === '3' // falso
var object1 = {'key': 'value'}, object2 = {'key': 'value'};
object1 === object2 //f also

 

Non-identity / desigualdade estrita (!==)

The non-identity operator returns true if the operands are not equal and/or not of the same type.

Syntax

x !== y

Examples

3 !== '3' // verdade
4 !== 3   // verdade

Relational operators

Each of these operators will call the valueOf() function on each operand before a comparison is made.

Operador Maior (>)

O operador de Maior retorna true se o operando da esquerda for maior que o operando da direita.

Sintaxe

x > y

Examplos

4 > 3 // verdade

Operador maior ou igual (>=)

O operador maior ou igual retorna true se o operando da esquerda for maior ou igual ao operando da direita.

Sintaxe

 x >= y

Examplos

4 >= 3 // verdade
3 >= 3 // verdade

Operador Menor (<)

O operador menor retorna true (verdadeiro) se o operando da esquerda for menor que o operando da direita.

Sintaxe

 x < y

Examplos

3 < 4 // verdade

Operador menor ou igual (<=)

O operador menor ou igual retorna true (verdadeiro) se o operando da esquerda for menor ou igual ao operando da direita.

Sintaxe

 x <= y

Examplos

3 <= 4 // verdade

Usando Operadores de Igualdade

The standard equality operators (== and !=) use the Abstract Equality Comparison Algorithm to compare two operands. If the operands are of different types, it will attempt to convert them to the same type before making the comparison, e.g., in the expression 5 == '5', the string on the right is converted to Number before the comparison is made.

The strict equality operators (=== and !==) use the Strict Equality Comparison Algorithm and are intended for performing equality comparisons on operands of the same type. If the operands are of different types, the result is always false so 5 !== '5'.

Use strict equality operators if the operands must be of a specific type as well as value or if the exact type of the operands is important. Otherwise, use the standard equality operators, which allow you to compare the identity of two operands even if they are not of the same type.

When type conversion is involved in the comparison (i.e., non–strict comparison), JavaScript converts the types String, Number, Boolean, or Object operands as follows:

  • When comparing a number and a string, the string is converted to a number value. JavaScript attempts to convert the string numeric literal to a Number type value. First, a mathematical value is derived from the string numeric literal. Next, this value is rounded to nearest Number type value.
  • If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false.
  • If an object is compared with a number or string, JavaScript attempts to return the default value for the object. Operators attempt to convert the object to a primitive value, a String or Number value, using the valueOf and toString methods of the objects. If this attempt to convert the object fails, a runtime error is generated.
  • Note that an object is converted into a primitive if, and only if, its comparand is a primitive. If both operands are objects, they're compared as objects, and the equality test is true only if both refer the same object.
Note: String objects are Type Object, not String! String objects are rarely used, so the following results might be surprising:
// true as both operands are type String (i.e. string primitives):
'foo' === 'foo'

var a = new String('foo');
var b = new String('foo');

// false as a and b are type Object and reference different objects
a == b 

// false as a and b are type Object and reference different objects
a === b 

// true as a and 'foo' are of different type and, the Object (a) 
// is converted to String 'foo' before comparison
a == 'foo'

Specifications

Specification Status Comment
ECMAScript 1st Edition (ECMA-262) Padrão Initial definition. Implemented in JavaScript 1.0
ECMAScript 3rd Edition (ECMA-262) Padrão Adds === and !== operators. Implemented in JavaScript 1.3
ECMAScript 5.1 (ECMA-262) Padrão Defined in several sections of the specification: Relational Operators, Equality Operators
ECMAScript 2015 (6th Edition, ECMA-262) Padrão Defined in several sections of the specification: Relational Operators, Equality Operators
ECMAScript Latest Draft (ECMA-262) Rascunho Defined in several sections of the specification: Relational Operators, Equality Operators

Browser compatibility

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidiOS SafariSamsung InternetNode.js
Equality (a == b)Chrome Full support YesEdge Full support YesFirefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
Inequality (a != b)Chrome Full support YesEdge Full support YesFirefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
Identity (a === b)Chrome Full support YesEdge Full support YesFirefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
Non-identity (a !== b)Chrome Full support YesEdge Full support YesFirefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
Greater than (a > b)Chrome Full support YesEdge Full support YesFirefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
Greater than or equal (a >= b)Chrome Full support YesEdge Full support YesFirefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
Less than (a < b)Chrome Full support YesEdge Full support YesFirefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
Less than or equal (a <= b)Chrome Full support YesEdge Full support YesFirefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes

Legend

Full support  
Full support

See also

Etiquetas do documento e colaboradores

Colaboradores desta página: adrianovictor
Última atualização por: adrianovictor,