From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../index.html | 61 ++++++++ .../errors/cant_access_property/index.html | 60 ++++++++ .../index.html" | 38 +++++ .../index.html | 52 +++++++ .../for-each-in_loops_are_deprecated/index.html | 169 +++++++++++++++++++++ .../reference/errors/illegal_character/index.html | 77 ++++++++++ .../web/javascript/reference/errors/index.html | 14 ++ .../errors/invalid_array_length/index.html | 78 ++++++++++ .../invalid_assignment_left-hand_side/index.html | 50 ++++++ .../errors/invalid_const_assignment/index.html | 91 +++++++++++ .../reference/errors/invalid_date/index.html | 55 +++++++ .../reference/errors/json_bad_parse/index.html | 105 +++++++++++++ .../missing_colon_after_property_id/index.html | 72 +++++++++ .../missing_curly_after_function_body/index.html | 67 ++++++++ .../errors/missing_formal_parameter/index.html | 80 ++++++++++ .../missing_semicolon_before_statement/index.html | 63 ++++++++ .../errors/negative_repetition_count/index.html | 45 ++++++ .../reference/errors/no_variable_name/index.html | 79 ++++++++++ .../reference/errors/not_a_codepoint/index.html | 56 +++++++ .../reference/errors/not_a_function/index.html | 123 +++++++++++++++ .../errors/n\303\243o_definido/index.html" | 66 ++++++++ .../index.html" | 116 ++++++++++++++ .../reference/errors/precision_range/index.html | 101 ++++++++++++ .../errors/property_access_denied/index.html | 42 +++++ .../reference/errors/read-only/index.html | 81 ++++++++++ .../errors/redeclared_parameter/index.html | 60 ++++++++ .../reference/errors/stmt_after_return/index.html | 74 +++++++++ .../reference/errors/too_much_recursion/index.html | 66 ++++++++ .../reference/errors/undeclared_var/index.html | 62 ++++++++ .../reference/errors/undefined_prop/index.html | 67 ++++++++ .../reference/errors/unexpected_token/index.html | 51 +++++++ .../reference/errors/unexpected_type/index.html | 67 ++++++++ .../errors/unterminated_string_literal/index.html | 63 ++++++++ 33 files changed, 2351 insertions(+) create mode 100644 files/pt-br/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/cant_access_property/index.html create mode 100644 "files/pt-br/web/javascript/reference/errors/fata_par\303\252nteses_ap\303\263s_lista_argumento/index.html" create mode 100644 files/pt-br/web/javascript/reference/errors/fecha_chaves_esquecida_apos_lista_propriedades/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/for-each-in_loops_are_deprecated/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/illegal_character/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/invalid_array_length/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/invalid_const_assignment/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/invalid_date/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/json_bad_parse/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/missing_colon_after_property_id/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/missing_curly_after_function_body/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/missing_formal_parameter/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/missing_semicolon_before_statement/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/negative_repetition_count/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/no_variable_name/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/not_a_codepoint/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/not_a_function/index.html create mode 100644 "files/pt-br/web/javascript/reference/errors/n\303\243o_definido/index.html" create mode 100644 "files/pt-br/web/javascript/reference/errors/n\303\243onomeado_func\303\243o_declara\303\247\303\243o/index.html" create mode 100644 files/pt-br/web/javascript/reference/errors/precision_range/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/property_access_denied/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/read-only/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/redeclared_parameter/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/stmt_after_return/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/too_much_recursion/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/undeclared_var/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/undefined_prop/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/unexpected_token/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/unexpected_type/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/unterminated_string_literal/index.html (limited to 'files/pt-br/web/javascript/reference/errors') diff --git a/files/pt-br/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.html b/files/pt-br/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.html new file mode 100644 index 0000000000..0b0aa34421 --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.html @@ -0,0 +1,61 @@ +--- +title: 'ReferenceError: can''t access lexical declaration`X'' before initialization' +slug: Web/JavaScript/Reference/Errors/Cant_access_lexical_declaration_before_init +tags: + - Erros + - JavaScript + - ReferenceError +translation_of: Web/JavaScript/Reference/Errors/Cant_access_lexical_declaration_before_init +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
ReferenceError: Use before delaration (Edge)
+ReferenceError: can't access lexical declaration `X' before initialization (Firefox)
+ReferenceError: 'x' is not defined (Chrome)
+
+ +

Tipo de Erro

+ +

{{jsxref("ReferenceError")}}

+ +

O  que está errado:

+ +

Uma variável léxica foi acessada antes de ser inicializada. Isso acontece dentro de qualquer declaração de bloco, quando as declarações let ou const são acessadas antes de serem definidas.

+ +

Exemplos

+ +

Errado

+ +

Neste caso, a variável "foo" é redeclarada usando let.

+ +
function test() {
+  let foo = 33;
+  if (true) {
+    let foo = (foo + 55);
+    // ReferenceError: can't access lexical
+    // declaration `foo' before initialization
+  }
+}
+test();
+
+ +

Certo

+ +

Para mudar "foo" dentro do bloco if você precisa remover o let que causa a redeclaração.

+ +
function test(){
+   let foo = 33;
+   if (true) {
+      foo = (foo + 55);
+   }
+}
+test();
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/cant_access_property/index.html b/files/pt-br/web/javascript/reference/errors/cant_access_property/index.html new file mode 100644 index 0000000000..7c5c9affa3 --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/cant_access_property/index.html @@ -0,0 +1,60 @@ +--- +title: 'TypeError: can''t access property "x" of "y"' +slug: Web/JavaScript/Reference/Errors/Cant_access_property +tags: + - Erros + - JavaScript + - TypeError +translation_of: Web/JavaScript/Reference/Errors/Cant_access_property +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
TypeError: Unable to get property {x} of undefined or null reference (Edge)
+TypeError: can't access property {x} of {y} (Firefox)
+TypeError: {y} is undefined, can't access property {x} of it (Firefox)
+TypeError: {y} is null, can't access property {x} of it (Firefox)
+
+Exemplos:
+TypeError: x is undefined, can't access property "prop" of it
+TypeError: x is null, can't access property "prop" of it
+TypeError: can't access property "prop" of undefined
+TypeError: can't access property "prop" of null
+
+ +

Tipo de Erro

+ +

{{jsxref("TypeError")}}.

+ +

O que deu errado?

+ +

O acesso a propriedade foi realizado com um valor {{jsxref("undefined")}} ou {{jsxref("null")}}.

+ +

Exemplos

+ +

Casos inválidos

+ +
// casos undefined e null, onde o metódo substring não irá funcionar
+
+var foo = undefined;
+foo.substring(1); // TypeError: x is undefined, can't access property "substring" of it
+
+var foo = null;
+foo.substring(1); // TypeError: x is null, can't access property "substring" of it
+
+ +

Corrigindo o problema

+ +

Para corrigir o problema de valores undefined ou null,  você pode usar o operador typeof, como no exemplo abaixo.

+ +
if (typeof foo !== 'undefined') {
+  // Agora que sabemos que foo está definida, podemos prosseguir
+}
+ +

Veja também

+ + diff --git "a/files/pt-br/web/javascript/reference/errors/fata_par\303\252nteses_ap\303\263s_lista_argumento/index.html" "b/files/pt-br/web/javascript/reference/errors/fata_par\303\252nteses_ap\303\263s_lista_argumento/index.html" new file mode 100644 index 0000000000..83844d17b5 --- /dev/null +++ "b/files/pt-br/web/javascript/reference/errors/fata_par\303\252nteses_ap\303\263s_lista_argumento/index.html" @@ -0,0 +1,38 @@ +--- +title: Erro de sintaxe falta ) depois da lista de argumentos +slug: Web/JavaScript/Reference/Errors/Fata_parênteses_após_lista_argumento +translation_of: Web/JavaScript/Reference/Errors/Missing_parenthesis_after_argument_list +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
Erro de sintaxe: Falta ) depois da lista de argumento
+
+ +

Tipo de Erro

+ +

{{jsxref("Erro de sintaxe")}}.

+ +

O que houve de errado?

+ +

Ocorreu um erro quando a função foi chamada. Pode ter sido um erro de escrita, falta de operador, ou uma string fora das aspas, por exemplo.

+ +

Exemplos

+ +

Pela falta do operador "+" para fazer a concatenação da string, o JavaScript esperou um argumento para a função log ser "PI: ". Nesse caso, deveria ser finalizado com parênteses de fechamento ')'.

+ +
console.log("PI: " Math.PI);
+// SyntaxError: missing ) after argument list
+
+ +

Você pode corrigir a chamada do log adicionand o operador "+":

+ +
console.log("PI: " + Math.PI);
+// "PI: 3.141592653589793"
+ +

Veja também:

+ + diff --git a/files/pt-br/web/javascript/reference/errors/fecha_chaves_esquecida_apos_lista_propriedades/index.html b/files/pt-br/web/javascript/reference/errors/fecha_chaves_esquecida_apos_lista_propriedades/index.html new file mode 100644 index 0000000000..b10562516e --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/fecha_chaves_esquecida_apos_lista_propriedades/index.html @@ -0,0 +1,52 @@ +--- +title: 'SyntaxError: missing } after property list' +slug: Web/JavaScript/Reference/Errors/Fecha_chaves_esquecida_apos_lista_propriedades +tags: + - Erro de Sintaxe + - Erros + - JavaScript + - SyntaxError +translation_of: Web/JavaScript/Reference/Errors/Missing_curly_after_property_list +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
SyntaxError: missing } after property list
+
+ +

Tipo de erro

+ +

{{jsxref("SyntaxError")}}

+ +

O que deu errado?

+ +

Aconteceu um engano na sintaxe do inicializador do objeto em algum lugar. Pode ser que você esqueceu de colocar uma chave, mas também pode ser uma vírgula que foi esquecida, por exemplo. Verifique também se alguma chave de finalização ou parêntesis estão em algum lugar que não deveriam estar. Indente ou formate o código de uma maneira legível pode te ajudar a enxergar no meio dessa selva.

+ +

Exemplos

+ +

Vírgula esquecida

+ +

Muitas vezes esquecemos uma vígula no inicializador de objeto:

+ +
var obj = {
+  a: 1,
+  b: { minhaProp: 2 }
+  c: 3
+};
+
+ +

O código correto deve ser:

+ +
var obj = {
+  a: 1,
+  b: { minhaProp: 2 },
+  c: 3
+};
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/for-each-in_loops_are_deprecated/index.html b/files/pt-br/web/javascript/reference/errors/for-each-in_loops_are_deprecated/index.html new file mode 100644 index 0000000000..c48e8a8294 --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/for-each-in_loops_are_deprecated/index.html @@ -0,0 +1,169 @@ +--- +title: 'Warning: JavaScript 1.6''s for-each-in loops are deprecated' +slug: Web/JavaScript/Reference/Errors/For-each-in_loops_are_deprecated +tags: + - Aviso + - JavaScript + - Warning +translation_of: Web/JavaScript/Reference/Errors/For-each-in_loops_are_deprecated +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
Warning: JavaScript 1.6's for-each-in loops are deprecated; consider using ES6 for-of instead
+
+ +

Tipo de mensagem

+ +

Warning

+ +

O que aconteceu de errado?

+ +

A declaração {{jsxref("Statements/for_each...in", "for each (variable in obj)")}} do JavaScript 1.6 foi descontinuada e será removida num futuro próximo.

+ +

Exemplos

+ +

Iteração do objeto

+ +

{{jsxref("Statements/for_each...in", "for each...in")}} tem sido usada para iterar por valores específicos do objeto.

+ +

Sintaxe descontinuada

+ +
var object = { a: 10, b: 20 };
+
+for each (var x in object) {
+  console.log(x);        // 10
+                         // 20
+}
+
+ +

Sintaxe padrão alternativa

+ +

Agora você pode utilizar o loop padrão {{jsxref("Statements/for...in", "for...in")}}, para iterar sobre chaves específicas do objeto e receber cada valor para dentro do loop:

+ +
var object = { a: 10, b: 20 };
+
+for (var key in object) {
+  var x = object[key];
+  console.log(x);        // 10
+                         // 20
+}
+
+ +

Ou, utilizando {{jsxref("Statements/for...of", "for...of")}} (ES2015) e {{jsxref("Object.values")}} (ES2017), você pode ter um array dos valores específicos do objeto e iterar sobre o array da seguinte maneira:

+ +
var object = { a: 10, b: 20 };
+
+for (var x of Object.values(object)) {
+  console.log(x);        // 10
+                         // 20
+}
+
+ +

Iteração sobre o Array

+ +

{{jsxref("Statements/for_each...in", "for each...in")}} tem sido usado para iterar sobre elementos específicos do array.

+ +

Sintaxe descontinuada

+ +
var array = [10, 20, 30];
+
+for each (var x in array) {
+  console.log(x);        // 10
+                         // 20
+                         // 30
+}
+
+ +

Sintaxe padrão alternativa

+ +

Isso agora é possível também com loops {{jsxref("Statements/for...of", "for...of")}} (ES2015).

+ +
var array = [10, 20, 30];
+
+for (var x of array) {
+  console.log(x);        // 10
+                         // 20
+                         // 30
+}
+
+ +

Iterando sobre um array null-able

+ +

{{jsxref("Statements/for_each...in", "for each...in")}} não faz nada se o valor especificado for null ou undefined, mas {{jsxref("Statements/for...of", "for...of")}} vai disparar uma exceção nestes casos.

+ +

Sintaxe descontinuada

+ +
function func(array) {
+  for each (var x in array) {
+    console.log(x);
+  }
+}
+func([10, 20]);        // 10
+                       // 20
+func(null);            // prints nothing
+func(undefined);       // prints nothing
+
+ +

Sintaxe padrão alternativa

+ +

Para reescrever as declarações {{jsxref("Statements/for_each...in", "for each...in")}} de modo que os valores possam ser null ou undefined com {{jsxref("Statements/for...of", "for...of")}} também, você precisa utilizar algo como {{jsxref("Statements/for...of", "for...of")}}.

+ +
function func(array) {
+  if (array) {
+    for (var x of array) {
+      console.log(x);
+    }
+  }
+}
+func([10, 20]);        // 10
+                       // 20
+func(null);            // prints nothing
+func(undefined);       // prints nothing
+
+ +

Iterando sobre um par chave-valor de um objeto

+ +

Sintaxe descontinuada

+ +

Existe um idioma descontinuado para iterar sobre pares chave-valor específicos de um objeto, utilizando {{jsxref("Statements/for_each...in", "for each...in")}} e o objeto descontinuado {{jsxref("Iterator")}}.

+ +
var object = { a: 10, b: 20 };
+
+for each (var [key, value] in Iterator(object)) {
+  console.log(key, value);  // "a", 10
+                            // "b", 20
+}
+
+ +

Sintaxe padrão alternativa

+ +

Você pode utilizar agora o loop padrão {{jsxref("Statements/for...in", "for...in")}} para iterar sobre chaves específicas do objeto, e obter cada valor dentro do loop:

+ +
var object = { a: 10, b: 20 };
+
+for (var key in object) {
+  var value = object[key];
+  console.log(key, value);  // "a", 10
+                            // "b", 20
+}
+
+ +

Ou utilizando {{jsxref("Statements/for...of", "for...of")}} (ES2015) e {{jsxref("Object.entries")}} (ES2017), você pode obter um array dos valores específicos do objeto e iterar sobre este array da seguinte maneira:

+ +
var object = { a: 10, b: 20 };
+
+for (var [key, value] of Object.entries(object)) {
+  console.log(key, value);  // "a", 10
+                            // "b", 20
+}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/illegal_character/index.html b/files/pt-br/web/javascript/reference/errors/illegal_character/index.html new file mode 100644 index 0000000000..c36124dc8d --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/illegal_character/index.html @@ -0,0 +1,77 @@ +--- +title: 'SyntaxError: illegal character' +slug: Web/JavaScript/Reference/Errors/Illegal_character +tags: + - Erro + - ErroSintaxe + - ErrodeSintaxe + - Erros + - JavaScript +translation_of: Web/JavaScript/Reference/Errors/Illegal_character +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
SyntaxError: Invalid character (Edge)
+SyntaxError: illegal character (Firefox)
+SyntaxError: Invalid or unexpected token (Chrome)
+
+ +

Tipo do erro

+ +

{{jsxref("SyntaxError")}}

+ +

O que deu errado?

+ +

Há um token inválido ou inesperado que não pertence a esta posição no código. Utilize um editor que realce a sintaxe e cuidadosamente verifique seu código em relação a desajustes como um sinal de menos ( - ) no lugar de um travessão () ou aspas simples ( " ) no lugar de aspas não padronizadas().

+ +

Exemplos

+ +

Caracteres desajustados

+ +

Alguns carateres parecem similares, mas irão impedir que o analisador interprete seu código. Exemplos famosos disso são as aspas, o sinal de menos ou o ponto e vírgula (o ponto de interrogação grego (U+37e) é quase igual)

+ +
“Isso parece uma string”;
+// SyntaxError: illegal character
+
+42 – 13;
+// SyntaxError: illegal character
+
+ +

Isto deve funcionar:

+ +
"Isso é realmente uma string";
+
+42 - 13;
+
+ +

Caracteres esquecidos

+ +

É fácil esquecer um caractere aqui ou ali.

+ +
var colors = ['#000', #333', '#666'];
+// SyntaxError: illegal character
+
+ +

Adicione as aspas que faltam no '#333'.

+ +
var colors = ['#000', '#333', '#666'];
+ +

Caracteres escondidos

+ +

Quando copiamos e colamos código de fontes externas, pode haver caracteres inválidos. Cuidado!

+ +
var foo = 'bar';​
+// SyntaxError: illegal character
+
+ +

Quando inspeciona-se este código em um editor como o Vim, você pode ver que, na verdade, há um caractere zero-width space (ZWSP) (U+200B).

+ +
var foo = 'bar';​<200b>
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/index.html b/files/pt-br/web/javascript/reference/errors/index.html new file mode 100644 index 0000000000..2df10baf6e --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/index.html @@ -0,0 +1,14 @@ +--- +title: JavaScript error reference +slug: Web/JavaScript/Reference/Errors +tags: + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Errors +--- +

{{jsSidebar("Errors")}}

+ +

Lista de erros "globais".

+ +

{{ListSubPages("/pt-BR/docs/Web/JavaScript/Reference/Errors")}}

diff --git a/files/pt-br/web/javascript/reference/errors/invalid_array_length/index.html b/files/pt-br/web/javascript/reference/errors/invalid_array_length/index.html new file mode 100644 index 0000000000..fc520f9bea --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/invalid_array_length/index.html @@ -0,0 +1,78 @@ +--- +title: 'RangeError: invalid array length' +slug: Web/JavaScript/Reference/Errors/Invalid_array_length +tags: + - Errors + - Erros + - JavaScript + - RangeError +translation_of: Web/JavaScript/Reference/Errors/Invalid_array_length +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
RangeError: invalid array length (Firefox)
+RangeError: Invalid array length (Chrome)
+RangeError: Invalid array buffer length (Chrome)
+
+ +

Tipo de erro

+ +

{{jsxref("RangeError")}}

+ +

O que houve de errado?

+ +

Um comprimento inválido de array pode aparecer nas seguintes situações:

+ + + +

Porque Array e ArrayBuffer tem um comprimento limitado? A propriedade length de um Array ou um ArrayBuffer é representado por um inteiro 32-bit unsigned, que pode apenas armazenar valores que estão no intervalo de 0 a 232-1.

+ +

Se você está criando um Array, utilizando o construtor, você provavelmente quer usar a notação literal, onde o primeiro argumento é interpretado como o comprimento do Array.

+ +

Ao contrário, você poderia querer travar o comprimento antes de ajustar a propriedade do comprimento, ou utilizá-lo com um argumento do construtor.

+ +

Exemplos

+ +

Casos inválidos

+ +
new Array(Math.pow(2, 40))
+new Array(-1)
+new ArrayBuffer(Math.pow(2, 32))
+new ArrayBuffer(-1)
+
+let a = [];
+a.length = a.length - 1;         // define -1 à propriedade length
+
+let b = new Array(Math.pow(2, 32) - 1);
+b.length = b.length + 1;         // define 2^32 à propriedade length
+
+ +

Casos válidos

+ +
[ Math.pow(2, 40) ]                     // [ 1099511627776 ]
+[ -1 ]                                  // [ -1 ]
+new ArrayBuffer(Math.pow(2, 32) - 1)
+new ArrayBuffer(0)
+
+let a = [];
+a.length = Math.max(0, a.length - 1);
+
+let b = new Array(Math.pow(2, 32) - 1);
+b.length = Math.min(0xffffffff, b.length + 1);
+
+// 0xffffffff é a notação hexadecimal de 2^32 - 1
+// que também pode ser escrito como (-1 >>> 0)
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.html b/files/pt-br/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.html new file mode 100644 index 0000000000..9b15ff4bf9 --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.html @@ -0,0 +1,50 @@ +--- +title: 'ReferenceError: invalid assignment left-hand side' +slug: Web/JavaScript/Reference/Errors/Invalid_assignment_left-hand_side +translation_of: Web/JavaScript/Reference/Errors/Invalid_assignment_left-hand_side +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
ReferenceError: invalid assignment left-hand side
+
+ +

Tipo do erro

+ +

{{jsxref("ReferenceError")}}.

+ +

O que deu errado?

+ +

Ouve uma declaração inesperada em algum lugar. Isso pode ocorrer devido a uma confusão entre um  Operador de atribuição e um Operador de comparação, por exemplo. Enquanto um "=" define uma variavel, "==" ou "===" são usados para fazer uma comparação entre valores.

+ +

 Exemplos

+ +
if (Math.PI = 3 || Math.PI = 4) {
+  console.log('de modo algum!');
+}
+// ReferenceError: invalid assignment left-hand side
+
+var str = 'Olá, '
++= 'sou eu '
++= 'que você está procurando?';
+// ReferenceError: invalid assignment left-hand side
+
+ +

Na declaração if você deve usar um operador de comparação ("=="), e para a  atribuição da string, apenas o operador mais ("+") é necessario

+ +
if (Math.PI == 3 || Math.PI == 4) {
+  console.log('de modo algum!');
+}
+
+var str = 'Olá, '
++ 'do '
++ 'outro lado!';
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/invalid_const_assignment/index.html b/files/pt-br/web/javascript/reference/errors/invalid_const_assignment/index.html new file mode 100644 index 0000000000..cc5a4733a4 --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/invalid_const_assignment/index.html @@ -0,0 +1,91 @@ +--- +title: 'TypeError: atribuição inválida para const "x"' +slug: Web/JavaScript/Reference/Errors/Invalid_const_assignment +tags: + - Erro + - JavaScript + - TypeError +translation_of: Web/JavaScript/Reference/Errors/Invalid_const_assignment +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
TypeError: invalid assignment to const "x" (Firefox)
+TypeError: Assignment to constant variable. (Chrome)
+TypeError: Assignment to const (Edge)
+TypeError: Redeclaration of const 'x' (IE)
+
+ +

Tipo de erro

+ +

{{jsxref("TypeError")}}

+ +

O que deu errado?

+ +

Uma constante é um valor que não pode ser alterado pelo programa durante a execução normal. Ele não pode mudar através de reatribuição e não pode ser redeclarado. Em JavaScript, as constantes são declaradas usando a palavra-chave const.

+ +

Exemplos

+ +

Redeclaração inválida

+ +

Atribuir um valor ao mesmo nome de constante no mesmo escopo de bloco lançará o erro.

+ +
const COLUNAS = 80;
+
+// ...
+
+COLUNAS = 120; // TypeError: invalid assignment to const `COLUNAS'
+ +

Corrigindo o erro

+ +

Existem várias opções para corrigir esse erro. Verifique o que se pretendia alcançar com a constante em questão.

+ +

Renomear

+ +

Se você quis declarar outra constante, escolha outro nome e renomeie. Esse nome de constante já está sendo usado nesse escopo.

+ +
const COLUNAS = 80;
+const COLUNAS_LARGAS = 120;
+ +

const, let ou var?

+ +

Não use const se você não quis declarar uma constante. Talvez você quisesse declarar uma variável com escopo de bloco com let ou uma variável global com var.

+ +
let colunas = 80;
+
+// ...
+
+let colunas = 120;
+
+ +

Escopo

+ +

Verifique se você está no escopo correto. Essa constante deve aparecer nesse escopo ou deveria aparecer em uma função, por exemplo?

+ +
const COLUNAS = 80;
+
+function configurarAmbienteTelaGrande() {
+  const COLUNAS = 120;
+}
+ +

const e imutabilidade

+ +

A declaração const cria uma referência somente leitura para um valor. Isso não significa que o valor que ela contém é imutável, apenas que o identificador da variável não pode ser reatribuído. Por exemplo, caso o conteúdo seja um objeto, isso significa que o objeto em si ainda pode ser alterado. Isso significa que você não pode alterar o valor armazenado em uma variável:

+ +
const obj = {foo: 'bar'};
+obj = {foo: 'baz'}; // TypeError: invalid assignment to const `obj'
+
+ +

Mas você pode alterar as propriedades em uma variável:

+ +
obj.foo = 'baz';
+obj; // Object { foo: "baz" }
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/invalid_date/index.html b/files/pt-br/web/javascript/reference/errors/invalid_date/index.html new file mode 100644 index 0000000000..8663f67051 --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/invalid_date/index.html @@ -0,0 +1,55 @@ +--- +title: 'RangeError: invalid date' +slug: Web/JavaScript/Reference/Errors/Invalid_date +tags: + - Errors + - Erros + - JavaScript + - RangeError +translation_of: Web/JavaScript/Reference/Errors/Invalid_date +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
RangeError: invalid date (Firefox)
+RangeError: invalid time value (Chrome)
+RangeError: Provided date is not in valid range (Chrome)
+
+ +

Tipo de erro

+ +

{{jsxref("RangeError")}}

+ +

O que houve de errado?

+ +

Uma string apontando para uma data inválida foi disponibilizada para {{jsxref("Date")}} ou {{jsxref("Date.parse()")}}.

+ +

Exemplos

+ +

Casos inválidos

+ +

Strings irreconhecíveis ou data contendo elementos de strings formatadas com valores ISO ilegais, geralmente retornam  {{jsxref("NaN")}}. No entanto, dependendo da implementação, strings com formatos em não conformidade ISO, também podem disparar RangeError: invalid date, como os seguintes casos no Firefox:

+ +
new Date('foo-bar 2014');
+new Date('2014-25-23').toISOString();
+new Date('foo-bar 2014').toString();
+
+ +

Isto, no entanto, retorna {{jsxref("NaN")}} no Firefox:

+ +
Date.parse('foo-bar 2014'); // NaN
+ +

Para mais detalhes, veja a documentação {{jsxref("Date.parse()")}}.

+ +

Casos válidos

+ +
new Date('05 October 2011 14:48 UTC');
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/json_bad_parse/index.html b/files/pt-br/web/javascript/reference/errors/json_bad_parse/index.html new file mode 100644 index 0000000000..e3d389d2f8 --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/json_bad_parse/index.html @@ -0,0 +1,105 @@ +--- +title: 'SyntaxError: JSON.parse: bad parsing' +slug: Web/JavaScript/Reference/Errors/JSON_bad_parse +translation_of: Web/JavaScript/Reference/Errors/JSON_bad_parse +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
SyntaxError: JSON.parse: unterminated string literal
+SyntaxError: JSON.parse: bad control character in string literal
+SyntaxError: JSON.parse: bad character in string literal
+SyntaxError: JSON.parse: bad Unicode escape
+SyntaxError: JSON.parse: bad escape character
+SyntaxError: JSON.parse: unterminated string
+SyntaxError: JSON.parse: no number after minus sign
+SyntaxError: JSON.parse: unexpected non-digit
+SyntaxError: JSON.parse: missing digits after decimal point
+SyntaxError: JSON.parse: unterminated fractional number
+SyntaxError: JSON.parse: missing digits after exponent indicator
+SyntaxError: JSON.parse: missing digits after exponent sign
+SyntaxError: JSON.parse: exponent part is missing a number
+SyntaxError: JSON.parse: unexpected end of data
+SyntaxError: JSON.parse: unexpected keyword
+SyntaxError: JSON.parse: unexpected character
+SyntaxError: JSON.parse: end of data while reading object contents
+SyntaxError: JSON.parse: expected property name or '}'
+SyntaxError: JSON.parse: end of data when ',' or ']' was expected
+SyntaxError: JSON.parse: expected ',' or ']' after array element
+SyntaxError: JSON.parse: end of data when property name was expected
+SyntaxError: JSON.parse: expected double-quoted property name
+SyntaxError: JSON.parse: end of data after property name when ':' was expected
+SyntaxError: JSON.parse: expected ':' after property name in object
+SyntaxError: JSON.parse: end of data after property value in object
+SyntaxError: JSON.parse: expected ',' or '}' after property value in object
+SyntaxError: JSON.parse: expected ',' or '}' after property-value pair in object literal
+SyntaxError: JSON.parse: property names must be double-quoted strings
+SyntaxError: JSON.parse: expected property name or '}'
+SyntaxError: JSON.parse: unexpected character
+SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
+
+ +

Tipo de erro

+ +

{{jsxref("SyntaxError")}}

+ +

O que ocorreu de errado?

+ +

{{jsxref("JSON.parse()")}} converte uma string para JSON. A string precisa ser um JSON válido e retornará esse erro caso a sintaxe esteja errada.

+ +

Exemplos

+ +

JSON.parse() não permite vírgulas à direita

+ +

As duas linhas retornarão um SyntaxError:

+ +
JSON.parse('[1, 2, 3, 4,]');
+JSON.parse('{"foo": 1,}');
+// SyntaxError JSON.parse: unexpected character
+// at line 1 column 14 of the JSON data
+
+ +

Retire as virgulas sobrando para converter o JSON corretamente:

+ +
JSON.parse('[1, 2, 3, 4]');
+JSON.parse('{"foo": 1}');
+ +

Propriedades precisão ser escritas com aspas duplas

+ +

Você não pode usar aspas simples em propriedades, exemplo: 'foo'.

+ +
JSON.parse("{'foo': 1}");
+// SyntaxError: JSON.parse: expected property name or '}'
+// at line 1 column 2 of the JSON data
+ +

Em vez disso use "foo":

+ +
JSON.parse('{"foo": 1}');
+ +

Zeros à esquerda e pontos decimais

+ +

Você não pode usar zeros à esquerda, como 01, e pontos decimais precisam ser seguidos de pelo menos um digito.

+ +
JSON.parse('{"foo": 01}');
+// SyntaxError: JSON.parse: expected ',' or '}' after property value
+// in object at line 1 column 2 of the JSON data
+
+JSON.parse('{"foo": 1.}');
+// SyntaxError: JSON.parse: unterminated fractional number
+// at line 1 column 2 of the JSON data
+
+ +

Em vez disso, use o 1 sem o zero, e pelo menos um digito após um ponto decimal:

+ +
JSON.parse('{"foo": 1}');
+JSON.parse('{"foo": 1.0}');
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/missing_colon_after_property_id/index.html b/files/pt-br/web/javascript/reference/errors/missing_colon_after_property_id/index.html new file mode 100644 index 0000000000..f235891169 --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/missing_colon_after_property_id/index.html @@ -0,0 +1,72 @@ +--- +title: 'Erro de Sintaxe: faltando : depois da propriedade id' +slug: Web/JavaScript/Reference/Errors/Missing_colon_after_property_id +translation_of: Web/JavaScript/Reference/Errors/Missing_colon_after_property_id +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
SyntaxError: missing : after property id
+
+ +

Tipo de erro

+ +

{{jsxref("SyntaxError")}}

+ +

O que deu errado?

+ +

Ao criar objetos com a sintaxe do iniciador do objeto, dois pontos (:) separam chaves e valores para as propriedades do objeto.

+ +
var obj = { propertyKey: 'value' };
+
+ +

Exemplos

+ +

Dois-pontos contra sinal de igualdade

+ +

Este código falha, pois o sinal de igualdade não pode ser usado dessa maneira nesta sintaxe do iniciador do objeto.

+ +
var obj = { propertyKey = 'value' };
+// SyntaxError: missing : after property id
+
+ +

Correto seria usar um dois-pontos, ou usar colchetes para atribuir uma nova propriedade depois que o objeto já foi criado.

+ +
var obj = { propertyKey: 'value' };
+
+// or alternatively
+
+var obj = { };
+obj['propertyKey'] = 'value';
+
+ +

Propriedades vazia

+ +

Você não pode criar propriedades vazias como esta:

+ +
var obj = { propertyKey; };
+// SyntaxError: missing : after property id
+
+ +

Se você precisa definir uma propriedade sem um valor, você pode usar {{jsxref("null")}} como um valor.

+ +
var obj = { propertyKey: null };
+ +

Propriedades computadas

+ +

Se você criar uma chave de propriedade de uma expressão, você precisa usar colchetes. Caso contrário, o nome da propriedade não pode ser computado:

+ +
var obj = { 'b'+'ar': 'foo' };
+// SyntaxError: missing : after property id
+
+ +

Coloque a expressão entre parênteses []:

+ +
var obj = { ['b'+'ar']: 'foo' };
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/missing_curly_after_function_body/index.html b/files/pt-br/web/javascript/reference/errors/missing_curly_after_function_body/index.html new file mode 100644 index 0000000000..b35ba4dfdf --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/missing_curly_after_function_body/index.html @@ -0,0 +1,67 @@ +--- +title: 'SyntaxError: missing } after function body' +slug: Web/JavaScript/Reference/Errors/Missing_curly_after_function_body +tags: + - PT +translation_of: Web/JavaScript/Reference/Errors/Missing_curly_after_function_body +--- +
{{jsSidebar("Errors")}}
+ +

The JavaScript exception "missing } after function body" occurs when there is a syntax mistake when creating a function somewhere. Check if any closing curly brackets or parenthesis are in the correct order.

+ +

Message

+ +
SyntaxError: Expected '}' (Edge)
+SyntaxError: missing } after function body (Firefox)
+
+ +

Error type

+ +

{{jsxref("SyntaxError")}}

+ +

What went wrong?

+ +

There is a syntax mistake when creating a function somewhere. Also check if any closing curly brackets or parenthesis are in the correct order. Indenting or formatting the code a bit nicer might also help you to see through the jungle.

+ +

Examples

+ +

Forgotten closing curly bracket

+ +

Oftentimes, there is a missing curly bracket in your function code:

+ +
var charge = function() {
+  if (sunny) {
+    useSolarCells();
+  } else {
+    promptBikeRide();
+};
+
+ +

Correct would be:

+ +
var charge = function() {
+  if (sunny) {
+    useSolarCells();
+  } else {
+    promptBikeRide();
+  }
+};
+ +

It can be more obscure when using IIFE, Closures, or other constructs that use a lot of different parenthesis and curly brackets, for example.

+ +
(function() { if (true) { return false; } );
+
+ +

Oftentimes, indenting differently or double checking indentation helps to spot these errors.

+ +
(function() {
+  if (true) {
+    return false;
+  }
+});
+ +

See also

+ + diff --git a/files/pt-br/web/javascript/reference/errors/missing_formal_parameter/index.html b/files/pt-br/web/javascript/reference/errors/missing_formal_parameter/index.html new file mode 100644 index 0000000000..cedc5bb71a --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/missing_formal_parameter/index.html @@ -0,0 +1,80 @@ +--- +title: 'SyntaxError: missing formal parameter' +slug: Web/JavaScript/Reference/Errors/Missing_formal_parameter +tags: + - Erro + - Erros + - JavaScript + - SyntaxError +translation_of: Web/JavaScript/Reference/Errors/Missing_formal_parameter +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
SyntaxError: missing formal parameter (Firefox)
+
+ +

Tipo de error

+ +

{{jsxref("SyntaxError")}}

+ +

O que deu errado?

+ +

"Parâmetro Formal" é uma maneira elegante de dizer "parâmetro de função". Faltam parâmetros válidos em sua função. Na declaração de uma função os parâmetros devem ser {{Glossary("Identifier", "identifiers")}}, em vez de um valor como números, strings ou objetos. Declarar funções e chamar funções são dois passos diferentes. Declarações exigem identificadores como parâmetros e é apenas ao chamar (invocar) a função que você fornece os valores que a função deve usar.

+ +

Em {{glossary("JavaScript")}}, identificadores podem obter apenas caracteres alfanuméricos (ou "$" e "_"), e não podem começar com um número. Um identificador difere de uma string porque uma string é um dado, enquanto que um identificador é parte do código.

+ +

Exemplos

+ +

Parâmetros de função devem ser identificadores ao se configurar uma função. Todas essas declarações de função abaixo falham, pois estão fornecendo valores para seus parâmetros:

+ +
function quadrado(3) {
+  return numero * numero;
+};
+// SyntaxError: missing formal parameter
+
+function saudacao("Olá") {
+  return saudacao;
+};
+// SyntaxError: missing formal parameter
+
+function log({ obj: "valor"}) {
+  console.log(arg)
+};
+// SyntaxError: missing formal parameter
+
+ +

Você terá de usar identificadores nas declarações de função:

+ +
function quadrado(numero) {
+  return numero * numero;
+};
+
+function saudar(saudacao) {
+  return saudacao;
+};
+
+function log(arg) {
+  console.log(arg)
+};
+ +

You can then call these functions with the arguments you like:

+ +
quadrado(2); // 4
+
+saudar("Olá"); // "Olá"
+
+log({obj: "valor"}); // Object { obj: "valor" }
+
+ +

Ver também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/missing_semicolon_before_statement/index.html b/files/pt-br/web/javascript/reference/errors/missing_semicolon_before_statement/index.html new file mode 100644 index 0000000000..b44ca2aae6 --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/missing_semicolon_before_statement/index.html @@ -0,0 +1,63 @@ +--- +title: 'SyntaxError: missing ; before statement' +slug: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement +translation_of: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement +--- +
{{jsSidebar("Errors")}}
+ +

Messagem

+ +
SyntaxError: falta ; antes da declaração
+
+ +

Tipo de erro

+ +

{{jsxref("SyntaxError")}}.

+ +

O que deu errado?

+ +

Falta um ponto-e-vírgula (;) em algum lugar. JavaScript statements must be terminated with semicolons. Some of them are affected by automatic semicolon insertion (ASI), but in this case you need to provide a semicolon, so that JavaScript can parse the source code correctly.

+ +

However, oftentimes, this error is only a consequence of another error, like not escaping strings properly, or using var wrongly. You might also have too many parenthesis somewhere. Carefully check the syntax when this error is thrown.

+ +

Exemplos

+ +

Unescaped strings

+ +

This error can occur easily when not escaping strings properly and the JavaScript engine is expecting the end of your string already. For example:

+ +
var foo = 'Tom's bar';
+// SyntaxError: missing ; before statement
+ +

You can use double quotes, or escape the apostrophe:

+ +
var foo = "Tom's bar";
+var foo = 'Tom\'s bar';
+
+ +

Declaring properties with var

+ +

You cannot declare properties of an object or array with a var declaration.

+ +
var obj = {};
+var obj.foo = 'hi'; // SyntaxError missing ; before statement
+
+var array = [];
+var array[0] = 'there'; // SyntaxError missing ; before statement
+
+ +

Instead, omit the var keyword:

+ +
var obj = {};
+obj.foo = 'hi';
+
+var array = [];
+array[0] = 'there';
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/negative_repetition_count/index.html b/files/pt-br/web/javascript/reference/errors/negative_repetition_count/index.html new file mode 100644 index 0000000000..599e7e1271 --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/negative_repetition_count/index.html @@ -0,0 +1,45 @@ +--- +title: 'RangeError: repeat count must be non-negative' +slug: Web/JavaScript/Reference/Errors/Negative_repetition_count +tags: + - Erros + - JavaScript + - RangeError +translation_of: Web/JavaScript/Reference/Errors/Negative_repetition_count +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
RangeError: argument out of range
+RangeError: repeat count must be non-negative (Firefox)
+RangeError: Invalid count value (Chrome)
+
+ +

Tipo de Erro

+ +

{{jsxref("RangeError")}}

+ +

O que está errado?

+ +

O método {{jsxref("String.prototype.repeat()")}} foi usado. Ele tem um parâmetro count indicando o número de vezes para repetir a string. Esse contador deve ser maior ou igual à 0 menor que  {{jsxref("Infinity")}} (infinito positivo). O intervalo de vaores permitidos pode ser descrito por:  [0, +∞).

+ +

Exemplos

+ +

Errado

+ +
'abc'.repeat(-1); // RangeError 
+ +

Certo

+ +
'abc'.repeat(0);    // ''
+'abc'.repeat(1);    // 'abc'
+'abc'.repeat(2);    // 'abcabc'
+'abc'.repeat(3.5);  // 'abcabcabc' (count será convertido para inteiro)
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/no_variable_name/index.html b/files/pt-br/web/javascript/reference/errors/no_variable_name/index.html new file mode 100644 index 0000000000..5e192a15a2 --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/no_variable_name/index.html @@ -0,0 +1,79 @@ +--- +title: 'SyntaxError: missing variable name' +slug: Web/JavaScript/Reference/Errors/No_variable_name +translation_of: Web/JavaScript/Reference/Errors/No_variable_name +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
SyntaxError: missing variable name (Firefox)
+SyntaxError: Unexpected token = (Chrome)
+ +

Tipo de erro

+ +

{{jsxref("SyntaxError")}}

+ +

O que deu errado?

+ +

O nome de uma variável está faltando. Isto é provavelmente devido a um erro de sintaxe no seu código. Provavelmente uma vírgula está errada em algum lugar. Totalmente compreensível! Nomear as coisas é tão difícil.

+ +

Examplos

+ +

Falta um nome de variável

+ +
var = "foo";
+
+ +

É difícil chegar com bons nomes de variáveis. Nós todos estivemos lá.

+ +
var ohGodWhy = "foo";
+ +

Palavras-chave reservadas não podem ser nomes de variáveis

+ +

Existem alguns nomes de variáveis ​​que são palavras-chave resevadas. Você não pode usar isso. Desculpa :(

+ +
var debugger = "whoop";
+// SyntaxError: missing variable name
+
+ +

Declarando múltiplas variáveis

+ +

Preste especial atenção às vírgulas ao declarar múltiplas variáveis. Existe um excesso de vírgula? Você acidentalmente adicionou vírgulas em vez de ponto e vírgula?

+ +
var x, y = "foo",
+var x, = "foo"
+
+var first = document.getElementById('one'),
+var second = document.getElementById('two'),
+
+// SyntaxError: missing variable name
+
+ +

A versão corrigida:

+ +
var x, y = "foo";
+var x = "foo";
+
+var first = document.getElementById('one');
+var second = document.getElementById('two');
+ +

Arrays

+ +

{{jsxref("Array")}} literais em JavaScript precisam de colchetes ao redor dos valores. Isso não funcionará:

+ +
var arr = 1,2,3,4,5;
+// SyntaxError: missing variable name
+
+ +

Isso seria correto:

+ +
var arr = [1,2,3,4,5];
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/not_a_codepoint/index.html b/files/pt-br/web/javascript/reference/errors/not_a_codepoint/index.html new file mode 100644 index 0000000000..7e0c85bf8d --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/not_a_codepoint/index.html @@ -0,0 +1,56 @@ +--- +title: 'RangeError: argument is not a valid code point' +slug: Web/JavaScript/Reference/Errors/Not_a_codepoint +tags: + - Erros + - JavaScript + - RangeError +translation_of: Web/JavaScript/Reference/Errors/Not_a_codepoint +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
RangeError: Invalid code point {0} (Edge)
+RangeError: {0} is not a valid code point (Firefox)
+RangeError: Invalid code point {0} (Chrome)
+
+ + + +

Tipo de Erro

+ +

{{jsxref("RangeError")}}

+ +

O que está errado?

+ +

{{jsxref("String.fromCodePoint()")}} dispara esse erro quando são passados valores {{jsxref("NaN")}}, inteiros negativos (-1), não inteiros (5.4), ou valores maiores que 0x10FFFF (1114111).

+ +

Um code point é um valor Unicode; isto é,é um valor inteiro entre 0 e 0x10FFFF.

+ +

Exemplos

+ +

Errado

+ +
String.fromCodePoint('_');      // RangeError
+String.fromCodePoint(Infinity); // RangeError
+String.fromCodePoint(-1);       // RangeError
+String.fromCodePoint(3.14);     // RangeError
+String.fromCodePoint(3e-2);     // RangeError
+String.fromCodePoint(NaN);      // RangeError
+ +

Certo

+ +
String.fromCodePoint(42);       // "*"
+String.fromCodePoint(65, 90);   // "AZ"
+String.fromCodePoint(0x404);    // "\u0404"
+String.fromCodePoint(0x2F804);  // "\uD87E\uDC04"
+String.fromCodePoint(194564);   // "\uD87E\uDC04"
+String.fromCodePoint(0x1D306, 0x61, 0x1D307) // "\uD834\uDF06a\uD834\uDF07"
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/not_a_function/index.html b/files/pt-br/web/javascript/reference/errors/not_a_function/index.html new file mode 100644 index 0000000000..c98e500583 --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/not_a_function/index.html @@ -0,0 +1,123 @@ +--- +title: 'TypeError: "x" is not a function' +slug: Web/JavaScript/Reference/Errors/Not_a_function +tags: + - Erros JavaScrip TypeError +translation_of: Web/JavaScript/Reference/Errors/Not_a_function +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
TypeError: Object doesn't support property or method {x} (Edge)
+TypeError: "x" is not a function
+
+ +

Tipo do erro

+ +

{{jsxref("TypeError")}}.

+ +

O que deu errado?

+ +

Houve a tentativa de obter um valor de uma função, mas o valor não é exatamente uma função. Algum código espera que você forneça uma função, mas não foi o que acontenceu.

+ +

Talvez exista um erro de digitação no nome da função? Talvez o objeto no qual você está chamando o método não tenha essa função? Por exemplo, objetos no JavaScript não tem a função map, mas o objeto Array tem.

+ +

Existem várias funções internas que precisam de uma função (callback). Você terá que prover uma função para obter esses métodos funcionando corretamente:

+ + + +

Exemplos

+ +

Um erro de digitação no nome da função

+ +

Nesse caso, que ocorre com bastante frequência, existe um erro de digitação no nome do método:

+ +
var x = document.getElementByID('foo');
+// TypeError: document.getElementByID is not a function
+
+ +

O nome correto da função é getElementById:

+ +
var x = document.getElementById('foo');
+
+ +

Função chamada no objeto errado

+ +

Para alguns métodos, é necessário fornecer a função (callback) que irá funcionar apenas em objetos específicos. Nesse exemplo, é utilizado {{jsxref("Array.prototype.map()")}} que irá funcionar apenas em objetos {{jsxref("Array")}}.

+ +
var obj = {a: 13, b: 37, c: 42};
+
+obj.map(function(num) {
+  return num * 2;
+});
+
+// TypeError: obj.map is not a function
+ +

Ao invés disso, use uma array:

+ +
var numbers = [1, 4, 9];
+
+numbers.map(function(num) {
+  return num * 2;
+});
+
+// Array [2, 8, 18]
+
+ +

Função compartilha o nome com uma propriedade pré-existente

+ +

Algumas vezes, ao criar uma classe, pode haver uma propriedade e função com os mesmos nomes. Ao chamar a função, o compilador não consegue identificar a função.

+ +
var Dog = function () {
+ this.age = 11;
+ this.color = "black";
+ this.name = "Ralph";
+ return this;
+}
+
+Dog.prototype.name = function(name) {
+ this.name = name;
+ return this;
+}
+
+
+var myNewDog = new Dog();
+myNewDog.name("Cassidy"); //Uncaught TypeError: myNewDog.name is not a function
+
+ +

Então, use um nome diferente para a propriedade

+ +
var Dog = function () {
+ this.age = 11;
+ this.color = "black";
+ this.dogName = "Ralph"; //Using this.dogName instead of .name
+ return this;
+}
+
+Dog.prototype.name = function(name) {
+ this.dogName = name;
+ return this;
+}
+
+
+var myNewDog = new Dog();
+myNewDog.name("Cassidy"); //Dog { age: 11, color: 'black', dogName: 'Cassidy' }
+
+ +

Veja também

+ + diff --git "a/files/pt-br/web/javascript/reference/errors/n\303\243o_definido/index.html" "b/files/pt-br/web/javascript/reference/errors/n\303\243o_definido/index.html" new file mode 100644 index 0000000000..6642b81b44 --- /dev/null +++ "b/files/pt-br/web/javascript/reference/errors/n\303\243o_definido/index.html" @@ -0,0 +1,66 @@ +--- +title: 'ReferenceError: "x" não está definido' +slug: Web/JavaScript/Reference/Errors/Não_definido +translation_of: Web/JavaScript/Reference/Errors/Not_defined +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
ReferenceError: "x" is not defined
+
+ +

Tipo de erro

+ +

{{jsxref("ReferenceError")}}

+ +

O que deu errado?

+ +

Há uma variavel inexistente referenciada em algum lugar. Essa variável precisa ser declarada ou você precisa ter certeza que ela está disponível no seu atual script ou {{Glossary("escopo")}}.

+ +
+

Nota: Quando carregar uma biblioteca (como o JQuery) tenha certeza que ela está carregada antes que você acesse as variáveis dela, como "$". Coloque na tag {{HTMLElement("script")}} para carregar a biblioteca antes do seu código usá-lo.

+
+ +

Exemplos

+ +

Variável não declarada

+ +
foo.substring(1); // ReferenceError: foo is not defined
+
+ +

A variável "foo" não está definida em lugar nenhum. Ela precisa ser uma string e assim o método {{jsxref("String.prototype.substring()")}} irá funcionar.

+ +
var foo = "bar";
+foo.substring(1); // "ar"
+ +

Escopo Errado

+ +

Uma variável precisa estar disponível no atual contexto de execução. Variáveis definidas dentro de uma function não podem ser acessadas de outros lugares fora da função, porque a variável é definida apenas no escopo da função

+ +
function numbers () {
+  var num1 = 2,
+      num2 = 3;
+  return num1 + num2;
+}
+
+console.log(num1); // ReferenceError num1 is not defined.
+ +

Entretanto, uma função pode acessar todas as variáveis e funções definidas dentro do escopo no qual elas estão definidas. Em outras palavras, uma função definida no escopo global pode acessar todas as variáveis no escopo global.

+ +
var num1 = 2,
+    num2 = 3;
+
+function numbers () {
+  return num1 + num2;
+}
+
+console.log(num1); // 2
+ +

Veja também

+ + diff --git "a/files/pt-br/web/javascript/reference/errors/n\303\243onomeado_func\303\243o_declara\303\247\303\243o/index.html" "b/files/pt-br/web/javascript/reference/errors/n\303\243onomeado_func\303\243o_declara\303\247\303\243o/index.html" new file mode 100644 index 0000000000..6f01588059 --- /dev/null +++ "b/files/pt-br/web/javascript/reference/errors/n\303\243onomeado_func\303\243o_declara\303\247\303\243o/index.html" @@ -0,0 +1,116 @@ +--- +title: 'Erro de sintaxe: declaração de função requer um nome' +slug: Web/JavaScript/Reference/Errors/NãoNomeado_funcão_declaração +tags: + - Erro + - Erro de Sintaxe + - JavaScript + - Statement +translation_of: Web/JavaScript/Reference/Errors/Unnamed_function_statement +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
Errodesintaxe: Identificador Esperado(Edge)
+Errodesintaxe: declaração de função requer um nome [Firefox]
+Errodesintaxe: Token inesperado ( [Chrome]
+
+ +

Tipo de erro

+ +

{{jsxref("Errodesintaxe")}}

+ +

O que estava errado?

+ +

Existe uma declaração no código que requer um nome. Você precisa checar como as funções são definidas e se você precisa providenciar um nome, se a função em questão precisa ser uma expressão de função, um {{Glossary("IIFE")}} ou se o código da função está colocado corretamente neste contexto.

+ +

Exemplos

+ +

Statements vs expressions

+ +

Uma  declaração de função (ou declaração de função) requer um nome, isso não vai funcionar:

+ +
function () {
+  return 'Olha mundo';
+}
+// SyntaxError: function statement requires a name
+
+ +

Você pode usar uma expressão de função ao invés de uma atribuição.

+ +
var saudar = function() {
+  return 'Ola mundo';
+};
+ +

Ou, sua função pode ser pretendida a ser uma IIFE (Immediately Invoked Function Expression), qual é uma função que será em breve definida. Você vai precisar de um pouco mais de colchetes neste caso:

+ +
(function () {
+
+})();
+ +

Funçoes etiquetadas

+ +

Se usar labels, precisará providenciar um nome de função depois da  palavra function . Isto não funciona:

+ +
function Saudacao() {
+  alemao: function () {
+    return "Moin";
+  }
+}
+// SyntaxError: a função declaração requer um nome
+
+ +

Isso funciona ,veja o exemplo:

+ +
function Saudacao() {
+  alemao: function g() {
+    return "Moin";
+  }
+}
+ +

Métodos de Objetos

+ +

Se pretende criar um metodo para um objeto, voce precisa-rá criar um objeto (hehehe). A seguir uma sintaxe sem nome depois de function é válida.

+ +
var saudacao = {
+  alemao: function () {
+    return "Moin";
+  }
+};
+ +

Callback Sintaxe

+ +

Alem disso,cheque sua sintaxe usando callbacks. Colchetes e virgulas ficam facilmente atrapalhar e dificultar.

+ +
promessa.then(
+  function() {
+    console.log("sucesso");
+  });
+  function() {
+    console.log("erro");
+}
+// SyntaxError: function statement requires a name
+
+ +

O correto seria:

+ +
promise.then(
+  function() {
+    console.log("success");
+  },
+  function() {
+    console.log("error");
+  }
+);//sempre que abrir feche();
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/precision_range/index.html b/files/pt-br/web/javascript/reference/errors/precision_range/index.html new file mode 100644 index 0000000000..b45da23806 --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/precision_range/index.html @@ -0,0 +1,101 @@ +--- +title: 'RangeError: precision is out of range' +slug: Web/JavaScript/Reference/Errors/Precision_range +tags: + - Erro + - Erros + - JavaScript + - RangeError +translation_of: Web/JavaScript/Reference/Errors/Precision_range +--- +
{{jsSidebar("Errors")}}
+ +

A exceção JavaScript "precision is out of range" (precisão fora de alcance) ocorre quando um número que está fora do intervalo que vai de 0 à 20 (ou 21) foi passado para toFixed ou toPrecision.

+ +

Mensagem

+ +
RangeError: The number of fractional digits is out of range (Edge)
+RangeError: The precision is out of range (Edge)
+RangeError: precision {0} out of range (Firefox)
+RangeError: toExponential() argument must be between 0 and 20 (Chrome)
+RangeError: toFixed() digits argument must be between 0 and 20 (Chrome)
+RangeError: toPrecision() argument must be between 1 and 21 (Chrome)
+
+ +

Tipo de erro

+ +

{{jsxref("RangeError")}}

+ +

O que houve de errado?

+ +

Existe um argumento de precisão fora do intervalo em um desses métodos:

+ + + +

Po padrão, o intervalo permitido para os métodos acima é de 0 à 20 (ou 21). Todavia, a especificação ECMAScript nos permite extender o intervalo.

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
MétodoFirefox (SpiderMonkey)Chrome, Opera (V8)
{{jsxref("Number.prototype.toExponential()")}}0 to 1000 to 20
{{jsxref("Number.prototype.toFixed()")}}-20 to 1000 to 20
{{jsxref("Number.prototype.toPrecision()")}}1 to 1001 to 21
+ +

Exemplos

+ +

Casos inválidos

+ +
77.1234.toExponential(-1);  // RangeError
+77.1234.toExponential(101); // RangeError
+
+2.34.toFixed(-100);         // RangeError
+2.34.toFixed(1001);         // RangeError
+
+1234.5.toPrecision(-1);     // RangeError
+1234.5.toPrecision(101);    // RangeError
+
+ +

Casos válidos

+ +
77.1234.toExponential(4); // 7.7123e+1
+77.1234.toExponential(2); // 7.71e+1
+
+2.34.toFixed(1); // 2.3
+2.35.toFixed(1); // 2.4 (perceba que ele foi arredondado nesse caso)
+
+5.123456.toPrecision(5); // 5.1235
+5.123456.toPrecision(2); // 5.1
+5.123456.toPrecision(1); // 5
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/property_access_denied/index.html b/files/pt-br/web/javascript/reference/errors/property_access_denied/index.html new file mode 100644 index 0000000000..01bcf0009b --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/property_access_denied/index.html @@ -0,0 +1,42 @@ +--- +title: 'Error: Permission denied to access property "x"' +slug: Web/JavaScript/Reference/Errors/Property_access_denied +translation_of: Web/JavaScript/Reference/Errors/Property_access_denied +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
Error: Permission denied to access property "x"
+
+ +

Tipo de erro

+ +

{{jsxref("Error")}}.

+ +

O que houve de errado?

+ +

Tentativa de acessar um objeto no qual você não possui permissões. Provavelmente um {{HTMLElement("iframe")}} carregado de um dominio diferente no qual foi violado o same-origin policy.

+ +

Exemplos

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <iframe id="myframe" src="http://www1.w3c-test.org/common/blank.html"></iframe>
+    <script>
+      onload = function() {
+        console.log(frames[0].document);
+        // Error: Permission denied to access property "document"
+      }
+    </script>
+  </head>
+  <body></body>
+</html>
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/read-only/index.html b/files/pt-br/web/javascript/reference/errors/read-only/index.html new file mode 100644 index 0000000000..fa7770fbcf --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/read-only/index.html @@ -0,0 +1,81 @@ +--- +title: 'TypeError: "x" is read-only' +slug: Web/JavaScript/Reference/Errors/Read-only +tags: + - Erros + - JavaScript + - TypeError +translation_of: Web/JavaScript/Reference/Errors/Read-only +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
TypeError: "x" is read-only (Firefox)
+TypeError: 0 is read-only (Firefox)
+TypeError: Cannot assign to read only property 'x' of #<Object> (Chrome)
+TypeError: Cannot assign to read only property '0' of [object Array] (Chrome)
+
+ +

Tipo de Erro

+ +

{{jsxref("TypeError")}}

+ +

O que deu errado?

+ +

A variável global ou propriedade do objeto foi definida como propriedade somente-leitura. (Tecnicamente, esse é um dado de não-escrita.)

+ +

Esse erro ocorre apenas em código no strict mode. No modo não strict mode, essa atribuição é ignorada silenciosamente.

+ +

Exemplos

+ +

Casos inválidos

+ +

Propriedades somente-leitura não são super comuns, mas elas podem ser criadas utilizando {{jsxref("Object.defineProperty()")}} ou {{jsxref("Object.freeze()")}}.

+ +
'use strict';
+var obj = Object.freeze({nome: 'Elsa', pontuacao: 157});
+obj.pontuacao = 0;  // TypeError
+
+'use strict';
+Object.defineProperty(this, 'CONTADOR_PULMAO', {value: 2, writable: false});
+CONTADOR_PULMAO = 3;  // TypeError
+
+'use strict';
+var frozenArray = Object.freeze([0, 1, 2]);
+frozenArray[0]++;  // TypeError
+
+ +

Existem também algumas propriedades somente-leitura nativas do Javascript. Talvez você já tentou redefinir um constante matemática.

+ +
'use strict';
+Math.PI = 4;  // TypeError
+
+ +

Desculpe, você não pode fazer isso.

+ +

A variável global undefined também é somente-leitura, então você não pode silenciar o infame erro "undefined is not a function" fazendo isso:

+ +
'use strict';
+undefined = function() {};  // TypeError: "undefined" is read-only
+
+ +

Casos válidos

+ +
'use strict';
+var obj = Object.freeze({nome: 'Score', pontos: 157});
+obj = {nome: obj.nome, pontos: 0};   // substituindo com o novo objeto funciona
+
+'use strict';
+var CONTADOR_PULMAO = 2;  // uma `var` funciona, porque ela não é somente-leitura
+CONTADOR_PULMAO = 3;  // ok (anatomicamente improvável, porém...)
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/redeclared_parameter/index.html b/files/pt-br/web/javascript/reference/errors/redeclared_parameter/index.html new file mode 100644 index 0000000000..901557d13b --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/redeclared_parameter/index.html @@ -0,0 +1,60 @@ +--- +title: 'SyntaxError: redeclaration of formal parameter "x"' +slug: Web/JavaScript/Reference/Errors/Redeclared_parameter +tags: + - Erros +translation_of: Web/JavaScript/Reference/Errors/Redeclared_parameter +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
SyntaxError: Let/Const redeclaration (Edge)
+SyntaxError: redeclaration of formal parameter "x" (Firefox)
+SyntaxError: Identifier "x" has already been declared (Chrome)
+
+ +

Tipo de Erro

+ +

{{jsxref("SyntaxError")}}

+ +

O que deu errado?

+ +

O mesmo nome de variável ocorre como parâmetro da função e é então redeclarada atribuindo let no corpo da função. Redeclarando a mesma variável dentro da mesma função ou no escopo do bloco usando let não é permitido em JavaScript.

+ +

Exemplos

+ +

Neste caso, a variável "arg" redeclara o argumento.

+ +
function f(arg) {
+  let arg = 'foo';
+}
+
+// SyntaxError: redeclaration of formal parameter "arg"
+
+ +

Se você quiser mudar o valor de "arg" no corpo da função, você pode fazer, mas você não precisa declarar novamente a mesma variável. Em outras palavras: você pode omitir a palavra chave let. Se você quiser criar uma nova variável, você precisa renomea-la, pois isso conflita com o parâmetro da função.

+ +
function f(arg) {
+  arg = 'foo';
+}
+
+function f(arg) {
+  let bar = 'foo';
+}
+
+ +

Notas de compatibilidade

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/stmt_after_return/index.html b/files/pt-br/web/javascript/reference/errors/stmt_after_return/index.html new file mode 100644 index 0000000000..6c2ad3146a --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/stmt_after_return/index.html @@ -0,0 +1,74 @@ +--- +title: 'Warning: unreachable code after return statement' +slug: Web/JavaScript/Reference/Errors/Stmt_after_return +translation_of: Web/JavaScript/Reference/Errors/Stmt_after_return +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
Warning: unreachable code after return statement (Firefox)
+
+ +

Tipo de Erro

+ +

Warning

+ +

O que deu errado?

+ +

Codigo inacessível depois da declaração de retorno pode ocorrer nas seguintes situações:

+ + + +

Quando existe uma expressão após uma declaração válida de return, um warning é dado para indicar que o código depois da declaração return é inacessível, significando que ele pode nunca ser executado.

+ +

Porque eu devo usar ponto-e-virgula após declarações return? No caso de declarações return sem ponto-e-vírgula, ele pode deixar obscuro se o desenvolvedor quis usar o return na proxima linha, ou parar a execução e retornar. O warning indica que há uma ambiguidade no modo que a declaração return foi escrita.

+ +

Warnings não serão mostrado para declarações return sem ponto-e-vírgula nas seguintes situações:

+ + + +

Exemplos

+ +

Casos Inválidos

+ +
function f() {
+  var x = 3;
+  x += 4;
+  return x;   // return exits the function immediately
+  x -= 3;     // so this line will never run; it is unreachable
+}
+
+function f() {
+  return     // this is treated like `return;`
+    3 + 4;   // so the function returns, and this line is never reached
+}
+
+ +

Casos Válidos

+ +
function f() {
+  var x = 3;
+  x += 4;
+  x -= 3;
+  return x;  // OK: return after all other statements
+}
+
+function f() {
+  return 3 + 4  // OK: semicolon-less return with expression on the same line
+}
+
+ +

Ver também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/too_much_recursion/index.html b/files/pt-br/web/javascript/reference/errors/too_much_recursion/index.html new file mode 100644 index 0000000000..26637da662 --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/too_much_recursion/index.html @@ -0,0 +1,66 @@ +--- +title: 'InternalError: too much recursion' +slug: Web/JavaScript/Reference/Errors/Too_much_recursion +translation_of: Web/JavaScript/Reference/Errors/Too_much_recursion +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
Error: Out of stack space (Edge)
+InternalError: too much recursion (Firefox)
+RangeError: Maximum call stack size exceeded (Chrome)
+
+ +

Tipo de erro

+ +

{{jsxref("InternalError")}}.

+ +

O que deu errado?

+ +

Uma função que invoca a si mesma é chamada função recursiva. Assim que uma condição é atendida, a função para de se invocar. 

+ +

De certa forma, recursão é análoga a um loop. Ambos executam o mesmo código múltiplas vezes, e ambos exigem uma condição (para evitar um loop infinito ou, nesse caso, uma recursão infinita). Quando são feitas excessivas invocações, ou a função não possui uma condição para interromper a recursividade, este erro é lançado.

+ +

Exemplos

+ +

Esta função recursiva roda 10 vezes, como definido pela condição de saída.

+ +
function loop(x) {
+  if (x >= 10) // "x >= 10" é a condição de saída
+    return;
+
+  loop(x + 1); // o código recursivo em si
+}
+loop(0);
+ +

Mudar esta condição para um valor extremamente alto não vai funcionar:

+ +
function loop(x) {
+  if (x >= 1000000000000)
+    return;
+
+  loop(x + 1);
+}
+loop(0);
+
+// InternalError: too much recursion
+ +

A seguinte função recursiva não possui condição de saída. Assim, ela vai continuar se invocando indefinidamente (até que o erro seja lançado e a execução interrom).

+ +
function loop(x) {
+ // Não há condição de saída
+
+loop(x + 1); // Código recursivo
+}
+
+loop(0);
+
+// InternalError: too much recursion
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/undeclared_var/index.html b/files/pt-br/web/javascript/reference/errors/undeclared_var/index.html new file mode 100644 index 0000000000..a51d080828 --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/undeclared_var/index.html @@ -0,0 +1,62 @@ +--- +title: 'ReferenceError: Atribuição à variável não declarada "x"' +slug: Web/JavaScript/Reference/Errors/Undeclared_var +translation_of: Web/JavaScript/Reference/Errors/Undeclared_var +--- +
{{jsSidebar("Errors")}}
+ +

Message

+ +
ReferenceError: Atribuição à variável não declarada "x"(Firefox)
+ReferenceError: "x" não está definido (Chrome)
+ReferenceError: Variável indefinida em strict mode (Edge)
+
+ +

Tipo de erro

+ +

{{jsxref("ReferenceError")}} aviso em strict mode somente.

+ +

O que deu errado?

+ +

Um valor foi atribuído a uma variável não declarada. Em outras palavras, houve uma atribuição sem a palavra-chave var. Existem algumas diferenças entre as variáveis declaradas e não declaradas, o que pode levar a resultados inesperados e é por isso que o JavaScript apresenta um erro no modo estrito.

+ +

Três coisas a observar sobre as variáveis declaradas e não declaradas:

+ + + +

Para mais exemplos, veja a página de referência var.

+ +

Erros sobre atribuições de variáveis não declaradas ocorrem apenas em código de modo estrito. Em código não-estrito, eles são silenciosamente ignorados.

+ +

Examplos

+ +

Casos inválidos

+ +

neste caso, a variavel "bar" é uma variavel não declarada.

+ +
function foo() {
+  "use strict";
+  bar = true;
+}
+foo(); // ReferenceError: assignment to undeclared variable bar
+
+ +

Casos válidos

+ +

Para fazer uma variável declarada "bar", você pode adicionar a palavra-chave var na frente dele.

+ +
function foo() {
+  "use strict";
+  var bar = true;
+}
+foo();
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/undefined_prop/index.html b/files/pt-br/web/javascript/reference/errors/undefined_prop/index.html new file mode 100644 index 0000000000..a15985670b --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/undefined_prop/index.html @@ -0,0 +1,67 @@ +--- +title: 'ReferenceError: reference to undefined property "x"' +slug: Web/JavaScript/Reference/Errors/Undefined_prop +tags: + - Erros + - JavaScript + - Modo Restrito + - ReferenceError +translation_of: Web/JavaScript/Reference/Errors/Undefined_prop +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
ReferenceError: reference to undefined property "x" (Firefox)
+
+ +

Tipo de Erro

+ +

(Apenas no Firefox) O aviso {{jsxref("ReferenceError")}} é reportado somente se a preferência javascript.options.strict está definida como true.

+ +

O que está errado?

+ +
+
+
+
+

O script tentou acessar uma propriedade de objeto que não existe. Existem duas maneiras de acessar propriedades; veja a página de referência {{jsxref ("Operators / Property_Accessors", "property accessors", 0, 1)}} para saber mais sobre eles.

+
+
+
+
+ +

Exemplos

+ +

Errado

+ +

Neste caso, a propriedade bar é uma propriedade não definida, assim, ocorrerá um ReferenceError.

+ +
var foo = {};
+foo.bar; // ReferenceError: reference to undefined property "bar"
+
+ +

Certo

+ +
+

Para evitar o erro, você precisa adicionar uma definição de bar ao objeto ou verificar a existência da propriedade bar antes de tentar acessá-la; Uma maneira de fazer isso é usar o método {{jsxref ("Object.prototype.hasOwnProperty ()")}}, desta forma:

+
+ +
var foo = {};
+
+// Define a propriedade bar
+
+foo.bar = 'moon';
+console.log(foo.bar); // "moon"
+
+// Teste para ter certeza se bar existe antes de acessa-lo
+
+if (foo.hasOwnProperty('bar')) {
+  console.log(foo.bar);
+}
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/unexpected_token/index.html b/files/pt-br/web/javascript/reference/errors/unexpected_token/index.html new file mode 100644 index 0000000000..7455321080 --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/unexpected_token/index.html @@ -0,0 +1,51 @@ +--- +title: 'SyntaxError: Unexpected token' +slug: Web/JavaScript/Reference/Errors/Unexpected_token +tags: + - Erro de Sintaxe + - Erros + - JavaScript + - SyntaxError +translation_of: Web/JavaScript/Reference/Errors/Unexpected_token +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
SyntaxError: expected expression, got "x"
+SyntaxError: expected property name, got "x"
+SyntaxError: expected target, got "x"
+SyntaxError: expected rest argument name, got "x"
+SyntaxError: expected closing parenthesis, got "x"
+SyntaxError: expected '=>' after argument list, got "x"
+
+ +

Tipo de erro

+ +

{{jsxref("SyntaxError")}}

+ +

O que deu errado?

+ +

Uma construção específica da linguagem era esperada, mas algo não foi fornecido. Isto deve ser um simples erro de digitação.

+ +

Exemplos

+ +

Expressão esperada

+ +

Por exemplo, quando funções são chamadas, vírgulas sem um valor na sequência não são permitidas. O JavaScript esperarará outro argumento, como pode ser qualquer expressão.

+ +
Math.max(2, 42,);
+// SyntaxError: expected expression, got ')'
+
+ +

O correto é omitir a vírgula ou adicionar outro argumento:

+ +
Math.max(2, 42);
+Math.max(2, 42, 13 + 37);
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/unexpected_type/index.html b/files/pt-br/web/javascript/reference/errors/unexpected_type/index.html new file mode 100644 index 0000000000..8e05992723 --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/unexpected_type/index.html @@ -0,0 +1,67 @@ +--- +title: 'TypeError: "x" is (not) "y"' +slug: Web/JavaScript/Reference/Errors/Unexpected_type +tags: + - Erros + - JavaScript + - TypeError +translation_of: Web/JavaScript/Reference/Errors/Unexpected_type +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
Tipo do erro: "x" é (não é) "y"
+
+Exemplos:
+Tipo do erro: "x" é indefinido
+Tipo do erro: "x" é nulo
+Tipo do erro: "x" indefinido" não é um objeto
+Tipo do erro: "x" não é um objeto ou é nulo
+Tipo do erro: "x" não é um símbolo
+
+ +

Tipo de erro

+ +

{{jsxref("TypeError")}}.

+ +

O que deu errado?

+ +

Houve um tipo inesperado. Isso ocorre muitas vezes com valores {{jsxref("undefined")}} ou {{jsxref("null")}}.

+ +

Além disso, certos métodos, tais como {{jsxref("Object.create()")}} ou {{jsxref("Symbol.keyFor()")}}, requerem um tipo específico, que deve ser fornecido.

+ +

Exemplos

+ +

Casos inválidos

+ +
// casos undefined e null nos quais o método substring não vai funcionar
+var foo = undefined;
+foo.substring(1); // TypeError: foo is undefined
+
+var foo = null;
+foo.substring(1); // TypeError: foo is null
+
+
+// Certos métodos podem precisar de um tipo específico
+var foo = {}
+Symbol.keyFor(foo); // TypeError: foo is not a symbol
+
+var foo = 'bar'
+Object.create(foo); // TypeError: "foo" is not an object or null
+
+ +

Consertando o problema

+ +

Para consertar o pointeiro nulo para valores undefined ou null,  você pode utilizar o operador typeof , por exemplo.

+ +
if (typeof foo !== 'undefined') {
+  // Agora nós sabemos que foo está definido, então podemos prosseguir.
+}
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/errors/unterminated_string_literal/index.html b/files/pt-br/web/javascript/reference/errors/unterminated_string_literal/index.html new file mode 100644 index 0000000000..831d9842e2 --- /dev/null +++ b/files/pt-br/web/javascript/reference/errors/unterminated_string_literal/index.html @@ -0,0 +1,63 @@ +--- +title: 'SyntaxError: unterminated string literal' +slug: Web/JavaScript/Reference/Errors/Unterminated_string_literal +translation_of: Web/JavaScript/Reference/Errors/Unterminated_string_literal +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
SyntaxError: unterminated string literal
+
+ +

Tipo de Erro

+ +

{{jsxref("SyntaxError")}}

+ +

O que deu errado?

+ +

Há uma {{jsxref("String")}} não finalizada em algum lugar do código. String literais devem se fechadas com aspas simples (') ou duplas (") . O JavaScript não faz distinção entre strings com aspas simples ou aspas duplas. As sequências de escape trabalham com strings criadas tanto com aspas simples, quanto com aspas duplas. Para consertar este erro, verifique se:

+ + + +

Exemplos

+ +

Múltiplas linhas

+ +

Você não pode dividir sua string em múltiplas linhas em Javascript:

+ +
var longString = "This is a very long string which needs
+                  to wrap across multiple lines because
+                  otherwise my code is unreadable.";
+// SyntaxError: unterminated string literal
+ +

Ao invés disso, você deve utilizar o operador + operator, uma barra invertida(\), ou modelos literais. Uma forma de uso do operador +, seria assim:

+ +
var longString = "This is a very long string which needs " +
+                 "to wrap across multiple lines because " +
+                 "otherwise my code is unreadable.";
+
+ +

Ou você pode usar uma barra invertida ("\") ao final de cada linha para indicar que a string continuará na próxima linha. Certifique-se de que não há espaço ou qualquer outro caractere após a barra invertida (excento quando for uma quebra de linha), ou como indentação; caso contrário, não funcionará. Esta forma ficaria assim:

+ +
var longString = "This is a very long string which needs \
+to wrap across multiple lines because \
+otherwise my code is unreadable.";
+
+ +

Uma outra possibilidade é usar um  modelo literal, que é suportado pelos ambientes ECMAScript 2015:

+ +
var longString = `This is a very long string which needs
+                  to wrap across multiple lines because
+                  otherwise my code is unreadable.`;
+ +

Veja também

+ + -- cgit v1.2.3-54-g00ecf