From 2c2df5ea01eb5cd8b9ea226b2869337e59c5fe3e Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:50:24 +0100 Subject: unslug pt-pt: move --- .../web/javascript/reference/about/index.html | 52 ++ .../deprecated_and_obsolete_features/index.html | 289 ++++++++++ .../index.html" | 113 ---- .../errors/unnamed_function_statement/index.html | 113 ++++ .../bloco/index.html" | 116 ---- .../for/index.html" | 145 ----- .../index.html" | 150 ------ .../return/index.html" | 148 ----- .../throw/index.html" | 271 ---------- .../reference/funcionalidades_obsoletas/index.html | 289 ---------- .../reference/funcoes/arguments/index.html | 228 -------- .../reference/funcoes/funcoes_seta/index.html | 399 -------------- .../web/javascript/reference/funcoes/index.html | 594 --------------------- .../reference/funcoes/parametros_rest/index.html | 234 -------- .../reference/functions/arguments/index.html | 228 ++++++++ .../reference/functions/arrow_functions/index.html | 399 ++++++++++++++ .../web/javascript/reference/functions/index.html | 594 +++++++++++++++++++++ .../reference/functions/rest_parameters/index.html | 234 ++++++++ .../asyncfunction/prototype/index.html | 55 -- .../global_objects/number/prototype/index.html | 131 ----- .../global_objects/object/prototype/index.html | 199 ------- .../operadores/fun\303\247\303\243o/index.html" | 139 ----- .../web/javascript/reference/operadores/index.html | 309 ----------- .../operadores/operador_virgula/index.html | 94 ---- .../operadores/precedencia_operador/index.html | 461 ---------------- .../reference/operators/comma_operator/index.html | 94 ++++ .../reference/operators/function/index.html | 139 +++++ .../web/javascript/reference/operators/index.html | 309 +++++++++++ .../operators/operator_precedence/index.html | 461 ++++++++++++++++ .../web/javascript/reference/sobre/index.html | 52 -- .../reference/statements/block/index.html | 116 ++++ .../javascript/reference/statements/for/index.html | 145 +++++ .../web/javascript/reference/statements/index.html | 150 ++++++ .../reference/statements/return/index.html | 148 +++++ .../reference/statements/throw/index.html | 271 ++++++++++ 35 files changed, 3742 insertions(+), 4127 deletions(-) create mode 100644 files/pt-pt/web/javascript/reference/about/index.html create mode 100644 files/pt-pt/web/javascript/reference/deprecated_and_obsolete_features/index.html delete mode 100644 "files/pt-pt/web/javascript/reference/errors/declara\303\247\303\243o_fun\303\247\303\243o_sem_nome/index.html" create mode 100644 files/pt-pt/web/javascript/reference/errors/unnamed_function_statement/index.html delete mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/bloco/index.html" delete mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/for/index.html" delete mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/index.html" delete mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/return/index.html" delete mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/throw/index.html" delete mode 100644 files/pt-pt/web/javascript/reference/funcionalidades_obsoletas/index.html delete mode 100644 files/pt-pt/web/javascript/reference/funcoes/arguments/index.html delete mode 100644 files/pt-pt/web/javascript/reference/funcoes/funcoes_seta/index.html delete mode 100644 files/pt-pt/web/javascript/reference/funcoes/index.html delete mode 100644 files/pt-pt/web/javascript/reference/funcoes/parametros_rest/index.html create mode 100644 files/pt-pt/web/javascript/reference/functions/arguments/index.html create mode 100644 files/pt-pt/web/javascript/reference/functions/arrow_functions/index.html create mode 100644 files/pt-pt/web/javascript/reference/functions/index.html create mode 100644 files/pt-pt/web/javascript/reference/functions/rest_parameters/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/asyncfunction/prototype/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/prototype/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/object/prototype/index.html delete mode 100644 "files/pt-pt/web/javascript/reference/operadores/fun\303\247\303\243o/index.html" delete mode 100644 files/pt-pt/web/javascript/reference/operadores/index.html delete mode 100644 files/pt-pt/web/javascript/reference/operadores/operador_virgula/index.html delete mode 100644 files/pt-pt/web/javascript/reference/operadores/precedencia_operador/index.html create mode 100644 files/pt-pt/web/javascript/reference/operators/comma_operator/index.html create mode 100644 files/pt-pt/web/javascript/reference/operators/function/index.html create mode 100644 files/pt-pt/web/javascript/reference/operators/index.html create mode 100644 files/pt-pt/web/javascript/reference/operators/operator_precedence/index.html delete mode 100644 files/pt-pt/web/javascript/reference/sobre/index.html create mode 100644 files/pt-pt/web/javascript/reference/statements/block/index.html create mode 100644 files/pt-pt/web/javascript/reference/statements/for/index.html create mode 100644 files/pt-pt/web/javascript/reference/statements/index.html create mode 100644 files/pt-pt/web/javascript/reference/statements/return/index.html create mode 100644 files/pt-pt/web/javascript/reference/statements/throw/index.html (limited to 'files/pt-pt/web/javascript/reference') diff --git a/files/pt-pt/web/javascript/reference/about/index.html b/files/pt-pt/web/javascript/reference/about/index.html new file mode 100644 index 0000000000..3b2a79ac32 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/about/index.html @@ -0,0 +1,52 @@ +--- +title: Sobre a referência de JavaScript +slug: Web/JavaScript/Reference/Sobre +tags: + - JavaScript +translation_of: Web/JavaScript/Reference/About +--- +
{{JsSidebar}}
+ +

The JavaScript reference serves as a repository of facts about the JavaScript language. The entire language is described here in detail. As you write JavaScript code, you'll refer to these pages often (thus the title "JavaScript reference"). If you're learning JavaScript, or need help understanding some of its capabilities or features, check out the JavaScript guide.

+ +

The JavaScript language is intended to be used within some larger environment, be it a browser, server-side scripts, or similar. For the most part, this reference attempts to be environment-agnostic and does not target a web browser environment.

+ +

Onde encontrar informação sobre JavaScript

+ +

JavaScript documentation of core language features (pure ECMAScript, for the most part) includes the following:

+ + + +

If you are new to JavaScript, start with the guide. Once you have a firm grasp of the fundamentals, you can use the reference to get more details on individual objects and language constructs.

+ +

Estrutura da referência

+ +

In the JavaScript reference you can find the following chapters:

+ +
+
Standard built-in objects
+
This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.
+
Statements and declarations
+
JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.
+
Expressions and operators
+
This chapter documents all the JavaScript language operators, expressions and keywords.
+
Functions
+
Chapter about JavaScript functions.
+
Classes
+
Chapter about JavaScript classes introduced in ECMAScript 6.
+
Errors
+
Chapter about specific errors, exceptions and warnings thrown by JavaScript.
+
New in JavaScript
+
Chapter about JavaScript version history.
+
+ +

Mais páginas de referência

+ + diff --git a/files/pt-pt/web/javascript/reference/deprecated_and_obsolete_features/index.html b/files/pt-pt/web/javascript/reference/deprecated_and_obsolete_features/index.html new file mode 100644 index 0000000000..9d0ae63c62 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/deprecated_and_obsolete_features/index.html @@ -0,0 +1,289 @@ +--- +title: Funcionalidades obsoletas +slug: Web/JavaScript/Reference/Funcionalidades_obsoletas +tags: + - JavaScript + - Obsoleto +translation_of: Web/JavaScript/Reference/Deprecated_and_obsolete_features +--- +
{{JsSidebar("More")}}
+ +

Esta página lista as funcionalidades de JavaScript que estão obsoletas (ou seja, ainda disponíveis, mas planeadas para remoção) e obsoletas (isto é, não são mais utilizáveis).

+ +

Funcionalidades obsoletas

+ +

Estas funcionalidades obsoletas ainda podem ser utilziadas, mas devem ser utilizadas ​​com cuidado, pois espera-se que estas sejam removidas inteiramente no futuro. Deverá trabalhar para remover a utilização das mesmas do seu código..

+ +

Propriedades de RegExp

+ +

The following properties are deprecated. This does not affect their use in {{jsxref("String.replace", "replacement strings", "", 1)}}:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropriedadesDescrição
{{jsxref("RegExp.n", "$1-$9")}} +

Parenthesized substring matches, if any.
+ Warning: Using these properties can result in problems, since browser extensions can modify them. Avoid them!

+
{{jsxref("RegExp.input", "$_")}}See input.
{{jsxref("RegExp.multiline", "$*")}}See multiline.
{{jsxref("RegExp.lastMatch", "$&")}}See lastMatch.
{{jsxref("RegExp.lastParen", "$+")}}See lastParen.
{{jsxref("RegExp.leftContext", "$`")}}See leftContext.
{{jsxref("RegExp.rightContext", "$'")}}See rightContext.
{{jsxref("RegExp.input", "input")}}The string against which a regular expression is matched.
{{jsxref("RegExp.lastMatch", "lastMatch")}}The last matched characters.
{{jsxref("RegExp.lastParen", "lastParen")}}The last parenthesized substring match, if any.
{{jsxref("RegExp.leftContext", "leftContext")}}The substring preceding the most recent match.
{{jsxref("RegExp.rightContext", "rightContext")}}The substring following the most recent match.
+ +

The following are now properties of RegExp instances, no longer of the RegExp object:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropriedadesDescrição
{{jsxref("RegExp.global", "global")}}Whether or not to test the regular expression against all possible matches in a string, or only against the first.
{{jsxref("RegExp.ignoreCase", "ignoreCase")}}Whether or not to ignore case while attempting a match in a string.
{{jsxref("RegExp.lastIndex", "lastIndex")}}The index at which to start the next match.
{{jsxref("RegExp.multiline", "multiline")}}Whether or not to search in strings across multiple lines.
{{jsxref("RegExp.source", "source")}}The text of the pattern.
+ +

Métodos de egExp

+ + + +

Propriedades de Function

+ + + +

Gerador de Legacy

+ + + +

Iterator

+ + + +

Métodos de Object

+ + + +

Métodos de Date

+ + + +

Functions

+ + + +

Proxy

+ + + +

Sequências de Escape

+ + + +

Métodos de String

+ + + +

Funcionalidades removidas

+ +

Estas funcionalidades obsoletas foram totalmente removidas do JavaScript e não podem mais ser utilizadas a partir da versão indicada do JavaScript.

+ +

Object

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyDescription
{{jsxref("Global_Objects/Object/count", "__count__")}}Returns the number of enumerable properties directly on a user-defined object.
{{jsxref("Global_Objects/Object/Parent", "__parent__")}}Points to an object's context.
{{jsxref("Global_Objects/Object/eval", "Object.prototype.eval()")}}Evaluates a string of JavaScript code in the context of the specified object.
{{jsxref("Object.observe()")}}Asynchronously observing the changes to an object.
{{jsxref("Object.unobserve()")}}Remove observers.
{{jsxref("Object.getNotifier()")}}Creates an object that allows to synthetically trigger a change.
+ +

Function

+ + + + + + + + + + + + +
PropertyDescription
{{jsxref("Global_Objects/Function/arity", "arity")}}Number of formal arguments.
+ +

Array

+ + + + + + + + + + + + + + + + +
PropertyDescription
{{jsxref("Array.observe()")}}Asynchronously observing changes to Arrays.
{{jsxref("Array.unobserve()")}}Remove observers.
+ +

Number

+ + + +

ParallelArray

+ + + +

Statements

+ + + +

E4X

+ +

See E4X for more information.

+ +

Variáveis Sharp

+ +

Consulte Sharp variables in JavaScript para mais informação.

diff --git "a/files/pt-pt/web/javascript/reference/errors/declara\303\247\303\243o_fun\303\247\303\243o_sem_nome/index.html" "b/files/pt-pt/web/javascript/reference/errors/declara\303\247\303\243o_fun\303\247\303\243o_sem_nome/index.html" deleted file mode 100644 index a747257379..0000000000 --- "a/files/pt-pt/web/javascript/reference/errors/declara\303\247\303\243o_fun\303\247\303\243o_sem_nome/index.html" +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: 'Erro de sintaxe: declaração de função precisa de um nome' -slug: Web/JavaScript/Reference/Errors/declaração_função_sem_nome -translation_of: Web/JavaScript/Reference/Errors/Unnamed_function_statement ---- -
{{jsSidebar("Errors")}}
- -

Mensagem

- -
Syntax Error: Expected identifier (Edge)
-SyntaxError: function statement requires a name [Firefox]
-SyntaxError: Unexpected token ( [Chrome]
-
- -

Tipo de erro

- -

{{jsxref("SyntaxError")}}

- -

O que correu mal?

- -

Existe uma declaração de função no código que precisa de um nome. Você deve verficiar como as funções são definidas e se é necessário indicar um nome para a função

- -

Existe uma declaração de função no código que requer um nome. Você precisará verificar como as funções são definidas e se você precisa fornecer um nome para a função, ou 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 esta colocado corretamente neste contexto.

- -

Exemplos

- -

Declarações vs Expressões

- -

Uma declaração de função precisa de um nome, o código seguinte não funciona:

- -
function () {
-  return 'Hello world';
-}
-// SyntaxError: function statement requires a name
-
- -

É possível usar uma expressão de função (atribuição) como alternativa:

- -
var greet = function() {
-  return 'Hello world';
-};
- -

Ou, a sua função é talvez destinada a ser uma IIFE (Expressão de Função Invocada Imediatamente), que é uma função que é executada assim que é definida. Serão precisos mais alguns parêntises neste caso:

- -
(function () {
-
-})();
- -

Funções com nome

- -

Se você está a usar uma função com identificador, ainda precisará fornecer um nome de função após a palavra-chave da função. O código seguinte não funciona:

- -
function Greeter() {
-  german: function () {
-    return "Moin";
-  }
-}
-// SyntaxError: function statement requires a name
-
- -

O código seguinte irá funcionar por exemplo:

- -
function Greeter() {
-  german: function g() {
-    return "Moin";
-  }
-}
- -

Métodos de objectos

- -

Se você pretendia criar um método de um objeto, você precisará criar um objeto. A sintaxe a seguir sem um nome após a palavra-chave function é válida.

- -
var greeter = {
-  german: function () {
-    return "Moin";
-  }
-};
- -

Sintaxe de Callback

- -

Além disso, verifique a sintaxe ao usar callbacks. Parêntisis e virgurlas podem facilmente se tornar complicados.

- -
promise.then(
-  function() {
-    console.log("success");
-  });
-  function() {
-    console.log("error");
-}
-// SyntaxError: function statement requires a name
-
- -

:

- -
promise.then(
-  function() {
-    console.log("success");
-  },
-  function() {
-    console.log("error");
-  }
-);
-
- -

Veja também

- - diff --git a/files/pt-pt/web/javascript/reference/errors/unnamed_function_statement/index.html b/files/pt-pt/web/javascript/reference/errors/unnamed_function_statement/index.html new file mode 100644 index 0000000000..a747257379 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/errors/unnamed_function_statement/index.html @@ -0,0 +1,113 @@ +--- +title: 'Erro de sintaxe: declaração de função precisa de um nome' +slug: Web/JavaScript/Reference/Errors/declaração_função_sem_nome +translation_of: Web/JavaScript/Reference/Errors/Unnamed_function_statement +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
Syntax Error: Expected identifier (Edge)
+SyntaxError: function statement requires a name [Firefox]
+SyntaxError: Unexpected token ( [Chrome]
+
+ +

Tipo de erro

+ +

{{jsxref("SyntaxError")}}

+ +

O que correu mal?

+ +

Existe uma declaração de função no código que precisa de um nome. Você deve verficiar como as funções são definidas e se é necessário indicar um nome para a função

+ +

Existe uma declaração de função no código que requer um nome. Você precisará verificar como as funções são definidas e se você precisa fornecer um nome para a função, ou 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 esta colocado corretamente neste contexto.

+ +

Exemplos

+ +

Declarações vs Expressões

+ +

Uma declaração de função precisa de um nome, o código seguinte não funciona:

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

É possível usar uma expressão de função (atribuição) como alternativa:

+ +
var greet = function() {
+  return 'Hello world';
+};
+ +

Ou, a sua função é talvez destinada a ser uma IIFE (Expressão de Função Invocada Imediatamente), que é uma função que é executada assim que é definida. Serão precisos mais alguns parêntises neste caso:

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

Funções com nome

+ +

Se você está a usar uma função com identificador, ainda precisará fornecer um nome de função após a palavra-chave da função. O código seguinte não funciona:

+ +
function Greeter() {
+  german: function () {
+    return "Moin";
+  }
+}
+// SyntaxError: function statement requires a name
+
+ +

O código seguinte irá funcionar por exemplo:

+ +
function Greeter() {
+  german: function g() {
+    return "Moin";
+  }
+}
+ +

Métodos de objectos

+ +

Se você pretendia criar um método de um objeto, você precisará criar um objeto. A sintaxe a seguir sem um nome após a palavra-chave function é válida.

+ +
var greeter = {
+  german: function () {
+    return "Moin";
+  }
+};
+ +

Sintaxe de Callback

+ +

Além disso, verifique a sintaxe ao usar callbacks. Parêntisis e virgurlas podem facilmente se tornar complicados.

+ +
promise.then(
+  function() {
+    console.log("success");
+  });
+  function() {
+    console.log("error");
+}
+// SyntaxError: function statement requires a name
+
+ +

:

+ +
promise.then(
+  function() {
+    console.log("success");
+  },
+  function() {
+    console.log("error");
+  }
+);
+
+ +

Veja também

+ + diff --git "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/bloco/index.html" "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/bloco/index.html" deleted file mode 100644 index a3104dbeae..0000000000 --- "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/bloco/index.html" +++ /dev/null @@ -1,116 +0,0 @@ ---- -title: Bloco (block) -slug: Web/JavaScript/Reference/Extratos_e_declarações/bloco -tags: - - Declaração - - Funcionalidade de Linguagem - - JavaScript - - Referencia -translation_of: Web/JavaScript/Reference/Statements/block ---- -
Bloco {{jsSidebar("Statements")}}
- -

Uma declaralção bloco (ou declaração composto em outras linguagens) é utilizada para agrupar zero ou mais declarações. O bloco é delimitado por um par de chavetas (“chavetas { }”) e opcionalmente poderá ser {{jsxref("Statements/label", "labelled", "", 1)}}:

- -
{{EmbedInteractiveExample("pages/js/statement-block.html", "taller")}}
- - - -

Sintaxe

- -

Declaração de Bloco

- -
{
-  StatementList
-}
-
- -

Declaração de Bloco Etiquetado

- -
LabelIdentifier: {
-  StatementList
-}
-
- -
-
StatementList
-
Statements grouped within the block statement.
-
LabelIdentifier
-
An optional {{jsxref("Statements/label", "label", "", 1)}} for visual identification or as a target for {{jsxref("Statements/break", "break")}}.
-
- -

Descrição

- -

The block statement is often called compound statement in other languages. It allows you to use multiple statements where JavaScript expects only one statement. Combining statements into blocks is a common practice in JavaScript. The opposite behavior is possible using an empty statement, where you provide no statement, although one is required.

- -

Blocks are commonly used in association with {{jsxref("Statements/if...else", "if...else")}} and {{jsxref("Statements/for", "for")}} statements.

- -

Block Scoping Rules

- -

With var or function declaration in non-strict mode

- -

Variables declared with var or created by function declarations in non-strict mode do not have block scope. Variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. For example:

- -
var x = 1;
-{
-  var x = 2;
-}
-console.log(x); // logs 2
-
- -

This logs 2 because the var x statement within the block is in the same scope as the var x statement before the block.

- -

In non-strict code, function declarations inside blocks behave strangely. Do not use them.

- -

With let, const or function declaration in strict mode

- -

By contrast, identifiers declared with {{jsxref("Statements/let", "let")}} and {{jsxref("Statements/const", "const")}} do have block scope:

- -
let x = 1;
-{
-  let x = 2;
-}
-console.log(x); // logs 1
- -

The x = 2 is limited in scope to the block in which it was defined.

- -

The same is true of const:

- -
const c = 1;
-{
-  const c = 2;
-}
-console.log(c); // logs 1 and does not throw SyntaxError...
- -

Note that the block-scoped const c = 2 does not throw a SyntaxError: Identifier 'c' has already been declared because it can be declared uniquely within the block.

- -

In strict mode, starting with ES2015, functions inside blocks are scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

- -

Especificações

- - - - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-block', 'Block statement')}}
- -

Compatibilidade de navegador

- - - -

{{Compat("javascript.statements.block")}}

- -

Consulte também

- - diff --git "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/for/index.html" "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/for/index.html" deleted file mode 100644 index ac7586e98b..0000000000 --- "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/for/index.html" +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: for -slug: Web/JavaScript/Reference/Extratos_e_declarações/for -tags: - - Declaração - - Funcionalidade de Linguagem - - JavaScript - - Loop - - Referencia - - Repetição - - for -translation_of: Web/JavaScript/Reference/Statements/for ---- -
{{jsSidebar("Statements")}}
- -

A declaração "for" cria uma repetição (loop) que consiste de três expressões opcionais, entre parênteses e separados por ponto e vírgula, seguido de uma declaração (normalmente bdeclaraçãod e bloco (block)) para ser executada na repetição.

- -
{{EmbedInteractiveExample("pages/js/statement-for.html")}}
- - - -

Sintaxe

- -
for ([initialization]; [condition]; [final-expression])
-   statement
- -
-
initialization
-
An expression (including assignment expressions) or variable declaration evaluated once before the loop begins. Typically used to initialize a counter variable. This expression may optionally declare new variables with var or let keywords. Variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in. Variables declared with let are local to the statement.
-
The result of this expression is discarded.
-
condition
-
An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following the for construct.
-
final-expression
-
An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable.
-
statement
-
A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a {{jsxref("Statements/block", "block", "", 0)}} statement ({ ... }) to group those statements. To execute no statement within the loop, use an {{jsxref("Statements/empty", "empty", "", 0)}} statement (;).
-
- -

Exemplos

- -

Using for

- -

The following for statement starts by declaring the variable i and initializing it to 0. It checks that i is less than nine, performs the two succeeding statements, and increments i by 1 after each pass through the loop.

- -
for (let i = 0; i < 9; i++) {
-   console.log(i);
-   // more statements
-}
-
- -

Optional for expressions

- -

All three expressions in the head of the for loop are optional.

- -

For example, in the initialization block it is not required to initialize variables:

- -
var i = 0;
-for (; i < 9; i++) {
-    console.log(i);
-    // more statements
-}
-
- -

Like the initialization block, the condition block is also optional. If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop.

- -
for (let i = 0;; i++) {
-   console.log(i);
-   if (i > 3) break;
-   // more statements
-}
- -

You can also omit all three blocks. Again, make sure to use a {{jsxref("Statements/break", "break")}} statement to end the loop and also modify (increase) a variable, so that the condition for the break statement is true at some point.

- -
var i = 0;
-
-for (;;) {
-  if (i > 3) break;
-  console.log(i);
-  i++;
-}
-
- -

Using for without a statement

- -

The following for cycle calculates the offset position of a node in the final-expression section, and therefore it does not require the use of a statement section, a semicolon is used instead.

- -
function showOffsetPos(sId) {
-
-  var nLeft = 0, nTop = 0;
-
-  for (
-
-    var oItNode = document.getElementById(sId); /* initialization */
-
-    oItNode; /* condition */
-
-    nLeft += oItNode.offsetLeft, nTop += oItNode.offsetTop, oItNode = oItNode.offsetParent /* final-expression */
-
-  ); /* semicolon */
-
-  console.log('Offset position of \'' + sId + '\' element:\n left: ' + nLeft + 'px;\n top: ' + nTop + 'px;');
-
-}
-
-/* Example call: */
-
-showOffsetPos('content');
-
-// Output:
-// "Offset position of "content" element:
-// left: 0px;
-// top: 153px;"
- -
Note: This is one of the few cases in JavaScript where the semicolon is mandatory. Indeed, without the semicolon the line that follows the cycle declaration will be considered a statement.
- -

Especificações

- - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-for-statement', 'for statement')}}
- -

Compatibilidade de navegador

- - - -

{{Compat("javascript.statements.for")}}

- -

Consulte também

- - diff --git "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/index.html" "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/index.html" deleted file mode 100644 index af841906a1..0000000000 --- "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/index.html" +++ /dev/null @@ -1,150 +0,0 @@ ---- -title: Declarações e instruções -slug: Web/JavaScript/Reference/Extratos_e_declarações -tags: - - JavaScript - - Referencia - - declarações - - instruções -translation_of: Web/JavaScript/Reference/Statements ---- -
{{jsSidebar("Statements")}}
- -

JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.

- -

Declarações e instruções por categoria

- -

For an alphabetical listing see the sidebar on the left.

- -

Controlo de Fluxo

- -
-
{{jsxref("Statements/block", "Block")}}
-
A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets.
-
{{jsxref("Statements/break", "break")}}
-
Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
-
{{jsxref("Statements/continue", "continue")}}
-
Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
-
{{jsxref("Statements/Empty", "Empty")}}
-
An empty statement is used to provide no statement, although the JavaScript syntax would expect one.
-
{{jsxref("Statements/if...else", "if...else")}}
-
Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.
-
{{jsxref("Statements/switch", "switch")}}
-
Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.
-
{{jsxref("Statements/throw", "throw")}}
-
Throws a user-defined exception.
-
{{jsxref("Statements/try...catch", "try...catch")}}
-
Marks a block of statements to try, and specifies a response, should an exception be thrown.
-
- -

Declarações

- -
-
{{jsxref("Statements/var", "var")}}
-
Declares a variable, optionally initializing it to a value.
-
{{jsxref("Statements/let", "let")}}
-
Declares a block scope local variable, optionally initializing it to a value.
-
{{jsxref("Statements/const", "const")}}
-
Declares a read-only named constant.
-
- -

Funções e classes

- -
-
{{jsxref("Statements/function", "function")}}
-
Declara as funções com parâmetros especificados.
-
{{jsxref("Statements/function*", "function*")}}
-
Generators functions enable writing iterators more easily.
-
{{jsxref("Statements/async_function", "async function")}}
-
Declares an async function with the specified parameters.
-
{{jsxref("Statements/return", "return")}}
-
Specifies the value to be returned by a function.
-
{{jsxref("Statements/class", "class")}}
-
Declara uma Classe.
-
- -

Iterações

- -
-
{{jsxref("Statements/do...while", "do...while")}}
-
Creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
-
{{jsxref("Statements/for", "for")}}
-
Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
-
{{deprecated_inline}} {{non-standard_inline()}} {{jsxref("Statements/for_each...in", "for each...in")}}
-
Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.
-
{{jsxref("Statements/for...in", "for...in")}}
-
Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
-
{{jsxref("Statements/for...of", "for...of")}}
-
Iterates over iterable objects (including {{jsxref("Global_Objects/Array","arrays","","true")}}, array-like objects, iterators and generators), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
-
{{jsxref("Statements/while", "while")}}
-
Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.
-
- -

Outros

- -
-
{{jsxref("Statements/debugger", "debugger")}}
-
Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.
-
{{jsxref("Statements/export", "export")}}
-
Used to export functions to make them available for imports in external modules, another scripts.
-
{{jsxref("Statements/import", "import")}}
-
Used to import functions exported from an external module, another script.
-
import.meta
-
A meta-property exposing context-specific metadata to a JavaScript module.
-
{{jsxref("Statements/label", "label")}}
-
Provides a statement with an identifier that you can refer to using a break or continue statement.
-
- -
-
{{deprecated_inline}} {{jsxref("Statements/with", "with")}}
-
Extends the scope chain for a statement.
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1', '#sec-12', 'Statements')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES3', '#sec-12', 'Statements')}}{{Spec2('ES3')}} 
{{SpecName('ES5.1', '#sec-12', 'Statements')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ES6')}}New: function*, let, for...of, yield, class
{{SpecName('ESDraft', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade de navegador

- - - -

{{Compat("javascript.statements")}}

- -

Consultar também

- - diff --git "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/return/index.html" "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/return/index.html" deleted file mode 100644 index 6cec134992..0000000000 --- "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/return/index.html" +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: return -slug: Web/JavaScript/Reference/Extratos_e_declarações/return -tags: - - Declaração - - JavaScript -translation_of: Web/JavaScript/Reference/Statements/return ---- -
{{jsSidebar("Statements")}}
- -

The return statement ends function execution and specifies a value to be returned to the function caller.

- -

Sintaxe

- -
return [[expression]]; 
- -
-
expression
-
The expression whose value is to be returned. If omitted, undefined is returned instead.
-
- -

Descrição

- -

When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, x, where x is a number.

- -
function square(x) {
-   return x * x;
-}
-var demo = square(3);
-// demo will equal 9
-
- -

If the value is omitted, undefined is returned instead.

- -

The following return statements all break the function execution:

- -
return;
-return true;
-return false;
-return x;
-return x + y / 3;
-
- -

Inserção Automática de Ponto e Vírgula

- -

The return statement is affected by automatic semicolon insertion (ASI). No line terminator is allowed between the return keyword and the expression.

- -
return
-a + b;
-
- -

is transformed by ASI into:

- -
return;
-a + b;
-
- -

The console will warn "unreachable code after return statement".

- -
Starting with Gecko 40 {{geckoRelease(40)}}, a warning is shown in the console if unreachable code is found after a return statement.
- -

Exemplos

- -

Interromper uma função

- -

A function immediately stops at the point where return is called.

- -
function counter() {
-  for (var count = 1; ; count++) {  // infinite loop
-    console.log(count + 'A'); // until 5
-      if (count === 5) {
-        return;
-      }
-      console.log(count + 'B');  // until 4
-    }
-  console.log(count + 'C');  // never appears
-}
-
-counter();
-
-// Output:
-// 1A
-// 1B
-// 2A
-// 2B
-// 3A
-// 3B
-// 4A
-// 4B
-// 5A
-
- -

Devolver uma função

- -

See also the article about Closures.

- -
function magic(x) {
-  return function calc(x) { return x * 42; };
-}
-
-var answer = magic();
-answer(1337); // 56154
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-12.9', 'Return statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-return-statement', 'Return statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-return-statement', 'Return statement')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade de navegador

- - - -

{{Compat("javascript.statements.return")}}

- -

Consulte também

- - diff --git "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/throw/index.html" "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/throw/index.html" deleted file mode 100644 index 9e7a8bf54e..0000000000 --- "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/throw/index.html" +++ /dev/null @@ -1,271 +0,0 @@ ---- -title: throw -slug: Web/JavaScript/Reference/Extratos_e_declarações/throw -tags: - - Comando - - Declaração - - JavaScript -translation_of: Web/JavaScript/Reference/Statements/throw ---- -
{{jsSidebar("Statements")}}
- -

A declaração throw lança uma exeção definida pelo utilizador. A execução da função atual irá parar (os comandos depois de throw não serão executados), e o controle será passado para o primeiro bloco catch no conjunto de chamadas. Se não existir nenhum bloco catch entre as funções de caller, o programa irá terminar.

- -

Sintaxe

- -
expressão throw; 
- -
-
expressão
-
A expressão para throw.
-
- -

Descrição

- -

Use the throw statement to throw an exception. When you throw an exception, expression specifies the value of the exception. Each of the following throws an exception:

- -
throw 'Error2'; // generates an exception with a string value
-throw 42;       // generates an exception with the value 42
-throw true;     // generates an exception with the value true
- -

Also note that the throw statement is affected by automatic semicolon insertion (ASI) as no line terminator between the throw keyword and the expression is allowed.

- -

Exemplos

- -

Throw um objeto

- -

You can specify an object when you throw an exception. You can then reference the object's properties in the catch block. The following example creates an object of type UserException and uses it in a throw statement.

- -
function UserException(message) {
-   this.message = message;
-   this.name = 'UserException';
-}
-function getMonthName(mo) {
-   mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec)
-   var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
-      'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
-   if (months[mo] !== undefined) {
-      return months[mo];
-   } else {
-      throw new UserException('InvalidMonthNo');
-   }
-}
-
-try {
-   // statements to try
-   var myMonth = 15; // 15 is out of bound to raise the exception
-   var monthName = getMonthName(myMonth);
-} catch (e) {
-   monthName = 'unknown';
-   console.log(e.message, e.name); // pass exception object to err handler
-}
-
- -

Outro exemplo de throwing um objeto

- -

The following example tests an input string for a U.S. zip code. If the zip code uses an invalid format, the throw statement throws an exception by creating an object of type ZipCodeFormatException.

- -
/*
- * Creates a ZipCode object.
- *
- * Accepted formats for a zip code are:
- *    12345
- *    12345-6789
- *    123456789
- *    12345 6789
- *
- * If the argument passed to the ZipCode constructor does not
- * conform to one of these patterns, an exception is thrown.
- */
-
-function ZipCode(zip) {
-   zip = new String(zip);
-   pattern = /[0-9]{5}([- ]?[0-9]{4})?/;
-   if (pattern.test(zip)) {
-      // zip code value will be the first match in the string
-      this.value = zip.match(pattern)[0];
-      this.valueOf = function() {
-         return this.value
-      };
-      this.toString = function() {
-         return String(this.value)
-      };
-   } else {
-      throw new ZipCodeFormatException(zip);
-   }
-}
-
-function ZipCodeFormatException(value) {
-   this.value = value;
-   this.message = 'does not conform to the expected format for a zip code';
-   this.toString = function() {
-      return this.value + this.message;
-   };
-}
-
-/*
- * This could be in a script that validates address data
- * for US addresses.
- */
-
-const ZIPCODE_INVALID = -1;
-const ZIPCODE_UNKNOWN_ERROR = -2;
-
-function verifyZipCode(z) {
-   try {
-      z = new ZipCode(z);
-   } catch (e) {
-      if (e instanceof ZipCodeFormatException) {
-         return ZIPCODE_INVALID;
-      } else {
-         return ZIPCODE_UNKNOWN_ERROR;
-      }
-   }
-   return z;
-}
-
-a = verifyZipCode(95060);         // returns 95060
-b = verifyZipCode(9560);          // returns -1
-c = verifyZipCode('a');           // returns -1
-d = verifyZipCode('95060');       // returns 95060
-e = verifyZipCode('95060 1234');  // returns 95060 1234
-
- -

Rethrow uma exceção

- -

You can use throw to rethrow an exception after you catch it. The following example catches an exception with a numeric value and rethrows it if the value is over 50. The rethrown exception propagates up to the enclosing function or to the top level so that the user sees it.

- -
try {
-   throw n; // throws an exception with a numeric value
-} catch (e) {
-   if (e <= 50) {
-      // statements to handle exceptions 1-50
-   } else {
-      // cannot handle this exception, so rethrow
-      throw e;
-   }
-}
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.4
{{SpecName('ES5.1', '#sec-12.13', 'throw statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-throw-statement', 'throw statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-throw-statement', 'throw statement')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade de navegador

- - - -

{{Compat("javascript.statements.throw")}}

- -

Consulte também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/javascript/reference/funcionalidades_obsoletas/index.html b/files/pt-pt/web/javascript/reference/funcionalidades_obsoletas/index.html deleted file mode 100644 index 9d0ae63c62..0000000000 --- a/files/pt-pt/web/javascript/reference/funcionalidades_obsoletas/index.html +++ /dev/null @@ -1,289 +0,0 @@ ---- -title: Funcionalidades obsoletas -slug: Web/JavaScript/Reference/Funcionalidades_obsoletas -tags: - - JavaScript - - Obsoleto -translation_of: Web/JavaScript/Reference/Deprecated_and_obsolete_features ---- -
{{JsSidebar("More")}}
- -

Esta página lista as funcionalidades de JavaScript que estão obsoletas (ou seja, ainda disponíveis, mas planeadas para remoção) e obsoletas (isto é, não são mais utilizáveis).

- -

Funcionalidades obsoletas

- -

Estas funcionalidades obsoletas ainda podem ser utilziadas, mas devem ser utilizadas ​​com cuidado, pois espera-se que estas sejam removidas inteiramente no futuro. Deverá trabalhar para remover a utilização das mesmas do seu código..

- -

Propriedades de RegExp

- -

The following properties are deprecated. This does not affect their use in {{jsxref("String.replace", "replacement strings", "", 1)}}:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropriedadesDescrição
{{jsxref("RegExp.n", "$1-$9")}} -

Parenthesized substring matches, if any.
- Warning: Using these properties can result in problems, since browser extensions can modify them. Avoid them!

-
{{jsxref("RegExp.input", "$_")}}See input.
{{jsxref("RegExp.multiline", "$*")}}See multiline.
{{jsxref("RegExp.lastMatch", "$&")}}See lastMatch.
{{jsxref("RegExp.lastParen", "$+")}}See lastParen.
{{jsxref("RegExp.leftContext", "$`")}}See leftContext.
{{jsxref("RegExp.rightContext", "$'")}}See rightContext.
{{jsxref("RegExp.input", "input")}}The string against which a regular expression is matched.
{{jsxref("RegExp.lastMatch", "lastMatch")}}The last matched characters.
{{jsxref("RegExp.lastParen", "lastParen")}}The last parenthesized substring match, if any.
{{jsxref("RegExp.leftContext", "leftContext")}}The substring preceding the most recent match.
{{jsxref("RegExp.rightContext", "rightContext")}}The substring following the most recent match.
- -

The following are now properties of RegExp instances, no longer of the RegExp object:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropriedadesDescrição
{{jsxref("RegExp.global", "global")}}Whether or not to test the regular expression against all possible matches in a string, or only against the first.
{{jsxref("RegExp.ignoreCase", "ignoreCase")}}Whether or not to ignore case while attempting a match in a string.
{{jsxref("RegExp.lastIndex", "lastIndex")}}The index at which to start the next match.
{{jsxref("RegExp.multiline", "multiline")}}Whether or not to search in strings across multiple lines.
{{jsxref("RegExp.source", "source")}}The text of the pattern.
- -

Métodos de egExp

- - - -

Propriedades de Function

- - - -

Gerador de Legacy

- - - -

Iterator

- - - -

Métodos de Object

- - - -

Métodos de Date

- - - -

Functions

- - - -

Proxy

- - - -

Sequências de Escape

- - - -

Métodos de String

- - - -

Funcionalidades removidas

- -

Estas funcionalidades obsoletas foram totalmente removidas do JavaScript e não podem mais ser utilizadas a partir da versão indicada do JavaScript.

- -

Object

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyDescription
{{jsxref("Global_Objects/Object/count", "__count__")}}Returns the number of enumerable properties directly on a user-defined object.
{{jsxref("Global_Objects/Object/Parent", "__parent__")}}Points to an object's context.
{{jsxref("Global_Objects/Object/eval", "Object.prototype.eval()")}}Evaluates a string of JavaScript code in the context of the specified object.
{{jsxref("Object.observe()")}}Asynchronously observing the changes to an object.
{{jsxref("Object.unobserve()")}}Remove observers.
{{jsxref("Object.getNotifier()")}}Creates an object that allows to synthetically trigger a change.
- -

Function

- - - - - - - - - - - - -
PropertyDescription
{{jsxref("Global_Objects/Function/arity", "arity")}}Number of formal arguments.
- -

Array

- - - - - - - - - - - - - - - - -
PropertyDescription
{{jsxref("Array.observe()")}}Asynchronously observing changes to Arrays.
{{jsxref("Array.unobserve()")}}Remove observers.
- -

Number

- - - -

ParallelArray

- - - -

Statements

- - - -

E4X

- -

See E4X for more information.

- -

Variáveis Sharp

- -

Consulte Sharp variables in JavaScript para mais informação.

diff --git a/files/pt-pt/web/javascript/reference/funcoes/arguments/index.html b/files/pt-pt/web/javascript/reference/funcoes/arguments/index.html deleted file mode 100644 index c7ac84a4b9..0000000000 --- a/files/pt-pt/web/javascript/reference/funcoes/arguments/index.html +++ /dev/null @@ -1,228 +0,0 @@ ---- -title: O objeto arguments -slug: Web/JavaScript/Reference/Funcoes/arguments -tags: - - Class - - Funções - - JavaScript - - Referencia - - arguments -translation_of: Web/JavaScript/Reference/Functions/arguments ---- -

{{JSSidebar("Functions")}}

- -

arguments é um objeto semelhante a uma "Matiz" acessível dentro de functions que contém os valores dos argumentos passados ​​para essa função.

- -
-

Nota: If you're writing ES6 compatible code, then rest parameters should be preferred.

-
- -
-

Nota: “Array-like” means that arguments has a length property and properties indexed from zero, but it doesn't have {{JSxRef("Array")}}'s built-in methods like forEach and map. See §Description for details.

-
- -
{{EmbedInteractiveExample("pages/js/functions-arguments.html")}}
- - - -

Sintaxe

- -
arguments
- -

Descrição

- -

The arguments object is a local variable available within all non-arrow functions. You can refer to a function's arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry's index at 0.

- -

For example, if a function is passed 3 arguments, you can access them as follows:

- -
arguments[0] // first argument
-arguments[1] // second argument
-arguments[2] // third argument
-
- -

Each argument can also be set or reassigned:

- -
arguments[1] = 'new value';
-
- -

The arguments object is not an {{JSxRef("Array")}}. It is similar, but does not have any Array properties except length. For example, it does not have the pop method. However, it can be converted to a real Array:

- -
var args = Array.prototype.slice.call(arguments);
-// Using an array literal is shorter than above but allocates an empty array
-var args = [].slice.call(arguments);
-
- -

As you can do with any Array-like object, you can use ES2015's {{JSxRef("Array.from()")}} method or spread operator to convert arguments to a real Array:

- -
let args = Array.from(arguments);
-// or
-let args = [...arguments];
- -

The arguments object is useful for functions called with more arguments than they are formally declared to accept. This technique is useful for functions that can be passed a variable number of arguments, such as Math.min(). This example function accepts any number of string arguments and returns the longest one:

- -
function longestString() {
-  var longest = '';
-  for (var i=0; i < arguments.length; i++) {
-    if (arguments[i].length > longest.length) {
-      longest = arguments[i];
-    }
-  }
-  return longest;
-}
-
- -

You can use arguments.length to count how many arguments the function was called with. If you instead want to count how many parameters a function is declared to accept, inspect that function's length property.

- -

Utilizar typeof com Arguments

- -

The typeof operator returns 'object' when used with arguments

- -
console.log(typeof arguments); // 'object' 
- -

The type of individual arguments can be determined by indexing arguments:

- -
console.log(typeof arguments[0]); // returns the type of the first argument
- -

Propriedades

- -
-
-
{{jsxref("Functions/arguments/callee", "arguments.callee")}}
-
Reference to the currently executing function that the arguments belong to.
-
{{jsxref("Functions/arguments/length", "arguments.length")}}
-
The number of arguments that were passed to the function.
-
{{jsxref("Functions/arguments/@@iterator", "arguments[@@iterator]")}}
-
Returns a new {{jsxref("Array/@@iterator", "Array iterator", "", 0)}} object that contains the values for each index in arguments.
-
- -

Exemplos

- -

Definir uma function que concatena várias strings

- -

This example defines a function that concatenates several strings. The function's only formal argument is a string containing the characters that separate the items to concatenate.

- -
function myConcat(separator) {
-  var args = Array.prototype.slice.call(arguments, 1);
-  return args.join(separator);
-}
- -

You can pass as many arguments as you like to this function. It returns a string list using each argument in the list:

- -
// returns "red, orange, blue"
-myConcat(', ', 'red', 'orange', 'blue');
-
-// returns "elephant; giraffe; lion; cheetah"
-myConcat('; ', 'elephant', 'giraffe', 'lion', 'cheetah');
-
-// returns "sage. basil. oregano. pepper. parsley"
-myConcat('. ', 'sage', 'basil', 'oregano', 'pepper', 'parsley');
- -

Definir uma function que cria listas HTML

- -

This example defines a function that creates a string containing HTML for a list. The only formal argument for the function is a string that is "u" if the list is to be unordered (bulleted), or "o" if the list is to be ordered (numbered). The function is defined as follows:

- -
function list(type) {
-  var html = '<' + type + 'l><li>';
-  var args = Array.prototype.slice.call(arguments, 1);
-  html += args.join('</li><li>');
-  html += '</li></' + type + 'l>'; // end list
-
-  return html;
-}
- -

You can pass any number of arguments to this function, and it adds each argument as a list item to a list of the type indicated. For example:

- -
var listHTML = list('u', 'One', 'Two', 'Three');
-
-/* listHTML is:
-"<ul><li>One</li><li>Two</li><li>Three</li></ul>"
-*/
- -

Parâmetros Rest, predefinição, e desestruturados

- -

The arguments object can be used in conjunction with rest, default, and destructured parameters.

- -
function foo(...args) {
-  return args;
-}
-foo(1, 2, 3); // [1,2,3]
-
- -

While the presence of rest, default, or destructured parameters does not alter the behavior of the arguments object in strict mode code, there is a subtle difference for non-strict code.

- -

In strict-mode code, the arguments object behaves the same whether or not a function is passed rest, default, or destructured parameters. That is, assigning new values to variables in the body of the function will not affect the arguments object. Nor will assigning new variables to the arguments object affect the value of variables.

- -
-

Nota: You cannot write a "use strict"; directive in the body of a function definition that accepts rest, default, or destructured parameters. Doing so will throw a syntax error.

-
- -

Non-strict functions that are passed only simple parameters (that is, not rest, default, or restructured parameters) will sync the value of variables new values in the body of the function with the arguments object, and vice versa:

- -
function func(a) {
-  arguments[0] = 99; // updating arguments[0] also updates a
-  console.log(a);
-}
-func(10); // 99
-
- -

And also:

- -
function func(a) {
-  a = 99; // updating a also updates arguments[0]
-  console.log(arguments[0]);
-}
-func(10); // 99
-
- -

Conversely, non-strict functions that are passed rest, default, or destructured parameters will not sync new values assigned to argument variables in the function body with the arguments object. Instead, the arguments object in non-strict functions with complex parameters will always reflect the values passed to the function when the function was called (this is the same behavior as exhibited by all strict-mode functions, regardless of the type of variables they are passed):

- -
function func(a = 55) {
-  arguments[0] = 99; // updating arguments[0] does not also update a
-  console.log(a);
-}
-func(10); // 10
- -

E também:

- -
function func(a = 55) {
-  a = 99; // updating a does not also update arguments[0]
-  console.log(arguments[0]);
-}
-func(10); // 10
-
- -

E também:

- -
// An untracked default parameter
-function func(a = 55) {
-  console.log(arguments[0]);
-}
-func(); // undefined
- -

Especificações

- - - - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}
- -

Compatibildiade de navegador

- - - -

{{Compat("javascript.functions.arguments")}}

- -

Consulte também

- - diff --git a/files/pt-pt/web/javascript/reference/funcoes/funcoes_seta/index.html b/files/pt-pt/web/javascript/reference/funcoes/funcoes_seta/index.html deleted file mode 100644 index aa7b7b3121..0000000000 --- a/files/pt-pt/web/javascript/reference/funcoes/funcoes_seta/index.html +++ /dev/null @@ -1,399 +0,0 @@ ---- -title: Expressões da função "Seta" -slug: Web/JavaScript/Reference/Funcoes/Funcoes_seta -translation_of: Web/JavaScript/Reference/Functions/Arrow_functions ---- -
{{jsSidebar("Functions")}}
- -

Uma expressão da função seta é uma alternativa sintaticamente compacta a uma expressão de expressão de função regular, embora sem as suas próprias associações às palavras-chave this, arguments, super, ou new.target. As expressões de função (function) de seta são inadequadas como métodos, e não podem ser utilziadas como construtores.

- -
{{EmbedInteractiveExample("pages/js/functions-arrow.html")}}
- -

Sintaxe

- -

Basic syntax

- -
(param1, param2, …, paramN) => { statements }
-(param1, param2, …, paramN) => expression
-// equivalent to: => { return expression; }
-
-// Parentheses are optional when there's only one parameter name:
-(singleParam) => { statements }
-singleParam => { statements }
-
-// The parameter list for a function with no parameters should be written with a pair of parentheses.
-() => { statements }
-
- -

Advanced syntax

- -
// Parenthesize the body of a function to return an object literal expression:
-params => ({foo: bar})
-
-// Rest parameters and default parameters are supported
-(param1, param2, ...rest) => { statements }
-(param1 = defaultValue1, param2, …, paramN = defaultValueN) => {
-statements }
-
-// Destructuring within the parameter list is also supported
-var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
-f(); // 6
-
- -

Descrição

- -

See also "ES6 In Depth: Arrow functions" on hacks.mozilla.org.

- -

Two factors influenced the introduction of arrow functions: the need for shorter functions and the behavior of the this keyword.

- -

Funções curtas

- -
var elements = [
-  'Hydrogen',
-  'Helium',
-  'Lithium',
-  'Beryllium'
-];
-
-// This statement returns the array: [8, 6, 7, 9]
-elements.map(function(element) {
-  return element.length;
-});
-
-// The regular function above can be written as the arrow function below
-elements.map((element) => {
-  return element.length;
-}); // [8, 6, 7, 9]
-
-// When there is only one parameter, we can remove the surrounding parentheses
-elements.map(element => {
-  return element.length;
-}); // [8, 6, 7, 9]
-
-// When the only statement in an arrow function is `return`, we can remove `return` and remove
-// the surrounding curly brackets
-elements.map(element => element.length); // [8, 6, 7, 9]
-
-// In this case, because we only need the length property, we can use destructuring parameter:
-// Notice that the `length` corresponds to the property we want to get whereas the
-// obviously non-special `lengthFooBArX` is just the name of a variable which can be changed
-// to any valid variable name you want
-elements.map(({ length: lengthFooBArX }) => lengthFooBArX); // [8, 6, 7, 9]
-
-// This destructuring parameter assignment can also be written as seen below. However, note that in
-// this example we are not assigning `length` value to the made up property. Instead, the literal name
-// itself of the variable `length` is used as the property we want to retrieve from the object.
-elements.map(({ length }) => length); // [8, 6, 7, 9]
-
- -

No separate this

- -

Before arrow functions, every new function defined its own this value based on how the function was called:

- - - -

This proved to be less than ideal with an object-oriented style of programming.

- -
function Person() {
-  // The Person() constructor defines `this` as an instance of itself.
-  this.age = 0;
-
-  setInterval(function growUp() {
-    // In non-strict mode, the growUp() function defines `this`
-    // as the global object (because it's where growUp() is executed.),
-    // which is different from the `this`
-    // defined by the Person() constructor.
-    this.age++;
-  }, 1000);
-}
-
-var p = new Person();
- -

In ECMAScript 3/5, the this issue was fixable by assigning the value in this to a variable that could be closed over.

- -
function Person() {
-  var that = this;
-  that.age = 0;
-
-  setInterval(function growUp() {
-    // The callback refers to the `that` variable of which
-    // the value is the expected object.
-    that.age++;
-  }, 1000);
-}
- -

Alternatively, a bound function could be created so that a preassigned this value would be passed to the bound target function (the growUp() function in the example above).

- -

An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope, an arrow function ends up finding the this from its enclosing scope.

- -

Thus, in the following code, the this within the function that is passed to setInterval has the same value as the this in the lexically enclosing function:

- -
function Person(){
-  this.age = 0;
-
-  setInterval(() => {
-    this.age++; // |this| properly refers to the Person object
-  }, 1000);
-}
-
-var p = new Person();
- -

Relation with strict mode

- -

Given that this comes from the surrounding lexical context, strict mode rules with regard to this are ignored.

- -
var f = () => { 'use strict'; return this; };
-f() === window; // or the global object
- -

All other strict mode rules apply normally.

- -

Invoked through call or apply

- -

Since arrow functions do not have their own this, the methods call() and apply() can only pass in parameters. Any this argument is ignored.

- -
var adder = {
-  base: 1,
-
-  add: function(a) {
-    var f = v => v + this.base;
-    return f(a);
-  },
-
-  addThruCall: function(a) {
-    var f = v => v + this.base;
-    var b = {
-      base: 2
-    };
-
-    return f.call(b, a);
-  }
-};
-
-console.log(adder.add(1));         // This would log 2
-console.log(adder.addThruCall(1)); // This would log 2 still
- -

No binding of arguments

- -

Arrow functions do not have their own arguments object. Thus, in this example, arguments is simply a reference to the arguments of the enclosing scope:

- -
var arguments = [1, 2, 3];
-var arr = () => arguments[0];
-
-arr(); // 1
-
-function foo(n) {
-  var f = () => arguments[0] + n; // foo's implicit arguments binding. arguments[0] is n
-  return f();
-}
-
-foo(3); // 6
- -

In most cases, using rest parameters is a good alternative to using an arguments object.

- -
function foo(n) {
-  var f = (...args) => args[0] + n;
-  return f(10);
-}
-
-foo(1); // 11
- -

Arrow functions used as methods

- -

As stated previously, arrow function expressions are best suited for non-method functions. Let's see what happens when we try to use them as methods:

- -
'use strict';
-
-var obj = { // does not create a new scope
-  i: 10,
-  b: () => console.log(this.i, this),
-  c: function() {
-    console.log(this.i, this);
-  }
-}
-
-obj.b(); // prints undefined, Window {...} (or the global object)
-obj.c(); // prints 10, Object {...}
- -

Arrow functions do not have their own this. Another example involving {{jsxref("Object.defineProperty()")}}:

- -
'use strict';
-
-var obj = {
-  a: 10
-};
-
-Object.defineProperty(obj, 'b', {
-  get: () => {
-    console.log(this.a, typeof this.a, this); // undefined 'undefined' Window {...} (or the global object)
-    return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined'
-  }
-});
-
- -

Use of the new operator

- -

Arrow functions cannot be used as constructors and will throw an error when used with new.

- -
var Foo = () => {};
-var foo = new Foo(); // TypeError: Foo is not a constructor
- -

Use of prototype property

- -

Arrow functions do not have a prototype property.

- -
var Foo = () => {};
-console.log(Foo.prototype); // undefined
-
- -

Use of the yield keyword

- -

The yield keyword may not be used in an arrow function's body (except when permitted within functions further nested within it). As a consequence, arrow functions cannot be used as generators.

- -

Function body

- -

Arrow functions can have either a "concise body" or the usual "block body".

- -

In a concise body, only an expression is specified, which becomes the implicit return value. In a block body, you must use an explicit return statement.

- -
var func = x => x * x;
-// concise body syntax, implied "return"
-
-var func = (x, y) => { return x + y; };
-// with block body, explicit "return" needed
-
- -

Returning object literals

- -

Keep in mind that returning object literals using the concise body syntax params => {object:literal} will not work as expected.

- -
var func = () => { foo: 1 };
-// Calling func() returns undefined!
-
-var func = () => { foo: function() {} };
-// SyntaxError: function statement requires a name
- -

This is because the code inside braces ({}) is parsed as a sequence of statements (i.e. foo is treated like a label, not a key in an object literal).

- -

You must wrap the object literal in parentheses:

- -
var func = () => ({ foo: 1 });
- -

Line breaks

- -

An arrow function cannot contain a line break between its parameters and its arrow.

- -
var func = (a, b, c)
-  => 1;
-// SyntaxError: expected expression, got '=>'
- -

However, this can be amended by putting the line break after the arrow or using parentheses/braces as seen below to ensure that the code stays pretty and fluffy. You can also put line breaks between arguments.

- -
var func = (a, b, c) =>
-  1;
-
-var func = (a, b, c) => (
-  1
-);
-
-var func = (a, b, c) => {
-  return 1
-};
-
-var func = (
-  a,
-  b,
-  c
-) => 1;
-
-// no SyntaxError thrown
- -

Parsing order

- -

Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with operator precedence compared to regular functions.

- -
let callback;
-
-callback = callback || function() {}; // ok
-
-callback = callback || () => {};
-// SyntaxError: invalid arrow-function arguments
-
-callback = callback || (() => {});    // ok
-
- -

More examples

- -
// An empty arrow function returns undefined
-let empty = () => {};
-
-(() => 'foobar')();
-// Returns "foobar"
-// (this is an Immediately Invoked Function Expression)
-
-var simple = a => a > 15 ? 15 : a;
-simple(16); // 15
-simple(10); // 10
-
-let max = (a, b) => a > b ? a : b;
-
-// Easy array filtering, mapping, ...
-
-var arr = [5, 6, 13, 0, 1, 18, 23];
-
-var sum = arr.reduce((a, b) => a + b);
-// 66
-
-var even = arr.filter(v => v % 2 == 0);
-// [6, 0, 18]
-
-var double = arr.map(v => v * 2);
-// [10, 12, 26, 0, 2, 36, 46]
-
-// More concise promise chains
-promise.then(a => {
-  // ...
-}).then(b => {
-  // ...
-});
-
-// Parameterless arrow functions that are visually easier to parse
-setTimeout( () => {
-  console.log('I happen sooner');
-  setTimeout( () => {
-    // deeper code
-    console.log('I happen later');
-  }, 1);
-}, 1);
-
- -

Specifications

- - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}
- -

Browser compatibility

- -
- - -

{{Compat("javascript.functions.arrow_functions")}}

-
- -

See also

- - diff --git a/files/pt-pt/web/javascript/reference/funcoes/index.html b/files/pt-pt/web/javascript/reference/funcoes/index.html deleted file mode 100644 index 02b35fc7bd..0000000000 --- a/files/pt-pt/web/javascript/reference/funcoes/index.html +++ /dev/null @@ -1,594 +0,0 @@ ---- -title: Funções -slug: Web/JavaScript/Reference/Funcoes -tags: - - Constructor - - Função - - Funções - - JavaScript - - Parâmetro - - parâmetros -translation_of: Web/JavaScript/Reference/Functions ---- -
{{jsSidebar("Functions")}}
- -

Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.

- -

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

- -

For more examples and explanations, see also the JavaScript guide about functions.

- -

Descrição

- -

Every function in JavaScript is a Function object. See {{jsxref("Function")}} for information on properties and methods of Function objects.

- -

To return a value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is {{jsxref("undefined")}}.

- -

The parameters of a function call are the function's arguments. Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example:

- -
/* Declare the function 'myFunc' */
-function myFunc(theObject) {
-  theObject.brand = "Toyota";
-}
-
-/*
- * Declare variable 'mycar';
- * create and initialize a new Object;
- * assign reference to it to 'mycar'
- */
-var mycar = {
-  brand: "Honda",
-  model: "Accord",
-  year: 1998
-};
-
-/* Logs 'Honda' */
-console.log(mycar.brand);
-
-/* Pass object reference to the function */
-myFunc(mycar);
-
-/*
- * Logs 'Toyota' as the value of the 'brand' property
- * of the object, as changed to by the function.
- */
-console.log(mycar.brand);
-
- -

The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function body.

- -

Definindo funções

- -

There are several ways to define functions:

- -

The function declaration (function statement)

- -

There is a special syntax for declaring functions (see function statement for details):

- -
function name([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
- -
-
statements
-
The statements comprising the body of the function.
-
- -

The function expression (function expression)

- -

A function expression is similar to and has the same syntax as a function declaration (see function expression for details). A function expression may be a part of a larger expression. One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. Function expressions are not hoisted onto the beginning of the scope, therefore they cannot be used before they appear in the code.

- -
function [name]([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
statements
-
The statements comprising the body of the function.
-
- -

Here is an example of an anonymous function expression (the name is not used):

- -
var myFunction = function() {
-    statements
-}
- -

It is also possible to provide a name inside the definition in order to create a named function expression:

- -
var myFunction = function namedFunction(){
-    statements
-}
-
- -

One of the benefit of creating a named function expression is that in case we encounted an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.

- -

As we can see, both examples do not start with the function keyword. Statements involving functions which do not start with function are function expressions.

- -

When functions are used only once, a common pattern is an IIFE (Immediately Invokable Function Expression).

- -
(function() {
-    statements
-})();
- -

IIFE are function expressions that are invoked as soon as the function is declared.

- -

The generator function declaration (function* statement)

- -

There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):

- -
function* name([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
- -
-
statements
-
The statements comprising the body of the function.
-
- -

The generator function expression (function* expression)

- -

A generator function expression is similar to and has the same syntax as a generator function declaration (see {{jsxref('Operators/function*', 'function* expression')}} for details):

- -
function* [name]([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
statements
-
The statements comprising the body of the function.
-
- -

The arrow function expression (=>)

- -

An arrow function expression has a shorter syntax and lexically binds its this value (see arrow functions for details):

- -
([param[, param]]) => {
-   statements
-}
-
-param => expression
-
- -
-
param
-
The name of an argument. Zero arguments need to be indicated with ().  For only one argument, the parentheses are not required. (like foo => 1)
-
statements or expression
-
Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of the function.
-
- -

The Function constructor

- -
-

Note: Using the Function constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

-
- -

As all other objects, {{jsxref("Function")}} objects can be created using the new operator:

- -
new Function (arg1, arg2, ... argN, functionBody)
-
- -
-
arg1, arg2, ... argN
-
Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.
-
- -
-
functionBody
-
A string containing the JavaScript statements comprising the function body.
-
- -

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

- -

The GeneratorFunction constructor

- -
-

Note: GeneratorFunction is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).

-
- -
-

Note: Using the GeneratorFunction constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

-
- -

As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the new operator:

- -
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
-
- -
-
arg1, arg2, ... argN
-
Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
-
- -
-
functionBody
-
A string containing the JavaScript statements comprising the function definition.
-
- -

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

- -

Parâmetros de função

- -

Parâmetros predefinidos

- -

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. For more details, see default parameters.

- -

Parâmetros Rest

- -

The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see rest parameters.

- -

O objeto arguments

- -

You can refer to a function's arguments within the function by using the arguments object. See arguments.

- - - -

Definindo funções de método

- -

Getter and setter functions

- -

You can define getters (accessor methods) and setters (mutator methods) on any standard built-in object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

- -
-
get
-
-

Binds an object property to a function that will be called when that property is looked up.

-
-
set
-
Binds an object property to a function to be called when there is an attempt to set that property.
-
- -

Method definition syntax

- -

Starting with ECMAScript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. See method definitions for more information.

- -
var obj = {
-  foo() {},
-  bar() {}
-};
- -

Constructor vs. declaration vs. expression

- -

Compare the following:

- -

A function defined with the Function constructor assigned to the variable multiply:

- -
var multiply = new Function('x', 'y', 'return x * y');
- -

A function declaration of a function named multiply:

- -
function multiply(x, y) {
-   return x * y;
-} // there is no semicolon here
-
- -

A function expression of an anonymous function assigned to the variable multiply:

- -
var multiply = function(x, y) {
-   return x * y;
-};
-
- -

A function expression of a function named func_name assigned to the variable multiply:

- -
var multiply = function func_name(x, y) {
-   return x * y;
-};
-
- -

Differences

- -

All do approximately the same thing, with a few subtle differences:

- -

There is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example:

- -
var y = function x() {};
-alert(x); // throws an error
-
- -

The function name also appears when the function is serialized via Function's toString method.

- -

On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope in which the function is declared.

- -

As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other. A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:

- -

A function defined by 'new Function' does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs:

- -
function anonymous() {
-}
-
- -

Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error:

- -
var foo = new Function("alert(anonymous);");
-foo();
-
- -

Unlike functions defined by function expressions or by the Function constructor, a function defined by a function declaration can be used before the function declaration itself. For example:

- -
foo(); // alerts FOO!
-function foo() {
-   alert('FOO!');
-}
-
- -

A function defined by a function expression or by a function declaration inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).

- -
/*
- * Declare and initialize a variable 'p' (global)
- * and a function 'myFunc' (to change the scope) inside which
- * declare a varible with same name 'p' (current) and
- * define three functions using three different ways:-
- *     1. function declaration
- *     2. function expression
- *     3. function constructor
- * each of which will log 'p'
- */
-var p = 5;
-function myFunc() {
-    var p = 9;
-
-    function decl() {
-        console.log(p);
-    }
-    var expr = function() {
-        console.log(p);
-    };
-    var cons = new Function('\tconsole.log(p);');
-
-    decl();
-    expr();
-    cons();
-}
-myFunc();
-
-/*
- * Logs:-
- * 9  - for 'decl' by function declaration (current scope)
- * 9  - for 'expr' by function expression (current scope)
- * 5  - for 'cons' by Function constructor (global scope)
- */
-
- -

Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function constructor must be parsed each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should generally be avoided whenever possible.

- -

It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a Function constructor 's string aren't parsed repeatedly. For example:

- -
var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))();
-foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.
- -

A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:

- - - -
var x = 0;               // source element
-if (x === 0) {           // source element
-   x = 10;               // not a source element
-   function boo() {}     // not a source element
-}
-function foo() {         // source element
-   var y = 20;           // source element
-   function bar() {}     // source element
-   while (y === 10) {    // source element
-      function blah() {} // not a source element
-      y++;               // not a source element
-   }
-}
-
- -

Examples

- -
// function declaration
-function foo() {}
-
-// function expression
-(function bar() {})
-
-// function expression
-x = function hello() {}
-
-
-if (x) {
-   // function expression
-   function world() {}
-}
-
-
-// function declaration
-function a() {
-   // function declaration
-   function b() {}
-   if (0) {
-      // function expression
-      function c() {}
-   }
-}
-
- -

Block-level functions

- -

In strict mode, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

- -
'use strict';
-
-function f() {
-  return 1;
-}
-
-{
-  function f() {
-    return 2;
-  }
-}
-
-f() === 1; // true
-
-// f() === 2 in non-strict mode
-
- -

Block-level functions in non-strict code

- -

In a word: Don't.

- -

In non-strict code, function declarations inside blocks behave strangely. For example:

- -
if (shouldDefineZero) {
-   function zero() {     // DANGER: compatibility risk
-      console.log("This is zero.");
-   }
-}
-
- -

ES2015 says that if shouldDefineZero is false, then zero should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define zero whether the block executed or not.

- -

In strict mode, all browsers that support ES2015 handle this the same way: zero is defined only if shouldDefineZero is true, and only in the scope of the if-block.

- -

A safer way to define functions conditionally is to assign a function expression to a variable:

- -
var zero;
-if (shouldDefineZero) {
-   zero = function() {
-      console.log("This is zero.");
-   };
-}
-
- -

Exemplos

- -

Returning a formatted number

- -

The following function returns a string containing the formatted representation of a number padded with leading zeros.

- -
// This function returns a string padded with leading zeros
-function padZeros(num, totalLen) {
-   var numStr = num.toString();             // Initialize return value as string
-   var numZeros = totalLen - numStr.length; // Calculate no. of zeros
-   for (var i = 1; i <= numZeros; i++) {
-      numStr = "0" + numStr;
-   }
-   return numStr;
-}
-
- -

The following statements call the padZeros function.

- -
var result;
-result = padZeros(42,4); // returns "0042"
-result = padZeros(42,2); // returns "42"
-result = padZeros(5,4);  // returns "0005"
-
- -

Determining whether a function exists

- -

You can determine whether a function exists by using the typeof operator. In the following example, a test is performed to determine if the window object has a property called noFunc that is a function. If so, it is used; otherwise some other action is taken.

- -
 if ('function' === typeof window.noFunc) {
-   // use noFunc()
- } else {
-   // do something else
- }
-
- -

Note that in the if test, a reference to noFunc is used—there are no brackets "()" after the function name so the actual function is not called.

- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}}New: Arrow functions, Generator functions, default parameters, rest parameters.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade de navegador

- - - -

{{Compat("javascript.functions")}}

- -

Consulte também

- - diff --git a/files/pt-pt/web/javascript/reference/funcoes/parametros_rest/index.html b/files/pt-pt/web/javascript/reference/funcoes/parametros_rest/index.html deleted file mode 100644 index a21cb25ed6..0000000000 --- a/files/pt-pt/web/javascript/reference/funcoes/parametros_rest/index.html +++ /dev/null @@ -1,234 +0,0 @@ ---- -title: Parâmetros Rest -slug: Web/JavaScript/Reference/Funcoes/parametros_rest -tags: - - Funcionalidade Linguagem - - Funções - - JavaScript - - Parametros Rest - - Rest -translation_of: Web/JavaScript/Reference/Functions/rest_parameters ---- -
Parâmetrois {{jsSidebar("Functions")}}
- -

A sintaxe do parâmetro "rest" permite-nos representar um número indefinido de argumentoscomo um array.

- -
{{EmbedInteractiveExample("pages/js/functions-restparameters.html")}}
- - - -

Sintaxe

- -
function f(a, b, ...theArgs) {
-  // ...
-}
- -

Descrição

- -

A function's last parameter can be prefixed with ... which will cause all remaining (user supplied) arguments to be placed within a "standard" Javascript array.

- -

Only the last parameter can be a "rest parameter".

- -
function myFun(a, b, ...manyMoreArgs) {
-  console.log("a", a)
-  console.log("b", b)
-  console.log("manyMoreArgs", manyMoreArgs)
-}
-
-myFun("one", "two", "three", "four", "five", "six")
-
-// Console Output:
-// a, one
-// b, two
-// manyMoreArgs, [three, four, five, six]
-
- -

Difference between rest parameters and the arguments object

- -

There are three main differences between rest parameters and the {{jsxref("Functions/arguments", "arguments")}} object:

- - - -

From arguments to an array

- -

Rest parameters have been introduced to reduce the boilerplate code that was induced by the arguments

- -
// Before rest parameters, "arguments" could be converted to a normal array using:
-
-function f(a, b) {
-
-  let normalArray = Array.prototype.slice.call(arguments)
-  // -- or --
-  let normalArray = [].slice.call(arguments)
-  // -- or --
-  let normalArray = Array.from(arguments)
-
-  let first = normalArray.shift()  // OK, gives the first argument
-  let first = arguments.shift()    // ERROR (arguments is not a normal array)
-}
-
-// Now, you can easily gain access to a normal array using a rest parameter
-
-function f(...args) {
-  let normalArray = args
-  let first = normalArray.shift() // OK, gives the first argument
-}
-
- -

Destructuring rest parameters

- -

Rest parameters can be destructured Arrays only (though objects will soon be supported). That means that their data can be unpacked into distinct variables. (See Destructuring assignment.)

- -
function f(...[a, b, c]) {
-  return a + b + c;
-}
-
-f(1)          // NaN (b and c are undefined)
-f(1, 2, 3)    // 6
-f(1, 2, 3, 4) // 6 (the fourth parameter is not destructured)
-
- -
-

Fixme

- -

Doing this is possible, but (afaik) there's no use-case, so it's just confusing the junior audience. The following code does exactly the same. There should at least be a note, that in theory you can do something like this, but there is no point in doing so. The example is contrived, but imagine that [a, b, c] were the return value of some function. Then the utility is clear.

- -

Also, since Function arguments will never have named parameters (this is not Python), the statement "objects will soon be supported" is wrong. The preceding example may be mixing up destructuring with rest parameters. Please see the page on destructuring assignment for an example with object destructuring applied in the parameters area.

- -
function f(a, b, c) {
-  return a + b + c
-}
-
-f(1)          // NaN (b and c are undefined)
-f(1, 2, 3)    // 6
-f(1, 2, 3, 4) // 6 (the fourth parameter is not ...)
-
-
- -

Exemplos

- -

In this example, the first argument is mapped to a and the second to b, so these named arguments are used like normal.

- -

However, the third argument, manyMoreArgs, will be an array that contains the 3rd, 4th, 5th, 6th ... nth — as many arguments that the user includes.

- -
function myFun(a, b, ...manyMoreArgs) {
-  console.log("a", a)
-  console.log("b", b)
-  console.log("manyMoreArgs", manyMoreArgs)
-}
-
-myFun("one", "two", "three", "four", "five", "six")
-
-// a, one
-// b, two
-// manyMoreArgs, [three, four, five, six]
-
- -

Below... even though there is just one value, the last argument still gets put into an array.

- -
// using the same function definition from example above
-
-myFun("one", "two", "three")
-
-// a, one
-// b, two
-// manyMoreArgs, [three]
- -

Below, the third argument isn't provided, but manyMoreArgs is still an array (albeit an empty one).

- -
// using the same function definition from example above
-
-myFun("one", "two")
-
-// a, one
-// b, two
-// manyMoreArgs, []
- -

Since theArgs is an array, a count of its elements is given by the length property:

- -
function fun1(...theArgs) {
-  console.log(theArgs.length)
-}
-
-fun1()         // 0
-fun1(5)        // 1
-fun1(5, 6, 7)  // 3
-
- -

In the next example, a rest parameter is used to collect all parameters after the first into an array. Each one of them is then multiplied by the first parameter, and the array is returned:

- -
function multiply(multiplier, ...theArgs) {
-  return theArgs.map(function(element) {
-    return multiplier * element
-  })
-}
-
-let arr = multiply(2, 1, 2, 3)
-console.log(arr)  // [2, 4, 6]
-
- -

Array methods can be used on rest parameters, but not on the arguments object:

- -
function sortRestArgs(...theArgs) {
-  let sortedArgs = theArgs.sort()
-  return sortedArgs
-}
-
-console.log(sortRestArgs(5, 3, 7, 1)) // 1, 3, 5, 7
-
-function sortArguments() {
-  let sortedArgs = arguments.sort()
-  return sortedArgs  // this will never happen
-}
-
-
-console.log(sortArguments(5, 3, 7, 1))
-// throws a TypeError (arguments.sort is not a function)
-
- -

To use Array methods on the arguments object, it must be converted to a real array first.

- -
function sortArguments() {
-  let args = Array.from(arguments)
-  let sortedArgs = args.sort()
-  return sortedArgs
-}
-console.log(sortArguments(5, 3, 7, 1))  // 1, 3, 5, 7
-
- -

Especificações

- - - - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}}
- -

Compatibildiade de navegador

- - - -

{{Compat("javascript.functions.rest_parameters")}}

- -

Consulte também

- - diff --git a/files/pt-pt/web/javascript/reference/functions/arguments/index.html b/files/pt-pt/web/javascript/reference/functions/arguments/index.html new file mode 100644 index 0000000000..c7ac84a4b9 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/functions/arguments/index.html @@ -0,0 +1,228 @@ +--- +title: O objeto arguments +slug: Web/JavaScript/Reference/Funcoes/arguments +tags: + - Class + - Funções + - JavaScript + - Referencia + - arguments +translation_of: Web/JavaScript/Reference/Functions/arguments +--- +

{{JSSidebar("Functions")}}

+ +

arguments é um objeto semelhante a uma "Matiz" acessível dentro de functions que contém os valores dos argumentos passados ​​para essa função.

+ +
+

Nota: If you're writing ES6 compatible code, then rest parameters should be preferred.

+
+ +
+

Nota: “Array-like” means that arguments has a length property and properties indexed from zero, but it doesn't have {{JSxRef("Array")}}'s built-in methods like forEach and map. See §Description for details.

+
+ +
{{EmbedInteractiveExample("pages/js/functions-arguments.html")}}
+ + + +

Sintaxe

+ +
arguments
+ +

Descrição

+ +

The arguments object is a local variable available within all non-arrow functions. You can refer to a function's arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry's index at 0.

+ +

For example, if a function is passed 3 arguments, you can access them as follows:

+ +
arguments[0] // first argument
+arguments[1] // second argument
+arguments[2] // third argument
+
+ +

Each argument can also be set or reassigned:

+ +
arguments[1] = 'new value';
+
+ +

The arguments object is not an {{JSxRef("Array")}}. It is similar, but does not have any Array properties except length. For example, it does not have the pop method. However, it can be converted to a real Array:

+ +
var args = Array.prototype.slice.call(arguments);
+// Using an array literal is shorter than above but allocates an empty array
+var args = [].slice.call(arguments);
+
+ +

As you can do with any Array-like object, you can use ES2015's {{JSxRef("Array.from()")}} method or spread operator to convert arguments to a real Array:

+ +
let args = Array.from(arguments);
+// or
+let args = [...arguments];
+ +

The arguments object is useful for functions called with more arguments than they are formally declared to accept. This technique is useful for functions that can be passed a variable number of arguments, such as Math.min(). This example function accepts any number of string arguments and returns the longest one:

+ +
function longestString() {
+  var longest = '';
+  for (var i=0; i < arguments.length; i++) {
+    if (arguments[i].length > longest.length) {
+      longest = arguments[i];
+    }
+  }
+  return longest;
+}
+
+ +

You can use arguments.length to count how many arguments the function was called with. If you instead want to count how many parameters a function is declared to accept, inspect that function's length property.

+ +

Utilizar typeof com Arguments

+ +

The typeof operator returns 'object' when used with arguments

+ +
console.log(typeof arguments); // 'object' 
+ +

The type of individual arguments can be determined by indexing arguments:

+ +
console.log(typeof arguments[0]); // returns the type of the first argument
+ +

Propriedades

+ +
+
+
{{jsxref("Functions/arguments/callee", "arguments.callee")}}
+
Reference to the currently executing function that the arguments belong to.
+
{{jsxref("Functions/arguments/length", "arguments.length")}}
+
The number of arguments that were passed to the function.
+
{{jsxref("Functions/arguments/@@iterator", "arguments[@@iterator]")}}
+
Returns a new {{jsxref("Array/@@iterator", "Array iterator", "", 0)}} object that contains the values for each index in arguments.
+
+ +

Exemplos

+ +

Definir uma function que concatena várias strings

+ +

This example defines a function that concatenates several strings. The function's only formal argument is a string containing the characters that separate the items to concatenate.

+ +
function myConcat(separator) {
+  var args = Array.prototype.slice.call(arguments, 1);
+  return args.join(separator);
+}
+ +

You can pass as many arguments as you like to this function. It returns a string list using each argument in the list:

+ +
// returns "red, orange, blue"
+myConcat(', ', 'red', 'orange', 'blue');
+
+// returns "elephant; giraffe; lion; cheetah"
+myConcat('; ', 'elephant', 'giraffe', 'lion', 'cheetah');
+
+// returns "sage. basil. oregano. pepper. parsley"
+myConcat('. ', 'sage', 'basil', 'oregano', 'pepper', 'parsley');
+ +

Definir uma function que cria listas HTML

+ +

This example defines a function that creates a string containing HTML for a list. The only formal argument for the function is a string that is "u" if the list is to be unordered (bulleted), or "o" if the list is to be ordered (numbered). The function is defined as follows:

+ +
function list(type) {
+  var html = '<' + type + 'l><li>';
+  var args = Array.prototype.slice.call(arguments, 1);
+  html += args.join('</li><li>');
+  html += '</li></' + type + 'l>'; // end list
+
+  return html;
+}
+ +

You can pass any number of arguments to this function, and it adds each argument as a list item to a list of the type indicated. For example:

+ +
var listHTML = list('u', 'One', 'Two', 'Three');
+
+/* listHTML is:
+"<ul><li>One</li><li>Two</li><li>Three</li></ul>"
+*/
+ +

Parâmetros Rest, predefinição, e desestruturados

+ +

The arguments object can be used in conjunction with rest, default, and destructured parameters.

+ +
function foo(...args) {
+  return args;
+}
+foo(1, 2, 3); // [1,2,3]
+
+ +

While the presence of rest, default, or destructured parameters does not alter the behavior of the arguments object in strict mode code, there is a subtle difference for non-strict code.

+ +

In strict-mode code, the arguments object behaves the same whether or not a function is passed rest, default, or destructured parameters. That is, assigning new values to variables in the body of the function will not affect the arguments object. Nor will assigning new variables to the arguments object affect the value of variables.

+ +
+

Nota: You cannot write a "use strict"; directive in the body of a function definition that accepts rest, default, or destructured parameters. Doing so will throw a syntax error.

+
+ +

Non-strict functions that are passed only simple parameters (that is, not rest, default, or restructured parameters) will sync the value of variables new values in the body of the function with the arguments object, and vice versa:

+ +
function func(a) {
+  arguments[0] = 99; // updating arguments[0] also updates a
+  console.log(a);
+}
+func(10); // 99
+
+ +

And also:

+ +
function func(a) {
+  a = 99; // updating a also updates arguments[0]
+  console.log(arguments[0]);
+}
+func(10); // 99
+
+ +

Conversely, non-strict functions that are passed rest, default, or destructured parameters will not sync new values assigned to argument variables in the function body with the arguments object. Instead, the arguments object in non-strict functions with complex parameters will always reflect the values passed to the function when the function was called (this is the same behavior as exhibited by all strict-mode functions, regardless of the type of variables they are passed):

+ +
function func(a = 55) {
+  arguments[0] = 99; // updating arguments[0] does not also update a
+  console.log(a);
+}
+func(10); // 10
+ +

E também:

+ +
function func(a = 55) {
+  a = 99; // updating a does not also update arguments[0]
+  console.log(arguments[0]);
+}
+func(10); // 10
+
+ +

E também:

+ +
// An untracked default parameter
+function func(a = 55) {
+  console.log(arguments[0]);
+}
+func(); // undefined
+ +

Especificações

+ + + + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}
+ +

Compatibildiade de navegador

+ + + +

{{Compat("javascript.functions.arguments")}}

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/functions/arrow_functions/index.html b/files/pt-pt/web/javascript/reference/functions/arrow_functions/index.html new file mode 100644 index 0000000000..aa7b7b3121 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/functions/arrow_functions/index.html @@ -0,0 +1,399 @@ +--- +title: Expressões da função "Seta" +slug: Web/JavaScript/Reference/Funcoes/Funcoes_seta +translation_of: Web/JavaScript/Reference/Functions/Arrow_functions +--- +
{{jsSidebar("Functions")}}
+ +

Uma expressão da função seta é uma alternativa sintaticamente compacta a uma expressão de expressão de função regular, embora sem as suas próprias associações às palavras-chave this, arguments, super, ou new.target. As expressões de função (function) de seta são inadequadas como métodos, e não podem ser utilziadas como construtores.

+ +
{{EmbedInteractiveExample("pages/js/functions-arrow.html")}}
+ +

Sintaxe

+ +

Basic syntax

+ +
(param1, param2, …, paramN) => { statements }
+(param1, param2, …, paramN) => expression
+// equivalent to: => { return expression; }
+
+// Parentheses are optional when there's only one parameter name:
+(singleParam) => { statements }
+singleParam => { statements }
+
+// The parameter list for a function with no parameters should be written with a pair of parentheses.
+() => { statements }
+
+ +

Advanced syntax

+ +
// Parenthesize the body of a function to return an object literal expression:
+params => ({foo: bar})
+
+// Rest parameters and default parameters are supported
+(param1, param2, ...rest) => { statements }
+(param1 = defaultValue1, param2, …, paramN = defaultValueN) => {
+statements }
+
+// Destructuring within the parameter list is also supported
+var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
+f(); // 6
+
+ +

Descrição

+ +

See also "ES6 In Depth: Arrow functions" on hacks.mozilla.org.

+ +

Two factors influenced the introduction of arrow functions: the need for shorter functions and the behavior of the this keyword.

+ +

Funções curtas

+ +
var elements = [
+  'Hydrogen',
+  'Helium',
+  'Lithium',
+  'Beryllium'
+];
+
+// This statement returns the array: [8, 6, 7, 9]
+elements.map(function(element) {
+  return element.length;
+});
+
+// The regular function above can be written as the arrow function below
+elements.map((element) => {
+  return element.length;
+}); // [8, 6, 7, 9]
+
+// When there is only one parameter, we can remove the surrounding parentheses
+elements.map(element => {
+  return element.length;
+}); // [8, 6, 7, 9]
+
+// When the only statement in an arrow function is `return`, we can remove `return` and remove
+// the surrounding curly brackets
+elements.map(element => element.length); // [8, 6, 7, 9]
+
+// In this case, because we only need the length property, we can use destructuring parameter:
+// Notice that the `length` corresponds to the property we want to get whereas the
+// obviously non-special `lengthFooBArX` is just the name of a variable which can be changed
+// to any valid variable name you want
+elements.map(({ length: lengthFooBArX }) => lengthFooBArX); // [8, 6, 7, 9]
+
+// This destructuring parameter assignment can also be written as seen below. However, note that in
+// this example we are not assigning `length` value to the made up property. Instead, the literal name
+// itself of the variable `length` is used as the property we want to retrieve from the object.
+elements.map(({ length }) => length); // [8, 6, 7, 9]
+
+ +

No separate this

+ +

Before arrow functions, every new function defined its own this value based on how the function was called:

+ + + +

This proved to be less than ideal with an object-oriented style of programming.

+ +
function Person() {
+  // The Person() constructor defines `this` as an instance of itself.
+  this.age = 0;
+
+  setInterval(function growUp() {
+    // In non-strict mode, the growUp() function defines `this`
+    // as the global object (because it's where growUp() is executed.),
+    // which is different from the `this`
+    // defined by the Person() constructor.
+    this.age++;
+  }, 1000);
+}
+
+var p = new Person();
+ +

In ECMAScript 3/5, the this issue was fixable by assigning the value in this to a variable that could be closed over.

+ +
function Person() {
+  var that = this;
+  that.age = 0;
+
+  setInterval(function growUp() {
+    // The callback refers to the `that` variable of which
+    // the value is the expected object.
+    that.age++;
+  }, 1000);
+}
+ +

Alternatively, a bound function could be created so that a preassigned this value would be passed to the bound target function (the growUp() function in the example above).

+ +

An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope, an arrow function ends up finding the this from its enclosing scope.

+ +

Thus, in the following code, the this within the function that is passed to setInterval has the same value as the this in the lexically enclosing function:

+ +
function Person(){
+  this.age = 0;
+
+  setInterval(() => {
+    this.age++; // |this| properly refers to the Person object
+  }, 1000);
+}
+
+var p = new Person();
+ +

Relation with strict mode

+ +

Given that this comes from the surrounding lexical context, strict mode rules with regard to this are ignored.

+ +
var f = () => { 'use strict'; return this; };
+f() === window; // or the global object
+ +

All other strict mode rules apply normally.

+ +

Invoked through call or apply

+ +

Since arrow functions do not have their own this, the methods call() and apply() can only pass in parameters. Any this argument is ignored.

+ +
var adder = {
+  base: 1,
+
+  add: function(a) {
+    var f = v => v + this.base;
+    return f(a);
+  },
+
+  addThruCall: function(a) {
+    var f = v => v + this.base;
+    var b = {
+      base: 2
+    };
+
+    return f.call(b, a);
+  }
+};
+
+console.log(adder.add(1));         // This would log 2
+console.log(adder.addThruCall(1)); // This would log 2 still
+ +

No binding of arguments

+ +

Arrow functions do not have their own arguments object. Thus, in this example, arguments is simply a reference to the arguments of the enclosing scope:

+ +
var arguments = [1, 2, 3];
+var arr = () => arguments[0];
+
+arr(); // 1
+
+function foo(n) {
+  var f = () => arguments[0] + n; // foo's implicit arguments binding. arguments[0] is n
+  return f();
+}
+
+foo(3); // 6
+ +

In most cases, using rest parameters is a good alternative to using an arguments object.

+ +
function foo(n) {
+  var f = (...args) => args[0] + n;
+  return f(10);
+}
+
+foo(1); // 11
+ +

Arrow functions used as methods

+ +

As stated previously, arrow function expressions are best suited for non-method functions. Let's see what happens when we try to use them as methods:

+ +
'use strict';
+
+var obj = { // does not create a new scope
+  i: 10,
+  b: () => console.log(this.i, this),
+  c: function() {
+    console.log(this.i, this);
+  }
+}
+
+obj.b(); // prints undefined, Window {...} (or the global object)
+obj.c(); // prints 10, Object {...}
+ +

Arrow functions do not have their own this. Another example involving {{jsxref("Object.defineProperty()")}}:

+ +
'use strict';
+
+var obj = {
+  a: 10
+};
+
+Object.defineProperty(obj, 'b', {
+  get: () => {
+    console.log(this.a, typeof this.a, this); // undefined 'undefined' Window {...} (or the global object)
+    return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined'
+  }
+});
+
+ +

Use of the new operator

+ +

Arrow functions cannot be used as constructors and will throw an error when used with new.

+ +
var Foo = () => {};
+var foo = new Foo(); // TypeError: Foo is not a constructor
+ +

Use of prototype property

+ +

Arrow functions do not have a prototype property.

+ +
var Foo = () => {};
+console.log(Foo.prototype); // undefined
+
+ +

Use of the yield keyword

+ +

The yield keyword may not be used in an arrow function's body (except when permitted within functions further nested within it). As a consequence, arrow functions cannot be used as generators.

+ +

Function body

+ +

Arrow functions can have either a "concise body" or the usual "block body".

+ +

In a concise body, only an expression is specified, which becomes the implicit return value. In a block body, you must use an explicit return statement.

+ +
var func = x => x * x;
+// concise body syntax, implied "return"
+
+var func = (x, y) => { return x + y; };
+// with block body, explicit "return" needed
+
+ +

Returning object literals

+ +

Keep in mind that returning object literals using the concise body syntax params => {object:literal} will not work as expected.

+ +
var func = () => { foo: 1 };
+// Calling func() returns undefined!
+
+var func = () => { foo: function() {} };
+// SyntaxError: function statement requires a name
+ +

This is because the code inside braces ({}) is parsed as a sequence of statements (i.e. foo is treated like a label, not a key in an object literal).

+ +

You must wrap the object literal in parentheses:

+ +
var func = () => ({ foo: 1 });
+ +

Line breaks

+ +

An arrow function cannot contain a line break between its parameters and its arrow.

+ +
var func = (a, b, c)
+  => 1;
+// SyntaxError: expected expression, got '=>'
+ +

However, this can be amended by putting the line break after the arrow or using parentheses/braces as seen below to ensure that the code stays pretty and fluffy. You can also put line breaks between arguments.

+ +
var func = (a, b, c) =>
+  1;
+
+var func = (a, b, c) => (
+  1
+);
+
+var func = (a, b, c) => {
+  return 1
+};
+
+var func = (
+  a,
+  b,
+  c
+) => 1;
+
+// no SyntaxError thrown
+ +

Parsing order

+ +

Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with operator precedence compared to regular functions.

+ +
let callback;
+
+callback = callback || function() {}; // ok
+
+callback = callback || () => {};
+// SyntaxError: invalid arrow-function arguments
+
+callback = callback || (() => {});    // ok
+
+ +

More examples

+ +
// An empty arrow function returns undefined
+let empty = () => {};
+
+(() => 'foobar')();
+// Returns "foobar"
+// (this is an Immediately Invoked Function Expression)
+
+var simple = a => a > 15 ? 15 : a;
+simple(16); // 15
+simple(10); // 10
+
+let max = (a, b) => a > b ? a : b;
+
+// Easy array filtering, mapping, ...
+
+var arr = [5, 6, 13, 0, 1, 18, 23];
+
+var sum = arr.reduce((a, b) => a + b);
+// 66
+
+var even = arr.filter(v => v % 2 == 0);
+// [6, 0, 18]
+
+var double = arr.map(v => v * 2);
+// [10, 12, 26, 0, 2, 36, 46]
+
+// More concise promise chains
+promise.then(a => {
+  // ...
+}).then(b => {
+  // ...
+});
+
+// Parameterless arrow functions that are visually easier to parse
+setTimeout( () => {
+  console.log('I happen sooner');
+  setTimeout( () => {
+    // deeper code
+    console.log('I happen later');
+  }, 1);
+}, 1);
+
+ +

Specifications

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.functions.arrow_functions")}}

+
+ +

See also

+ + diff --git a/files/pt-pt/web/javascript/reference/functions/index.html b/files/pt-pt/web/javascript/reference/functions/index.html new file mode 100644 index 0000000000..02b35fc7bd --- /dev/null +++ b/files/pt-pt/web/javascript/reference/functions/index.html @@ -0,0 +1,594 @@ +--- +title: Funções +slug: Web/JavaScript/Reference/Funcoes +tags: + - Constructor + - Função + - Funções + - JavaScript + - Parâmetro + - parâmetros +translation_of: Web/JavaScript/Reference/Functions +--- +
{{jsSidebar("Functions")}}
+ +

Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.

+ +

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

+ +

For more examples and explanations, see also the JavaScript guide about functions.

+ +

Descrição

+ +

Every function in JavaScript is a Function object. See {{jsxref("Function")}} for information on properties and methods of Function objects.

+ +

To return a value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is {{jsxref("undefined")}}.

+ +

The parameters of a function call are the function's arguments. Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example:

+ +
/* Declare the function 'myFunc' */
+function myFunc(theObject) {
+  theObject.brand = "Toyota";
+}
+
+/*
+ * Declare variable 'mycar';
+ * create and initialize a new Object;
+ * assign reference to it to 'mycar'
+ */
+var mycar = {
+  brand: "Honda",
+  model: "Accord",
+  year: 1998
+};
+
+/* Logs 'Honda' */
+console.log(mycar.brand);
+
+/* Pass object reference to the function */
+myFunc(mycar);
+
+/*
+ * Logs 'Toyota' as the value of the 'brand' property
+ * of the object, as changed to by the function.
+ */
+console.log(mycar.brand);
+
+ +

The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function body.

+ +

Definindo funções

+ +

There are several ways to define functions:

+ +

The function declaration (function statement)

+ +

There is a special syntax for declaring functions (see function statement for details):

+ +
function name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
+ +
+
statements
+
The statements comprising the body of the function.
+
+ +

The function expression (function expression)

+ +

A function expression is similar to and has the same syntax as a function declaration (see function expression for details). A function expression may be a part of a larger expression. One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. Function expressions are not hoisted onto the beginning of the scope, therefore they cannot be used before they appear in the code.

+ +
function [name]([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
statements
+
The statements comprising the body of the function.
+
+ +

Here is an example of an anonymous function expression (the name is not used):

+ +
var myFunction = function() {
+    statements
+}
+ +

It is also possible to provide a name inside the definition in order to create a named function expression:

+ +
var myFunction = function namedFunction(){
+    statements
+}
+
+ +

One of the benefit of creating a named function expression is that in case we encounted an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.

+ +

As we can see, both examples do not start with the function keyword. Statements involving functions which do not start with function are function expressions.

+ +

When functions are used only once, a common pattern is an IIFE (Immediately Invokable Function Expression).

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

IIFE are function expressions that are invoked as soon as the function is declared.

+ +

The generator function declaration (function* statement)

+ +

There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):

+ +
function* name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
+ +
+
statements
+
The statements comprising the body of the function.
+
+ +

The generator function expression (function* expression)

+ +

A generator function expression is similar to and has the same syntax as a generator function declaration (see {{jsxref('Operators/function*', 'function* expression')}} for details):

+ +
function* [name]([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
statements
+
The statements comprising the body of the function.
+
+ +

The arrow function expression (=>)

+ +

An arrow function expression has a shorter syntax and lexically binds its this value (see arrow functions for details):

+ +
([param[, param]]) => {
+   statements
+}
+
+param => expression
+
+ +
+
param
+
The name of an argument. Zero arguments need to be indicated with ().  For only one argument, the parentheses are not required. (like foo => 1)
+
statements or expression
+
Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of the function.
+
+ +

The Function constructor

+ +
+

Note: Using the Function constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

+
+ +

As all other objects, {{jsxref("Function")}} objects can be created using the new operator:

+ +
new Function (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.
+
+ +
+
functionBody
+
A string containing the JavaScript statements comprising the function body.
+
+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

The GeneratorFunction constructor

+ +
+

Note: GeneratorFunction is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).

+
+ +
+

Note: Using the GeneratorFunction constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

+
+ +

As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the new operator:

+ +
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
+
+ +
+
functionBody
+
A string containing the JavaScript statements comprising the function definition.
+
+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

Parâmetros de função

+ +

Parâmetros predefinidos

+ +

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. For more details, see default parameters.

+ +

Parâmetros Rest

+ +

The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see rest parameters.

+ +

O objeto arguments

+ +

You can refer to a function's arguments within the function by using the arguments object. See arguments.

+ + + +

Definindo funções de método

+ +

Getter and setter functions

+ +

You can define getters (accessor methods) and setters (mutator methods) on any standard built-in object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

+ +
+
get
+
+

Binds an object property to a function that will be called when that property is looked up.

+
+
set
+
Binds an object property to a function to be called when there is an attempt to set that property.
+
+ +

Method definition syntax

+ +

Starting with ECMAScript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. See method definitions for more information.

+ +
var obj = {
+  foo() {},
+  bar() {}
+};
+ +

Constructor vs. declaration vs. expression

+ +

Compare the following:

+ +

A function defined with the Function constructor assigned to the variable multiply:

+ +
var multiply = new Function('x', 'y', 'return x * y');
+ +

A function declaration of a function named multiply:

+ +
function multiply(x, y) {
+   return x * y;
+} // there is no semicolon here
+
+ +

A function expression of an anonymous function assigned to the variable multiply:

+ +
var multiply = function(x, y) {
+   return x * y;
+};
+
+ +

A function expression of a function named func_name assigned to the variable multiply:

+ +
var multiply = function func_name(x, y) {
+   return x * y;
+};
+
+ +

Differences

+ +

All do approximately the same thing, with a few subtle differences:

+ +

There is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example:

+ +
var y = function x() {};
+alert(x); // throws an error
+
+ +

The function name also appears when the function is serialized via Function's toString method.

+ +

On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope in which the function is declared.

+ +

As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other. A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:

+ +

A function defined by 'new Function' does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs:

+ +
function anonymous() {
+}
+
+ +

Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error:

+ +
var foo = new Function("alert(anonymous);");
+foo();
+
+ +

Unlike functions defined by function expressions or by the Function constructor, a function defined by a function declaration can be used before the function declaration itself. For example:

+ +
foo(); // alerts FOO!
+function foo() {
+   alert('FOO!');
+}
+
+ +

A function defined by a function expression or by a function declaration inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).

+ +
/*
+ * Declare and initialize a variable 'p' (global)
+ * and a function 'myFunc' (to change the scope) inside which
+ * declare a varible with same name 'p' (current) and
+ * define three functions using three different ways:-
+ *     1. function declaration
+ *     2. function expression
+ *     3. function constructor
+ * each of which will log 'p'
+ */
+var p = 5;
+function myFunc() {
+    var p = 9;
+
+    function decl() {
+        console.log(p);
+    }
+    var expr = function() {
+        console.log(p);
+    };
+    var cons = new Function('\tconsole.log(p);');
+
+    decl();
+    expr();
+    cons();
+}
+myFunc();
+
+/*
+ * Logs:-
+ * 9  - for 'decl' by function declaration (current scope)
+ * 9  - for 'expr' by function expression (current scope)
+ * 5  - for 'cons' by Function constructor (global scope)
+ */
+
+ +

Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function constructor must be parsed each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should generally be avoided whenever possible.

+ +

It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a Function constructor 's string aren't parsed repeatedly. For example:

+ +
var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))();
+foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.
+ +

A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:

+ + + +
var x = 0;               // source element
+if (x === 0) {           // source element
+   x = 10;               // not a source element
+   function boo() {}     // not a source element
+}
+function foo() {         // source element
+   var y = 20;           // source element
+   function bar() {}     // source element
+   while (y === 10) {    // source element
+      function blah() {} // not a source element
+      y++;               // not a source element
+   }
+}
+
+ +

Examples

+ +
// function declaration
+function foo() {}
+
+// function expression
+(function bar() {})
+
+// function expression
+x = function hello() {}
+
+
+if (x) {
+   // function expression
+   function world() {}
+}
+
+
+// function declaration
+function a() {
+   // function declaration
+   function b() {}
+   if (0) {
+      // function expression
+      function c() {}
+   }
+}
+
+ +

Block-level functions

+ +

In strict mode, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

+ +
'use strict';
+
+function f() {
+  return 1;
+}
+
+{
+  function f() {
+    return 2;
+  }
+}
+
+f() === 1; // true
+
+// f() === 2 in non-strict mode
+
+ +

Block-level functions in non-strict code

+ +

In a word: Don't.

+ +

In non-strict code, function declarations inside blocks behave strangely. For example:

+ +
if (shouldDefineZero) {
+   function zero() {     // DANGER: compatibility risk
+      console.log("This is zero.");
+   }
+}
+
+ +

ES2015 says that if shouldDefineZero is false, then zero should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define zero whether the block executed or not.

+ +

In strict mode, all browsers that support ES2015 handle this the same way: zero is defined only if shouldDefineZero is true, and only in the scope of the if-block.

+ +

A safer way to define functions conditionally is to assign a function expression to a variable:

+ +
var zero;
+if (shouldDefineZero) {
+   zero = function() {
+      console.log("This is zero.");
+   };
+}
+
+ +

Exemplos

+ +

Returning a formatted number

+ +

The following function returns a string containing the formatted representation of a number padded with leading zeros.

+ +
// This function returns a string padded with leading zeros
+function padZeros(num, totalLen) {
+   var numStr = num.toString();             // Initialize return value as string
+   var numZeros = totalLen - numStr.length; // Calculate no. of zeros
+   for (var i = 1; i <= numZeros; i++) {
+      numStr = "0" + numStr;
+   }
+   return numStr;
+}
+
+ +

The following statements call the padZeros function.

+ +
var result;
+result = padZeros(42,4); // returns "0042"
+result = padZeros(42,2); // returns "42"
+result = padZeros(5,4);  // returns "0005"
+
+ +

Determining whether a function exists

+ +

You can determine whether a function exists by using the typeof operator. In the following example, a test is performed to determine if the window object has a property called noFunc that is a function. If so, it is used; otherwise some other action is taken.

+ +
 if ('function' === typeof window.noFunc) {
+   // use noFunc()
+ } else {
+   // do something else
+ }
+
+ +

Note that in the if test, a reference to noFunc is used—there are no brackets "()" after the function name so the actual function is not called.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}}New: Arrow functions, Generator functions, default parameters, rest parameters.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.functions")}}

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/functions/rest_parameters/index.html b/files/pt-pt/web/javascript/reference/functions/rest_parameters/index.html new file mode 100644 index 0000000000..a21cb25ed6 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/functions/rest_parameters/index.html @@ -0,0 +1,234 @@ +--- +title: Parâmetros Rest +slug: Web/JavaScript/Reference/Funcoes/parametros_rest +tags: + - Funcionalidade Linguagem + - Funções + - JavaScript + - Parametros Rest + - Rest +translation_of: Web/JavaScript/Reference/Functions/rest_parameters +--- +
Parâmetrois {{jsSidebar("Functions")}}
+ +

A sintaxe do parâmetro "rest" permite-nos representar um número indefinido de argumentoscomo um array.

+ +
{{EmbedInteractiveExample("pages/js/functions-restparameters.html")}}
+ + + +

Sintaxe

+ +
function f(a, b, ...theArgs) {
+  // ...
+}
+ +

Descrição

+ +

A function's last parameter can be prefixed with ... which will cause all remaining (user supplied) arguments to be placed within a "standard" Javascript array.

+ +

Only the last parameter can be a "rest parameter".

+ +
function myFun(a, b, ...manyMoreArgs) {
+  console.log("a", a)
+  console.log("b", b)
+  console.log("manyMoreArgs", manyMoreArgs)
+}
+
+myFun("one", "two", "three", "four", "five", "six")
+
+// Console Output:
+// a, one
+// b, two
+// manyMoreArgs, [three, four, five, six]
+
+ +

Difference between rest parameters and the arguments object

+ +

There are three main differences between rest parameters and the {{jsxref("Functions/arguments", "arguments")}} object:

+ + + +

From arguments to an array

+ +

Rest parameters have been introduced to reduce the boilerplate code that was induced by the arguments

+ +
// Before rest parameters, "arguments" could be converted to a normal array using:
+
+function f(a, b) {
+
+  let normalArray = Array.prototype.slice.call(arguments)
+  // -- or --
+  let normalArray = [].slice.call(arguments)
+  // -- or --
+  let normalArray = Array.from(arguments)
+
+  let first = normalArray.shift()  // OK, gives the first argument
+  let first = arguments.shift()    // ERROR (arguments is not a normal array)
+}
+
+// Now, you can easily gain access to a normal array using a rest parameter
+
+function f(...args) {
+  let normalArray = args
+  let first = normalArray.shift() // OK, gives the first argument
+}
+
+ +

Destructuring rest parameters

+ +

Rest parameters can be destructured Arrays only (though objects will soon be supported). That means that their data can be unpacked into distinct variables. (See Destructuring assignment.)

+ +
function f(...[a, b, c]) {
+  return a + b + c;
+}
+
+f(1)          // NaN (b and c are undefined)
+f(1, 2, 3)    // 6
+f(1, 2, 3, 4) // 6 (the fourth parameter is not destructured)
+
+ +
+

Fixme

+ +

Doing this is possible, but (afaik) there's no use-case, so it's just confusing the junior audience. The following code does exactly the same. There should at least be a note, that in theory you can do something like this, but there is no point in doing so. The example is contrived, but imagine that [a, b, c] were the return value of some function. Then the utility is clear.

+ +

Also, since Function arguments will never have named parameters (this is not Python), the statement "objects will soon be supported" is wrong. The preceding example may be mixing up destructuring with rest parameters. Please see the page on destructuring assignment for an example with object destructuring applied in the parameters area.

+ +
function f(a, b, c) {
+  return a + b + c
+}
+
+f(1)          // NaN (b and c are undefined)
+f(1, 2, 3)    // 6
+f(1, 2, 3, 4) // 6 (the fourth parameter is not ...)
+
+
+ +

Exemplos

+ +

In this example, the first argument is mapped to a and the second to b, so these named arguments are used like normal.

+ +

However, the third argument, manyMoreArgs, will be an array that contains the 3rd, 4th, 5th, 6th ... nth — as many arguments that the user includes.

+ +
function myFun(a, b, ...manyMoreArgs) {
+  console.log("a", a)
+  console.log("b", b)
+  console.log("manyMoreArgs", manyMoreArgs)
+}
+
+myFun("one", "two", "three", "four", "five", "six")
+
+// a, one
+// b, two
+// manyMoreArgs, [three, four, five, six]
+
+ +

Below... even though there is just one value, the last argument still gets put into an array.

+ +
// using the same function definition from example above
+
+myFun("one", "two", "three")
+
+// a, one
+// b, two
+// manyMoreArgs, [three]
+ +

Below, the third argument isn't provided, but manyMoreArgs is still an array (albeit an empty one).

+ +
// using the same function definition from example above
+
+myFun("one", "two")
+
+// a, one
+// b, two
+// manyMoreArgs, []
+ +

Since theArgs is an array, a count of its elements is given by the length property:

+ +
function fun1(...theArgs) {
+  console.log(theArgs.length)
+}
+
+fun1()         // 0
+fun1(5)        // 1
+fun1(5, 6, 7)  // 3
+
+ +

In the next example, a rest parameter is used to collect all parameters after the first into an array. Each one of them is then multiplied by the first parameter, and the array is returned:

+ +
function multiply(multiplier, ...theArgs) {
+  return theArgs.map(function(element) {
+    return multiplier * element
+  })
+}
+
+let arr = multiply(2, 1, 2, 3)
+console.log(arr)  // [2, 4, 6]
+
+ +

Array methods can be used on rest parameters, but not on the arguments object:

+ +
function sortRestArgs(...theArgs) {
+  let sortedArgs = theArgs.sort()
+  return sortedArgs
+}
+
+console.log(sortRestArgs(5, 3, 7, 1)) // 1, 3, 5, 7
+
+function sortArguments() {
+  let sortedArgs = arguments.sort()
+  return sortedArgs  // this will never happen
+}
+
+
+console.log(sortArguments(5, 3, 7, 1))
+// throws a TypeError (arguments.sort is not a function)
+
+ +

To use Array methods on the arguments object, it must be converted to a real array first.

+ +
function sortArguments() {
+  let args = Array.from(arguments)
+  let sortedArgs = args.sort()
+  return sortedArgs
+}
+console.log(sortArguments(5, 3, 7, 1))  // 1, 3, 5, 7
+
+ +

Especificações

+ + + + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}}
+ +

Compatibildiade de navegador

+ + + +

{{Compat("javascript.functions.rest_parameters")}}

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/asyncfunction/prototype/index.html b/files/pt-pt/web/javascript/reference/global_objects/asyncfunction/prototype/index.html deleted file mode 100644 index 8a085d6986..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/asyncfunction/prototype/index.html +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: AsyncFunction.prototype -slug: Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype -translation_of: Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype ---- -
{{JSRef}}
- -

A propriedade AsyncFunction.prototype representa o objecto prototype {{jsxref("AsyncFunction")}}.

- -

Description

- -

Os objectos {{jsxref("AsyncFunction")}} são herdados de AsyncFunction.prototype e não podem ser modificados.

- -

Propriedades

- -
-
AsyncFunction.constructor
-
O valor inicial é {{jsxref("AsyncFunction")}}.
-
AsyncFunction.prototype[@@toStringTag]
-
Retorna "AsyncFunction".
-
- -

Especificações

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-async-function-constructor-prototype', 'AsyncFunction.prototype')}}{{Spec2('ESDraft')}}Definição inicial ES2017.
- -

Compatibilidade entre navegadores

- -
- - -

{{Compat("javascript.builtins.AsyncFunction.prototype")}}

-
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/prototype/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/prototype/index.html deleted file mode 100644 index 9014ecdb24..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/number/prototype/index.html +++ /dev/null @@ -1,131 +0,0 @@ ---- -title: Number.prototype -slug: Web/JavaScript/Reference/Global_Objects/Number/prototype -tags: - - JavaScript - - Number - - Property - - Prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Number -translation_of_original: Web/JavaScript/Reference/Global_Objects/Number/prototype ---- -
{{JSRef}}
- -

A propriedade Number.prototype representa o protótipo (prototype) para o constructor de {{jsxref("Number")}}.

- -
{{js_property_attributes(0, 0, 0)}}
- -

Descrição

- -

Todas as instâncias de {{jsxref("Number")}} herdam de Number.prototype. O objecto protótipo (prototype) do constructor de {{jsxref("Number")}} pode ser modificado para afectar todas as instâncias de {{jsxref( "Number")}}.

- -

Propriedades

- -
-
Number.prototype.constructor
-
Retorna a função criadora das instâncias deste objecto. Por predifinição este é o objecto {{jsxref("Number")}}.
-
- -

Métodos

- -
-
{{jsxref("Number.prototype.toExponential()")}}
-
Retorna uma representação em string do número em notação científica.
-
{{jsxref("Number.prototype.toFixed()")}}
-
Retorna uma representação em string do número em notação de ponto fixo.
-
{{jsxref("Number.prototype.toLocaleString()")}}
-
Retorna uma string do número numa representação sensível à linguagem. Faz override do método {{jsxref("Object.prototype.toLocaleString()")}}.
-
{{jsxref("Number.prototype.toPrecision()")}}
-
Retorna uma representação em string do número numa precisão especificada em ponto fixo ou notação científica.
-
{{jsxref("Number.prototype.toSource()")}} {{non-standard_inline}}
-
Retorna um objecto literal representando o objecto {{jsxref("Number")}} especificado; podes usar este valor para criar um novo objecto. Faz override ao método {{jsxref("Object.prototype.toSource()")}}.
-
{{jsxref("Number.prototype.toString()")}}
-
Retorna uma representação em string do objecto especificado na base especificada. Faz override ao método {{jsxref("Object.prototype.toString()")}}.
-
{{jsxref("Number.prototype.valueOf()")}}
-
Retorna o valor primitivo do objecto especificado. Faz override ao método {{jsxref("Object.prototype.valueOf()")}}.
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição Inicial. Implementado em  JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.4', 'Number')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-the-number-prototype-object', 'Number')}}{{Spec2('ES6')}} 
- -

Compatibilidade dos browsers

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/object/prototype/index.html b/files/pt-pt/web/javascript/reference/global_objects/object/prototype/index.html deleted file mode 100644 index 411832665a..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/object/prototype/index.html +++ /dev/null @@ -1,199 +0,0 @@ ---- -title: Object.prototype -slug: Web/JavaScript/Reference/Global_Objects/Object/prototype -tags: - - JavaScript - - Object - - Objeto - - Propriedade -translation_of: Web/JavaScript/Reference/Global_Objects/Object -translation_of_original: Web/JavaScript/Reference/Global_Objects/Object/prototype ---- -
{{JSRef}}
- -

A propriedade Object.prototype representa o prototype object {{jsxref("Object","Objeto")}} .

- -
{{js_property_attributes(0, 0, 0)}}
- -

Descrição

- -

Nearly all objects in JavaScript are instances of {{jsxref("Object")}}; a typical object inherits properties (including methods) from Object.prototype, although these properties may be shadowed (a.k.a. overridden). However, an Object may be deliberately created for which this is not true (e.g. by {{jsxref("Object.create", "Object.create(null)")}}), or it may be altered so that this is no longer true (e.g. with {{jsxref("Object.setPrototypeOf")}}).

- -

Changes to the Object prototype object are seen by all objects through prototype chaining, unless the properties and methods subject to those changes are overridden further along the prototype chain.  This provides a very powerful although potentially dangerous mechanism to override or extend object behavior.

- -

Propriedades

- -
-
{{jsxref("Object.prototype.constructor")}}
-
Specifies the function that creates an object's prototype.
-
{{jsxref("Object.prototype.__proto__")}} {{non-standard_inline}}
-
Points to the object which was used as prototype when the object was instantiated.
-
{{jsxref("Object.prototype.__noSuchMethod__")}} {{non-standard_inline}}
-
Allows a function to be defined that will be executed when an undefined object member is called as a method.
-
{{jsxref("Object.prototype.count","Object.prototype.__count__")}} {{obsolete_inline}}
-
Used to return the number of enumerable properties directly on a user-defined object, but has been removed.
-
{{jsxref("Object.prototype.parent","Object.prototype.__parent__")}} {{obsolete_inline}}
-
Used to point to an object's context, but has been removed.
-
- -

Métodos

- -
-
{{jsxref("Object.prototype.__defineGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
-
Associates a function with a property that, when accessed, executes that function and returns its return value.
-
{{jsxref("Object.prototype.__defineSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
-
Associates a function with a property that, when set, executes that function which modifies the property.
-
{{jsxref("Object.prototype.__lookupGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
-
Returns the function associated with the specified property by the {{jsxref("Object.prototype.__defineGetter__()", "__defineGetter__()")}} method.
-
{{jsxref("Object.prototype.__lookupSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
-
Returns the function associated with the specified property by the {{jsxref("Object.prototype.__defineSetter__()", "__defineSetter__()")}} method.
-
{{jsxref("Object.prototype.hasOwnProperty()")}}
-
Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain.
-
{{jsxref("Object.prototype.isPrototypeOf()")}}
-
Returns a boolean indicating whether the object this method is called upon is in the prototype chain of the specified object.
-
{{jsxref("Object.prototype.propertyIsEnumerable()")}}
-
Returns a boolean indicating if the internal ECMAScript [[Enumerable]] attribute is set.
-
{{jsxref("Object.prototype.toSource()")}} {{non-standard_inline}}
-
Returns string containing the source of an object literal representing the object that this method is called upon; you can use this value to create a new object.
-
{{jsxref("Object.prototype.toLocaleString()")}}
-
Calls {{jsxref("Object.toString", "toString()")}}.
-
{{jsxref("Object.prototype.toString()")}}
-
Returns a string representation of the object.
-
{{jsxref("Object.prototype.unwatch()")}} {{non-standard_inline}}
-
Removes a watchpoint from a property of the object.
-
{{jsxref("Object.prototype.valueOf()")}}
-
Returns the primitive value of the specified object.
-
{{jsxref("Object.prototype.watch()")}} {{non-standard_inline}}
-
Adds a watchpoint to a property of the object.
-
{{jsxref("Object.prototype.eval()")}} {{obsolete_inline}}
-
Used to evaluate a string of JavaScript code in the context of the specified object, but has been removed.
-
- -

Exemplos

- -

When altering the behavior of existing Object.prototype methods, consider injecting code by wrapping your extension before or after the existing logic.  For example, this (untested) code will pre-conditionally execute custom logic before the built-in logic or someone else's extension is executed.

- -

When a function is called, the arguments to the call are held in the array-like "variable" arguments. For example, in the call "myFn(a, b, c)", the arguments within myFn's body will contain 3 array-like elements corresponding to (a, b, c).  When modifying prototypes with hooks, simply pass this & the arguments (the call state) to the current behavior by calling apply() on the function.  This pattern can be used for any prototype, such as Node.prototype, Function.prototype, etc.

- -
var current = Object.prototype.valueOf;
-
-// Since my property "-prop-value" is cross-cutting and isn't always
-// on the same prototype chain, I want to modify Object.prototype:
-Object.prototype.valueOf = function() {
-  if (this.hasOwnProperty('-prop-value')) {
-    return this['-prop-value'];
-  } else {
-    // It doesn't look like one of my objects, so let's fall back on
-    // the default behavior by reproducing the current behavior as best we can.
-    // The apply behaves like "super" in some other languages.
-    // Even though valueOf() doesn't take arguments, some other hook may.
-    return current.apply(this, arguments);
-  }
-}
-
- -

Since JavaScript doesn't exactly have sub-class objects, prototype is a useful workaround to make a “base class” object of certain functions that act as objects. For example:

- -
var Person = function(name) {
-  this.name = name;
-  this.canTalk = true;
-};
-
-Person.prototype.greet = function() {
-  if (this.canTalk) {
-    console.log('Hi, I am ' + this.name);
-  }
-};
-
-var Employee = function(name, title) {
-  Person.call(this, name);
-  this.title = title;
-};
-
-Employee.prototype = Object.create(Person.prototype);
-
-Employee.prototype.greet = function() {
-  if (this.canTalk) {
-    console.log('Hi, I am ' + this.name + ', the ' + this.title);
-  }
-};
-
-var Customer = function(name) {
-  Person.call(this, name);
-};
-
-Customer.prototype = Object.create(Person.prototype);
-
-var Mime = function(name) {
-  Person.call(this, name);
-  this.canTalk = false;
-};
-
-Mime.prototype = Object.create(Person.prototype);
-
-var bob = new Employee('Bob', 'Builder');
-var joe = new Customer('Joe');
-var rg = new Employee('Red Green', 'Handyman');
-var mike = new Customer('Mike');
-var mime = new Mime('Mime');
-
-bob.greet();
-// Hi, I am Bob, the Builder
-
-joe.greet();
-// Hi, I am Joe
-
-rg.greet();
-// Hi, I am Red Green, the Handyman
-
-mike.greet();
-// Hi, I am Mike
-
-mime.greet();
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2.3.1', 'Object.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype', 'Object.prototype')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.prototype', 'Object.prototype')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade de navegador

- -
- - -

{{Compat("javascript.builtins.Object.prototype")}}

-
- -

Consultar também

- - diff --git "a/files/pt-pt/web/javascript/reference/operadores/fun\303\247\303\243o/index.html" "b/files/pt-pt/web/javascript/reference/operadores/fun\303\247\303\243o/index.html" deleted file mode 100644 index 450183b727..0000000000 --- "a/files/pt-pt/web/javascript/reference/operadores/fun\303\247\303\243o/index.html" +++ /dev/null @@ -1,139 +0,0 @@ ---- -title: Expressão função (Function expression) -slug: Web/JavaScript/Reference/Operadores/função -tags: - - Expressões Primárias - - Funiconaldiade de Linguagem - - Função - - JavaScript - - Operador -translation_of: Web/JavaScript/Reference/Operators/function ---- -
{{jsSidebar("Operators")}}
- -

A palavra-chave function  pode ser utilziada para definir uma função dentro de uma expressão.

- -

You can also define functions using the Function constructor and a function declaration.

- -
{{EmbedInteractiveExample("pages/js/expressions-functionexpression.html", "shorter")}}
- - - -

Sintaxe

- -
let myFunction = function [name]([param1[, param2[, ..., paramN]]]) {
-   statements
-};
- -

As of ES2015, you can also use {{jsxref("Functions/Arrow_functions", "arrow functions")}}.

- -

Parâmetros

- -
-
name {{optional_inline}}
-
The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function body.
-
paramN {{optional_inline}}
-
The name of an argument to be passed to the function.
-
statements {{optional_inline}}
-
The statements which comprise the body of the function.
-
- -

Descrição

- -

A function expression is very similar to and has almost the same syntax as a function declaration (see {{jsxref("Statements/function", "function statement")}} for details). The main difference between a function expression and a function declaration is the function name, which can be omitted in function expressions to create anonymous functions. A function expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined. See also the chapter about {{jsxref("Functions", "functions")}} for more information.

- -

Function expression hoisting

- -

Function expressions in JavaScript are not hoisted, unlike {{jsxref("Statements/function", "function declarations", "#Function_declaration_hoisting")}}. You can't use function expressions before you define them:

- -
console.log(notHoisted) // undefined
-//  even though the variable name is hoisted, the definition isn't. so it's undefined.
-notHoisted(); // TypeError: notHoisted is not a function
-
-var notHoisted = function() {
-   console.log('bar');
-};
-
- -

Named function expression

- -

If you want to refer to the current function inside the function body, you need to create a named function expression. This name is then local only to the function body (scope). This also avoids using the non-standard {{jsxref("Functions/arguments/callee", "arguments.callee")}} property.

- -
let math = {
-  'factit': function factorial(n) {
-    console.log(n)
-    if (n <= 1) {
-      return 1;
-    }
-    return n * factorial(n - 1);
-  }
-};
-
-math.factit(3) //3;2;1;
-
- -

The variable the function expression is assigned to will have a name property. The name doesn't change if it's assigned to a different variable. If function name is omitted, it will be the variable name (implicit name). If function name is present, it will be the function name (explicit name). This also applies to {{jsxref("Functions/Arrow_functions", "arrow functions")}} (arrows don't have a name so you can only give the variable an implicit name).

- -
var foo = function() {}
-foo.name // "foo"
-
-var foo2 = foo
-foo2.name // "foo"
-
-var bar = function baz() {}
-bar.name // "baz"
-
-console.log(foo === foo2); // true
-console.log(typeof baz); // undefined
-console.log(bar === baz); // false (errors because baz == undefined)
-
- -

Exemplos

- -

The following example defines an unnamed function and assigns it to x. The function returns the square of its argument:

- -
var x = function(y) {
-   return y * y;
-};
-
- -

More commonly it is used as a callback:

- -
button.addEventListener('click', function(event) {
-    console.log('button is clicked!')
-})
- -

Especificações

- - - - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}
- -

Compatibilidade de navegador

- - - -

{{Compat("javascript.operators.function")}}

- -

Consulte também 

- - diff --git a/files/pt-pt/web/javascript/reference/operadores/index.html b/files/pt-pt/web/javascript/reference/operadores/index.html deleted file mode 100644 index 02a550b7b0..0000000000 --- a/files/pt-pt/web/javascript/reference/operadores/index.html +++ /dev/null @@ -1,309 +0,0 @@ ---- -title: Expressões e operadores -slug: Web/JavaScript/Reference/Operadores -tags: - - JavaScript - - Operadores - - Página Landing - - Resumo - - Sinopse -translation_of: Web/JavaScript/Reference/Operators ---- -
{{jsSidebar("Operators")}}
- -

Este capítulo documenta todos os operadores, expressões e palavras-chave da linguagem JavaScript.

- -

Expressões e operadores por categoria

- -

For an alphabetical listing see the sidebar on the left.

- -

Expressões primárias

- -

Basic keywords and general expressions in JavaScript.

- -
-
{{JSxRef("Operators/this", "this")}}
-
The this keyword refers to a special property of an execution context.
-
{{JSxRef("Operators/function", "function")}}
-
The function keyword defines a function expression.
-
{{JSxRef("Operators/class", "class")}}
-
The class keyword defines a class expression.
-
{{JSxRef("Operators/function*", "function*")}}
-
The function* keyword defines a generator function expression.
-
{{JSxRef("Operators/yield", "yield")}}
-
Pause and resume a generator function.
-
{{JSxRef("Operators/yield*", "yield*")}}
-
Delegate to another generator function or iterable object.
-
{{JSxRef("Operators/async_function", "async function")}}
-
The async function defines an async function expression.
-
{{JSxRef("Operators/await", "await")}}
-
Pause and resume an async function and wait for the promise's resolution/rejection.
-
{{JSxRef("Global_Objects/Array", "[]")}}
-
Array initializer/literal syntax.
-
{{JSxRef("Operators/Object_initializer", "{}")}}
-
Object initializer/literal syntax.
-
{{JSxRef("Global_Objects/RegExp", "/ab+c/i")}}
-
Regular expression literal syntax.
-
{{JSxRef("Operators/Grouping", "( )")}}
-
Grouping operator.
-
- -

Expressões "Left-hand-side"

- -

Left values are the destination of an assignment.

- -
-
{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
-
Member operators provide access to a property or method of an object
- (object.property and object["property"]).
-
{{jsxref("Operators/new", "new")}}
-
The new operator creates an instance of a constructor.
-
new.target
-
In constructors, new.target refers to the constructor that was invoked by {{jsxref("Operators/new", "new")}}.
-
{{jsxref("Operators/super", "super")}}
-
The super keyword calls the parent constructor.
-
{{jsxref("Operators/Spread_operator", "...obj")}}
-
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
-
- -

Aumento e diminuição

- -

Postfix/prefix increment and postfix/prefix decrement operators.

- -
-
{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}
-
Postfix increment operator.
-
{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}
-
Postfix decrement operator.
-
{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}
-
Prefix increment operator.
-
{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}
-
Prefix decrement operator.
-
- -

Operadores unários

- -

A unary operation is operation with only one operand.

- -
-
{{jsxref("Operators/delete", "delete")}}
-
The delete operator deletes a property from an object.
-
{{jsxref("Operators/void", "void")}}
-
The void operator discards an expression's return value.
-
{{jsxref("Operators/typeof", "typeof")}}
-
The typeof operator determines the type of a given object.
-
{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}
-
The unary plus operator converts its operand to Number type.
-
{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}
-
The unary negation operator converts its operand to Number type and then negates it.
-
{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}
-
Bitwise NOT operator.
-
{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}
-
Logical NOT operator.
-
- -

Operadores de aritmética

- -

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

- -
-
{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}
-
Addition operator.
-
{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}
-
Subtraction operator.
-
{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}
-
Division operator.
-
{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}
-
Multiplication operator.
-
{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}
-
Remainder operator.
-
- -
-
{{JSxRef("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}
-
Exponentiation operator.
-
- -

Operadores relacionais

- -

A comparison operator compares its operands and returns a Boolean value based on whether the comparison is true.

- -
-
{{jsxref("Operators/in", "in")}}
-
The in operator determines whether an object has a given property.
-
{{jsxref("Operators/instanceof", "instanceof")}}
-
The instanceof operator determines whether an object is an instance of another object.
-
{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}
-
Less than operator.
-
{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}
-
Greater than operator.
-
{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}
-
Less than or equal operator.
-
{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}
-
Greater than or equal operator.
-
- -
-

Nota: => não é um operador, mas a notação para funções seta (arrow).

-
- -

Operadores de equality

- -

The result of evaluating an equality operator is always of type Boolean based on whether the comparison is true.

- -
-
{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}
-
Equality operator.
-
{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}
-
Inequality operator.
-
{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}
-
Identity operator.
-
{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}
-
Nonidentity operator.
-
- -

Bitwise shift operators

- -

Operations to shift all bits of the operand.

- -
-
{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}
-
Bitwise left shift operator.
-
{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}
-
Bitwise right shift operator.
-
{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}
-
Bitwise unsigned right shift operator.
-
- -

Operadores de binário bitwise

- -

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

- -
-
{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}
-
Bitwise AND.
-
{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}
-
Bitwise OR.
-
{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}
-
Bitwise XOR.
-
- -

Operadores de binário logical

- -

Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.

- -
-
{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}
-
Logical AND.
-
{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}
-
Logical OR.
-
- -

Operdor condicional (ternário)

- -
-
{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}
-
-

The conditional operator returns one of two values based on the logical value of the condition.

-
-
- -

Operadores de Assignment

- -

An assignment operator assigns a value to its left operand based on the value of its right operand.

- -
-
{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}
-
Assignment operator.
-
{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}
-
Multiplication assignment.
-
{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}
-
Division assignment.
-
{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}
-
Remainder assignment.
-
{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}
-
Addition assignment.
-
{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}
-
Subtraction assignment
-
{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}
-
Left shift assignment.
-
{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}
-
Right shift assignment.
-
{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}
-
Unsigned right shift assignment.
-
{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}
-
Bitwise AND assignment.
-
{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}
-
Bitwise XOR assignment.
-
{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}
-
Bitwise OR assignment.
-
{{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
- {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}
-
-

Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.

-
-
- -

Operador de aspas

- -
-
{{jsxref("Operators/Comma_Operator", ",")}}
-
The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.
-
- -

Funcionalidades não padrão

- -
-
{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}
-
The function keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function body should contains at least one {{jsxref("Operators/yield", "yield")}} expression.
-
{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}
-
The expression closure syntax is a shorthand for writing simple function.
-
{{non-standard_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}
-
Array comprehensions.
-
{{non-standard_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}
-
Generator comprehensions.
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1', '#sec-11', 'Expressions')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES5.1', '#sec-11', 'Expressions')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ES6')}}New: Spread operator, destructuring assignment, super keyword.
{{SpecName('ESDraft', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ESDraft')}}
- -

Compatibilidade de navegador

- - - -

{{Compat("javascript.operators")}}

- -

Consulte também

- - diff --git a/files/pt-pt/web/javascript/reference/operadores/operador_virgula/index.html b/files/pt-pt/web/javascript/reference/operadores/operador_virgula/index.html deleted file mode 100644 index e797f92953..0000000000 --- a/files/pt-pt/web/javascript/reference/operadores/operador_virgula/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Operador Vírgula -slug: Web/JavaScript/Reference/Operadores/Operador_virgula -tags: - - Composto - - Expressão - - Funcionalidade de Linguagem - - JavaScript - - Operador - - Referencia - - Vírgula -translation_of: Web/JavaScript/Reference/Operators/Comma_Operator ---- -
Operador {{jsSidebar("Operators")}}
- -

operador vírgula (,) avalia cada um dos seus operandos (da esquerda para a direita) e devolve o valor do último operando. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions. This is commonly used to provide multiple parameters to a for loop.

- -
{{EmbedInteractiveExample("pages/js/expressions-commaoperators.html")}}
- - - -

Sintaxe

- -
expr1, expr2, expr3...
- -

Parâmetros

- -
-
expr1, expr2, expr3...
-
One or more expressions, the last of which is returned as the value of the compound expression.
-
- -

Notas de utilização

- -

You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop.

- -

The comma operator is fully different from the comma within arrays, objects, and function arguments and parameters.

- -

Exemplos

- -

If a is a 2-dimensional array with 10 elements on each side, the following code uses the comma operator to increment i and decrement j at once.

- -

The following code prints the values of the diagonal elements in the array:

- -
for (var i = 0, j = 9; i <= 9; i++, j--)
-  console.log('a[' + i + '][' + j + '] = ' + a[i][j]);
- -

Note that the comma operators in assignments may appear not to have the normal effect of comma operators because they don't exist within an expression. In the following example, a is set to the value of b = 3 (which is 3), but the c = 4 expression still evaluates and its result returned to console (i.e., 4). This is due to operator precedence and associativity.

- -
var a, b, c;
-
-a = b = 3, c = 4; // Returns 4 in console
-console.log(a); // 3 (left-most)
-
-var x, y, z;
-
-x = (y = 5, z = 6); // Returns 6 in console
-console.log(x); // 6 (right-most)
-
- -

Processing and then returning

- -

Another example that one could make with comma operator is processing before returning. As stated, only the last element will be returned but all others are going to be evaluated as well. So, one could do:

- -
function myFunc() {
-  var x = 0;
-
-  return (x += 1, x); // the same as return ++x;
-}
- -

Especificações

- - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-comma-operator', 'Comma operator')}}
- -

Compatibilidade de navegador

- - - -

{{Compat("javascript.operators.comma")}}

- -

Consulte também

- - diff --git a/files/pt-pt/web/javascript/reference/operadores/precedencia_operador/index.html b/files/pt-pt/web/javascript/reference/operadores/precedencia_operador/index.html deleted file mode 100644 index 03d4345410..0000000000 --- a/files/pt-pt/web/javascript/reference/operadores/precedencia_operador/index.html +++ /dev/null @@ -1,461 +0,0 @@ ---- -title: Precedência de operador -slug: Web/JavaScript/Reference/Operadores/Precedencia_operador -tags: - - Guía - - JavaScript - - precedência -translation_of: Web/JavaScript/Reference/Operators/Operator_Precedence ---- -
{{jsSidebar("Operators")}}
- -

A precedência de operador determina a maneira pela qual os operadores são analisados ​​em relação a cada um. Os operadores com maior precedência tornam-se operandos dos operadores com menor precedência..

- -
{{EmbedInteractiveExample("pages/js/expressions-operatorprecedence.html")}}
- - - -

Precedência e Associabilidade

- -

Consider an expression describable by the representation below. Note that both OP1 and OPare fill-in-the-blanks for OPerators.

- -
a OP b OP c
-
- -

If OP1 and OP2 have different precedence levels (see the table below), the operator with the highest precedence goes first and associativity does not matter. Observe how multiplication has higher associativity than addition and executed first, even though addition is written first in the code.

- -
console.log(3 + 10 * 2);   // logs 23
-console.log(3 + (10 * 2)); // logs 23 because parentheses here are superfluous
-console.log((3 + 10) * 2); // logs 26 because the parentheses change the order 
- -

Left-associativity (left-to-right) means that it is processed as (a OP1 b) OP2 c, while right-associativity (right-to-left) means it is interpreted as a OP1 (b OP2 c). Assignment operators are right-associative, so you can write:

- -
a = b = 5; // same as writing a = (b = 5);
-
- -

with the expected result that a and b get the value 5. This is because the assignment operator returns the value that is assigned. First, b is set to 5. Then the a is also set to 5, the return value of b = 5, aka right operand of the assignment.

- -

As another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity. It is interesting to note that, the order of evaluation is always left-to-right irregardless of associativity.

- - - - - - - - - - - - - - - - -
CódigoResultado
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the division operator (/)
-console.log(echo("left", 6) / echo("right", 2));
-
-
-
-Evaluating the left side
-Evaluating the right side
-3
-
-
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the exponentiation operator (**)
-console.log(echo("left", 2) ** echo("right", 3));
-
-
-Evaluating the left side
-Evaluating the right side
-8
-
- -

The difference in associativity comes into play when there are multiple operators of the same precedence. With only one operator or operators of different precedences, associativity does affect the output, as seen in the example above. In the example below, observe how associativity affects the output when multiple of the same operator are used.

- - - - - - - - - - - - - - - - - - - - -
CódigoResultado
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the division operator (/)
-console.log(echo("left", 6) / echo("middle", 2) / echo("right", 3));
-
-
-
-Evaluating the left side
-Evaluating the middle side
-Evaluating the right side
-1
-
-
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the exponentiation operator (**)
-console.log(echo("left", 2) ** echo("middle", 3) ** echo("right", 2));
-
-
-
-Evaluating the left side
-Evaluating the middle side
-Evaluating the right side
-512
-
-
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the parentheses around the left and middle exponentiation
-console.log((echo("left", 2) ** echo("middle", 3)) ** echo("right", 2));
-
-
-Evaluating the left side
-Evaluating the middle side
-Evaluating the right side
-64
-
- -

Looking at the code snippets above, 6 / 3 / 2 is the same as (6 / 3) / 2 because division is left-associative. Exponentiation, on the other hand, is right-associative, so 2 ** 3 ** 2 is the same as 2 ** (3 ** 2). Thus, doing (2 ** 3) ** 2 changes the order and results in the 64 seen in the table above.

- -

Remember that precedence comes before associativity. So, mixing division and exponentiation, the exponentiation comes before the division. For example, 2 ** 3 / 3 ** 2 results in 0.8888888888888888 because it is the same as (2 ** 3) / (3 ** 2).

- -

Note on Grouping and Short-Circuiting

- -

In the table below, Grouping is listed as having the highest precedence. However, that does not always mean the expression within the grouping symbols ( … ) is evaluated first, especially when it comes to short-circuiting.

- -

Short-circuiting is jargon for conditional evaluation. For example, in the expression a && (b + c), if a is “falsy”, then the sub-expression (b + c) will not even get evaluated, even if it is in parentheses. We could say that the logical disjunction operator (“OR”) is “short-circuited”. Along with logical disjunction, other short-circuited operators include logical conjunction (“AND”), nullish-coalescing, optional chaining, and the conditional operator. Some more examples follow.

- -
a || (b * c);  // evaluate `a` first, then produce `a` if `a` is “truthy”
-a && (b < c);  // evaluate `a` first, then produce `a` if `a` is “falsy”
-a ?? (b || c); // evaluate `a` first, then produce `a` if `a` is not `null` and not `undefined`
-a?.b.c;        // evaluate `a` first, then produce `a` if `a` is `null` or `undefined`
-
- -

Exemplos

- -
3 > 2 && 2 > 1
-// returns true
-
-3 > 2 > 1
-// Returns false because 3 > 2 is true, then true is converted to 1 in inequality operators, therefore true > 1 becomes 1 > 1, which
-//  is false. Adding parentheses makes things clear: (3 > 2) > 1.
-
-
- -

Tabela

- -

The following table is ordered from highest (20) to lowest (1) precedence.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PrecedênciaTipo de operador (Operator)AssociatividadeOperadores individuais
20{{jsxref("Operators/Grouping", "Grouping")}}n/a( … )
19{{jsxref("Operators/Property_Accessors", "Member Access", "#Dot_notation")}}left-to-right… . …
{{jsxref("Operators/Property_Accessors", "Computed Member Access","#Bracket_notation")}}left-to-right… [ … ]
{{jsxref("Operators/new","new")}} (with argument list)n/anew … ( … )
Function Callleft-to-right… ( … )
18{{jsxref("Operators/new","new")}} (without argument list)right-to-leftnew …
17{{jsxref("Operators/Arithmetic_Operators","Postfix Increment","#Increment")}}n/a… ++
{{jsxref("Operators/Arithmetic_Operators","Postfix Decrement","#Decrement")}}… --
16Logical NOTright-to-left! …
Bitwise NOT~ …
Unary Plus+ …
Unary Negation- …
Prefix Increment++ …
Prefix Decrement-- …
typeoftypeof …
voidvoid …
deletedelete …
awaitawait …
15Exponentiationright-to-left… ** …
14Multiplicationleft-to-right… * …
Division… / …
Remainder… % …
13Additionleft-to-right… + …
Subtraction… - …
12Bitwise Left Shiftleft-to-right… << …
Bitwise Right Shift… >> …
Bitwise Unsigned Right Shift… >>> …
11Less Thanleft-to-right… < …
Less Than Or Equal… <= …
Greater Than… > …
Greater Than Or Equal… >= …
in… in …
instanceof… instanceof …
10Equalityleft-to-right… == …
Inequality… != …
Strict Equality… === …
Strict Inequality… !== …
9Bitwise ANDleft-to-right… & …
8Bitwise XORleft-to-right… ^ …
7Bitwise ORleft-to-right… | …
6Logical ANDleft-to-right… && …
5Logical ORleft-to-right… || …
4Conditionalright-to-left… ? … : …
3Assignmentright-to-left… = …
… += …
… -= …
… **= …
… *= …
… /= …
… %= …
… <<= …
… >>= …
… >>>= …
… &= …
… ^= …
… |= …
2{{jsxref("Operators/yield", "yield")}}right-to-leftyield …
{{jsxref("Operators/yield*", "yield*")}}yield* …
1Vírgula / Sequêncialeft-to-right… , …
diff --git a/files/pt-pt/web/javascript/reference/operators/comma_operator/index.html b/files/pt-pt/web/javascript/reference/operators/comma_operator/index.html new file mode 100644 index 0000000000..e797f92953 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/operators/comma_operator/index.html @@ -0,0 +1,94 @@ +--- +title: Operador Vírgula +slug: Web/JavaScript/Reference/Operadores/Operador_virgula +tags: + - Composto + - Expressão + - Funcionalidade de Linguagem + - JavaScript + - Operador + - Referencia + - Vírgula +translation_of: Web/JavaScript/Reference/Operators/Comma_Operator +--- +
Operador {{jsSidebar("Operators")}}
+ +

operador vírgula (,) avalia cada um dos seus operandos (da esquerda para a direita) e devolve o valor do último operando. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions. This is commonly used to provide multiple parameters to a for loop.

+ +
{{EmbedInteractiveExample("pages/js/expressions-commaoperators.html")}}
+ + + +

Sintaxe

+ +
expr1, expr2, expr3...
+ +

Parâmetros

+ +
+
expr1, expr2, expr3...
+
One or more expressions, the last of which is returned as the value of the compound expression.
+
+ +

Notas de utilização

+ +

You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop.

+ +

The comma operator is fully different from the comma within arrays, objects, and function arguments and parameters.

+ +

Exemplos

+ +

If a is a 2-dimensional array with 10 elements on each side, the following code uses the comma operator to increment i and decrement j at once.

+ +

The following code prints the values of the diagonal elements in the array:

+ +
for (var i = 0, j = 9; i <= 9; i++, j--)
+  console.log('a[' + i + '][' + j + '] = ' + a[i][j]);
+ +

Note that the comma operators in assignments may appear not to have the normal effect of comma operators because they don't exist within an expression. In the following example, a is set to the value of b = 3 (which is 3), but the c = 4 expression still evaluates and its result returned to console (i.e., 4). This is due to operator precedence and associativity.

+ +
var a, b, c;
+
+a = b = 3, c = 4; // Returns 4 in console
+console.log(a); // 3 (left-most)
+
+var x, y, z;
+
+x = (y = 5, z = 6); // Returns 6 in console
+console.log(x); // 6 (right-most)
+
+ +

Processing and then returning

+ +

Another example that one could make with comma operator is processing before returning. As stated, only the last element will be returned but all others are going to be evaluated as well. So, one could do:

+ +
function myFunc() {
+  var x = 0;
+
+  return (x += 1, x); // the same as return ++x;
+}
+ +

Especificações

+ + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-comma-operator', 'Comma operator')}}
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.operators.comma")}}

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/operators/function/index.html b/files/pt-pt/web/javascript/reference/operators/function/index.html new file mode 100644 index 0000000000..450183b727 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/operators/function/index.html @@ -0,0 +1,139 @@ +--- +title: Expressão função (Function expression) +slug: Web/JavaScript/Reference/Operadores/função +tags: + - Expressões Primárias + - Funiconaldiade de Linguagem + - Função + - JavaScript + - Operador +translation_of: Web/JavaScript/Reference/Operators/function +--- +
{{jsSidebar("Operators")}}
+ +

A palavra-chave function  pode ser utilziada para definir uma função dentro de uma expressão.

+ +

You can also define functions using the Function constructor and a function declaration.

+ +
{{EmbedInteractiveExample("pages/js/expressions-functionexpression.html", "shorter")}}
+ + + +

Sintaxe

+ +
let myFunction = function [name]([param1[, param2[, ..., paramN]]]) {
+   statements
+};
+ +

As of ES2015, you can also use {{jsxref("Functions/Arrow_functions", "arrow functions")}}.

+ +

Parâmetros

+ +
+
name {{optional_inline}}
+
The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function body.
+
paramN {{optional_inline}}
+
The name of an argument to be passed to the function.
+
statements {{optional_inline}}
+
The statements which comprise the body of the function.
+
+ +

Descrição

+ +

A function expression is very similar to and has almost the same syntax as a function declaration (see {{jsxref("Statements/function", "function statement")}} for details). The main difference between a function expression and a function declaration is the function name, which can be omitted in function expressions to create anonymous functions. A function expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined. See also the chapter about {{jsxref("Functions", "functions")}} for more information.

+ +

Function expression hoisting

+ +

Function expressions in JavaScript are not hoisted, unlike {{jsxref("Statements/function", "function declarations", "#Function_declaration_hoisting")}}. You can't use function expressions before you define them:

+ +
console.log(notHoisted) // undefined
+//  even though the variable name is hoisted, the definition isn't. so it's undefined.
+notHoisted(); // TypeError: notHoisted is not a function
+
+var notHoisted = function() {
+   console.log('bar');
+};
+
+ +

Named function expression

+ +

If you want to refer to the current function inside the function body, you need to create a named function expression. This name is then local only to the function body (scope). This also avoids using the non-standard {{jsxref("Functions/arguments/callee", "arguments.callee")}} property.

+ +
let math = {
+  'factit': function factorial(n) {
+    console.log(n)
+    if (n <= 1) {
+      return 1;
+    }
+    return n * factorial(n - 1);
+  }
+};
+
+math.factit(3) //3;2;1;
+
+ +

The variable the function expression is assigned to will have a name property. The name doesn't change if it's assigned to a different variable. If function name is omitted, it will be the variable name (implicit name). If function name is present, it will be the function name (explicit name). This also applies to {{jsxref("Functions/Arrow_functions", "arrow functions")}} (arrows don't have a name so you can only give the variable an implicit name).

+ +
var foo = function() {}
+foo.name // "foo"
+
+var foo2 = foo
+foo2.name // "foo"
+
+var bar = function baz() {}
+bar.name // "baz"
+
+console.log(foo === foo2); // true
+console.log(typeof baz); // undefined
+console.log(bar === baz); // false (errors because baz == undefined)
+
+ +

Exemplos

+ +

The following example defines an unnamed function and assigns it to x. The function returns the square of its argument:

+ +
var x = function(y) {
+   return y * y;
+};
+
+ +

More commonly it is used as a callback:

+ +
button.addEventListener('click', function(event) {
+    console.log('button is clicked!')
+})
+ +

Especificações

+ + + + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.operators.function")}}

+ +

Consulte também 

+ + diff --git a/files/pt-pt/web/javascript/reference/operators/index.html b/files/pt-pt/web/javascript/reference/operators/index.html new file mode 100644 index 0000000000..02a550b7b0 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/operators/index.html @@ -0,0 +1,309 @@ +--- +title: Expressões e operadores +slug: Web/JavaScript/Reference/Operadores +tags: + - JavaScript + - Operadores + - Página Landing + - Resumo + - Sinopse +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

Este capítulo documenta todos os operadores, expressões e palavras-chave da linguagem JavaScript.

+ +

Expressões e operadores por categoria

+ +

For an alphabetical listing see the sidebar on the left.

+ +

Expressões primárias

+ +

Basic keywords and general expressions in JavaScript.

+ +
+
{{JSxRef("Operators/this", "this")}}
+
The this keyword refers to a special property of an execution context.
+
{{JSxRef("Operators/function", "function")}}
+
The function keyword defines a function expression.
+
{{JSxRef("Operators/class", "class")}}
+
The class keyword defines a class expression.
+
{{JSxRef("Operators/function*", "function*")}}
+
The function* keyword defines a generator function expression.
+
{{JSxRef("Operators/yield", "yield")}}
+
Pause and resume a generator function.
+
{{JSxRef("Operators/yield*", "yield*")}}
+
Delegate to another generator function or iterable object.
+
{{JSxRef("Operators/async_function", "async function")}}
+
The async function defines an async function expression.
+
{{JSxRef("Operators/await", "await")}}
+
Pause and resume an async function and wait for the promise's resolution/rejection.
+
{{JSxRef("Global_Objects/Array", "[]")}}
+
Array initializer/literal syntax.
+
{{JSxRef("Operators/Object_initializer", "{}")}}
+
Object initializer/literal syntax.
+
{{JSxRef("Global_Objects/RegExp", "/ab+c/i")}}
+
Regular expression literal syntax.
+
{{JSxRef("Operators/Grouping", "( )")}}
+
Grouping operator.
+
+ +

Expressões "Left-hand-side"

+ +

Left values are the destination of an assignment.

+ +
+
{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
+
Member operators provide access to a property or method of an object
+ (object.property and object["property"]).
+
{{jsxref("Operators/new", "new")}}
+
The new operator creates an instance of a constructor.
+
new.target
+
In constructors, new.target refers to the constructor that was invoked by {{jsxref("Operators/new", "new")}}.
+
{{jsxref("Operators/super", "super")}}
+
The super keyword calls the parent constructor.
+
{{jsxref("Operators/Spread_operator", "...obj")}}
+
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
+
+ +

Aumento e diminuição

+ +

Postfix/prefix increment and postfix/prefix decrement operators.

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}
+
Postfix increment operator.
+
{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}
+
Postfix decrement operator.
+
{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}
+
Prefix increment operator.
+
{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}
+
Prefix decrement operator.
+
+ +

Operadores unários

+ +

A unary operation is operation with only one operand.

+ +
+
{{jsxref("Operators/delete", "delete")}}
+
The delete operator deletes a property from an object.
+
{{jsxref("Operators/void", "void")}}
+
The void operator discards an expression's return value.
+
{{jsxref("Operators/typeof", "typeof")}}
+
The typeof operator determines the type of a given object.
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}
+
The unary plus operator converts its operand to Number type.
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}
+
The unary negation operator converts its operand to Number type and then negates it.
+
{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}
+
Bitwise NOT operator.
+
{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}
+
Logical NOT operator.
+
+ +

Operadores de aritmética

+ +

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}
+
Addition operator.
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}
+
Subtraction operator.
+
{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}
+
Division operator.
+
{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}
+
Multiplication operator.
+
{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}
+
Remainder operator.
+
+ +
+
{{JSxRef("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}
+
Exponentiation operator.
+
+ +

Operadores relacionais

+ +

A comparison operator compares its operands and returns a Boolean value based on whether the comparison is true.

+ +
+
{{jsxref("Operators/in", "in")}}
+
The in operator determines whether an object has a given property.
+
{{jsxref("Operators/instanceof", "instanceof")}}
+
The instanceof operator determines whether an object is an instance of another object.
+
{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}
+
Less than operator.
+
{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}
+
Greater than operator.
+
{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}
+
Less than or equal operator.
+
{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}
+
Greater than or equal operator.
+
+ +
+

Nota: => não é um operador, mas a notação para funções seta (arrow).

+
+ +

Operadores de equality

+ +

The result of evaluating an equality operator is always of type Boolean based on whether the comparison is true.

+ +
+
{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}
+
Equality operator.
+
{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}
+
Inequality operator.
+
{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}
+
Identity operator.
+
{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}
+
Nonidentity operator.
+
+ +

Bitwise shift operators

+ +

Operations to shift all bits of the operand.

+ +
+
{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}
+
Bitwise left shift operator.
+
{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}
+
Bitwise right shift operator.
+
{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}
+
Bitwise unsigned right shift operator.
+
+ +

Operadores de binário bitwise

+ +

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

+ +
+
{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}
+
Bitwise AND.
+
{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}
+
Bitwise OR.
+
{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}
+
Bitwise XOR.
+
+ +

Operadores de binário logical

+ +

Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.

+ +
+
{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}
+
Logical AND.
+
{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}
+
Logical OR.
+
+ +

Operdor condicional (ternário)

+ +
+
{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}
+
+

The conditional operator returns one of two values based on the logical value of the condition.

+
+
+ +

Operadores de Assignment

+ +

An assignment operator assigns a value to its left operand based on the value of its right operand.

+ +
+
{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}
+
Assignment operator.
+
{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}
+
Multiplication assignment.
+
{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}
+
Division assignment.
+
{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}
+
Remainder assignment.
+
{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}
+
Addition assignment.
+
{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}
+
Subtraction assignment
+
{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}
+
Left shift assignment.
+
{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}
+
Right shift assignment.
+
{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}
+
Unsigned right shift assignment.
+
{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}
+
Bitwise AND assignment.
+
{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}
+
Bitwise XOR assignment.
+
{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}
+
Bitwise OR assignment.
+
{{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
+ {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}
+
+

Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.

+
+
+ +

Operador de aspas

+ +
+
{{jsxref("Operators/Comma_Operator", ",")}}
+
The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.
+
+ +

Funcionalidades não padrão

+ +
+
{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}
+
The function keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function body should contains at least one {{jsxref("Operators/yield", "yield")}} expression.
+
{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}
+
The expression closure syntax is a shorthand for writing simple function.
+
{{non-standard_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}
+
Array comprehensions.
+
{{non-standard_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}
+
Generator comprehensions.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES1', '#sec-11', 'Expressions')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES5.1', '#sec-11', 'Expressions')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ES6')}}New: Spread operator, destructuring assignment, super keyword.
{{SpecName('ESDraft', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ESDraft')}}
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.operators")}}

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/operators/operator_precedence/index.html b/files/pt-pt/web/javascript/reference/operators/operator_precedence/index.html new file mode 100644 index 0000000000..03d4345410 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/operators/operator_precedence/index.html @@ -0,0 +1,461 @@ +--- +title: Precedência de operador +slug: Web/JavaScript/Reference/Operadores/Precedencia_operador +tags: + - Guía + - JavaScript + - precedência +translation_of: Web/JavaScript/Reference/Operators/Operator_Precedence +--- +
{{jsSidebar("Operators")}}
+ +

A precedência de operador determina a maneira pela qual os operadores são analisados ​​em relação a cada um. Os operadores com maior precedência tornam-se operandos dos operadores com menor precedência..

+ +
{{EmbedInteractiveExample("pages/js/expressions-operatorprecedence.html")}}
+ + + +

Precedência e Associabilidade

+ +

Consider an expression describable by the representation below. Note that both OP1 and OPare fill-in-the-blanks for OPerators.

+ +
a OP b OP c
+
+ +

If OP1 and OP2 have different precedence levels (see the table below), the operator with the highest precedence goes first and associativity does not matter. Observe how multiplication has higher associativity than addition and executed first, even though addition is written first in the code.

+ +
console.log(3 + 10 * 2);   // logs 23
+console.log(3 + (10 * 2)); // logs 23 because parentheses here are superfluous
+console.log((3 + 10) * 2); // logs 26 because the parentheses change the order 
+ +

Left-associativity (left-to-right) means that it is processed as (a OP1 b) OP2 c, while right-associativity (right-to-left) means it is interpreted as a OP1 (b OP2 c). Assignment operators are right-associative, so you can write:

+ +
a = b = 5; // same as writing a = (b = 5);
+
+ +

with the expected result that a and b get the value 5. This is because the assignment operator returns the value that is assigned. First, b is set to 5. Then the a is also set to 5, the return value of b = 5, aka right operand of the assignment.

+ +

As another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity. It is interesting to note that, the order of evaluation is always left-to-right irregardless of associativity.

+ + + + + + + + + + + + + + + + +
CódigoResultado
+
+function echo(name, num) {
+    console.log("Evaluating the " + name + " side");
+    return num;
+}
+// Notice the division operator (/)
+console.log(echo("left", 6) / echo("right", 2));
+
+
+
+Evaluating the left side
+Evaluating the right side
+3
+
+
+
+function echo(name, num) {
+    console.log("Evaluating the " + name + " side");
+    return num;
+}
+// Notice the exponentiation operator (**)
+console.log(echo("left", 2) ** echo("right", 3));
+
+
+Evaluating the left side
+Evaluating the right side
+8
+
+ +

The difference in associativity comes into play when there are multiple operators of the same precedence. With only one operator or operators of different precedences, associativity does affect the output, as seen in the example above. In the example below, observe how associativity affects the output when multiple of the same operator are used.

+ + + + + + + + + + + + + + + + + + + + +
CódigoResultado
+
+function echo(name, num) {
+    console.log("Evaluating the " + name + " side");
+    return num;
+}
+// Notice the division operator (/)
+console.log(echo("left", 6) / echo("middle", 2) / echo("right", 3));
+
+
+
+Evaluating the left side
+Evaluating the middle side
+Evaluating the right side
+1
+
+
+
+function echo(name, num) {
+    console.log("Evaluating the " + name + " side");
+    return num;
+}
+// Notice the exponentiation operator (**)
+console.log(echo("left", 2) ** echo("middle", 3) ** echo("right", 2));
+
+
+
+Evaluating the left side
+Evaluating the middle side
+Evaluating the right side
+512
+
+
+
+function echo(name, num) {
+    console.log("Evaluating the " + name + " side");
+    return num;
+}
+// Notice the parentheses around the left and middle exponentiation
+console.log((echo("left", 2) ** echo("middle", 3)) ** echo("right", 2));
+
+
+Evaluating the left side
+Evaluating the middle side
+Evaluating the right side
+64
+
+ +

Looking at the code snippets above, 6 / 3 / 2 is the same as (6 / 3) / 2 because division is left-associative. Exponentiation, on the other hand, is right-associative, so 2 ** 3 ** 2 is the same as 2 ** (3 ** 2). Thus, doing (2 ** 3) ** 2 changes the order and results in the 64 seen in the table above.

+ +

Remember that precedence comes before associativity. So, mixing division and exponentiation, the exponentiation comes before the division. For example, 2 ** 3 / 3 ** 2 results in 0.8888888888888888 because it is the same as (2 ** 3) / (3 ** 2).

+ +

Note on Grouping and Short-Circuiting

+ +

In the table below, Grouping is listed as having the highest precedence. However, that does not always mean the expression within the grouping symbols ( … ) is evaluated first, especially when it comes to short-circuiting.

+ +

Short-circuiting is jargon for conditional evaluation. For example, in the expression a && (b + c), if a is “falsy”, then the sub-expression (b + c) will not even get evaluated, even if it is in parentheses. We could say that the logical disjunction operator (“OR”) is “short-circuited”. Along with logical disjunction, other short-circuited operators include logical conjunction (“AND”), nullish-coalescing, optional chaining, and the conditional operator. Some more examples follow.

+ +
a || (b * c);  // evaluate `a` first, then produce `a` if `a` is “truthy”
+a && (b < c);  // evaluate `a` first, then produce `a` if `a` is “falsy”
+a ?? (b || c); // evaluate `a` first, then produce `a` if `a` is not `null` and not `undefined`
+a?.b.c;        // evaluate `a` first, then produce `a` if `a` is `null` or `undefined`
+
+ +

Exemplos

+ +
3 > 2 && 2 > 1
+// returns true
+
+3 > 2 > 1
+// Returns false because 3 > 2 is true, then true is converted to 1 in inequality operators, therefore true > 1 becomes 1 > 1, which
+//  is false. Adding parentheses makes things clear: (3 > 2) > 1.
+
+
+ +

Tabela

+ +

The following table is ordered from highest (20) to lowest (1) precedence.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PrecedênciaTipo de operador (Operator)AssociatividadeOperadores individuais
20{{jsxref("Operators/Grouping", "Grouping")}}n/a( … )
19{{jsxref("Operators/Property_Accessors", "Member Access", "#Dot_notation")}}left-to-right… . …
{{jsxref("Operators/Property_Accessors", "Computed Member Access","#Bracket_notation")}}left-to-right… [ … ]
{{jsxref("Operators/new","new")}} (with argument list)n/anew … ( … )
Function Callleft-to-right… ( … )
18{{jsxref("Operators/new","new")}} (without argument list)right-to-leftnew …
17{{jsxref("Operators/Arithmetic_Operators","Postfix Increment","#Increment")}}n/a… ++
{{jsxref("Operators/Arithmetic_Operators","Postfix Decrement","#Decrement")}}… --
16Logical NOTright-to-left! …
Bitwise NOT~ …
Unary Plus+ …
Unary Negation- …
Prefix Increment++ …
Prefix Decrement-- …
typeoftypeof …
voidvoid …
deletedelete …
awaitawait …
15Exponentiationright-to-left… ** …
14Multiplicationleft-to-right… * …
Division… / …
Remainder… % …
13Additionleft-to-right… + …
Subtraction… - …
12Bitwise Left Shiftleft-to-right… << …
Bitwise Right Shift… >> …
Bitwise Unsigned Right Shift… >>> …
11Less Thanleft-to-right… < …
Less Than Or Equal… <= …
Greater Than… > …
Greater Than Or Equal… >= …
in… in …
instanceof… instanceof …
10Equalityleft-to-right… == …
Inequality… != …
Strict Equality… === …
Strict Inequality… !== …
9Bitwise ANDleft-to-right… & …
8Bitwise XORleft-to-right… ^ …
7Bitwise ORleft-to-right… | …
6Logical ANDleft-to-right… && …
5Logical ORleft-to-right… || …
4Conditionalright-to-left… ? … : …
3Assignmentright-to-left… = …
… += …
… -= …
… **= …
… *= …
… /= …
… %= …
… <<= …
… >>= …
… >>>= …
… &= …
… ^= …
… |= …
2{{jsxref("Operators/yield", "yield")}}right-to-leftyield …
{{jsxref("Operators/yield*", "yield*")}}yield* …
1Vírgula / Sequêncialeft-to-right… , …
diff --git a/files/pt-pt/web/javascript/reference/sobre/index.html b/files/pt-pt/web/javascript/reference/sobre/index.html deleted file mode 100644 index 3b2a79ac32..0000000000 --- a/files/pt-pt/web/javascript/reference/sobre/index.html +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: Sobre a referência de JavaScript -slug: Web/JavaScript/Reference/Sobre -tags: - - JavaScript -translation_of: Web/JavaScript/Reference/About ---- -
{{JsSidebar}}
- -

The JavaScript reference serves as a repository of facts about the JavaScript language. The entire language is described here in detail. As you write JavaScript code, you'll refer to these pages often (thus the title "JavaScript reference"). If you're learning JavaScript, or need help understanding some of its capabilities or features, check out the JavaScript guide.

- -

The JavaScript language is intended to be used within some larger environment, be it a browser, server-side scripts, or similar. For the most part, this reference attempts to be environment-agnostic and does not target a web browser environment.

- -

Onde encontrar informação sobre JavaScript

- -

JavaScript documentation of core language features (pure ECMAScript, for the most part) includes the following:

- - - -

If you are new to JavaScript, start with the guide. Once you have a firm grasp of the fundamentals, you can use the reference to get more details on individual objects and language constructs.

- -

Estrutura da referência

- -

In the JavaScript reference you can find the following chapters:

- -
-
Standard built-in objects
-
This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.
-
Statements and declarations
-
JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.
-
Expressions and operators
-
This chapter documents all the JavaScript language operators, expressions and keywords.
-
Functions
-
Chapter about JavaScript functions.
-
Classes
-
Chapter about JavaScript classes introduced in ECMAScript 6.
-
Errors
-
Chapter about specific errors, exceptions and warnings thrown by JavaScript.
-
New in JavaScript
-
Chapter about JavaScript version history.
-
- -

Mais páginas de referência

- - diff --git a/files/pt-pt/web/javascript/reference/statements/block/index.html b/files/pt-pt/web/javascript/reference/statements/block/index.html new file mode 100644 index 0000000000..a3104dbeae --- /dev/null +++ b/files/pt-pt/web/javascript/reference/statements/block/index.html @@ -0,0 +1,116 @@ +--- +title: Bloco (block) +slug: Web/JavaScript/Reference/Extratos_e_declarações/bloco +tags: + - Declaração + - Funcionalidade de Linguagem + - JavaScript + - Referencia +translation_of: Web/JavaScript/Reference/Statements/block +--- +
Bloco {{jsSidebar("Statements")}}
+ +

Uma declaralção bloco (ou declaração composto em outras linguagens) é utilizada para agrupar zero ou mais declarações. O bloco é delimitado por um par de chavetas (“chavetas { }”) e opcionalmente poderá ser {{jsxref("Statements/label", "labelled", "", 1)}}:

+ +
{{EmbedInteractiveExample("pages/js/statement-block.html", "taller")}}
+ + + +

Sintaxe

+ +

Declaração de Bloco

+ +
{
+  StatementList
+}
+
+ +

Declaração de Bloco Etiquetado

+ +
LabelIdentifier: {
+  StatementList
+}
+
+ +
+
StatementList
+
Statements grouped within the block statement.
+
LabelIdentifier
+
An optional {{jsxref("Statements/label", "label", "", 1)}} for visual identification or as a target for {{jsxref("Statements/break", "break")}}.
+
+ +

Descrição

+ +

The block statement is often called compound statement in other languages. It allows you to use multiple statements where JavaScript expects only one statement. Combining statements into blocks is a common practice in JavaScript. The opposite behavior is possible using an empty statement, where you provide no statement, although one is required.

+ +

Blocks are commonly used in association with {{jsxref("Statements/if...else", "if...else")}} and {{jsxref("Statements/for", "for")}} statements.

+ +

Block Scoping Rules

+ +

With var or function declaration in non-strict mode

+ +

Variables declared with var or created by function declarations in non-strict mode do not have block scope. Variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. For example:

+ +
var x = 1;
+{
+  var x = 2;
+}
+console.log(x); // logs 2
+
+ +

This logs 2 because the var x statement within the block is in the same scope as the var x statement before the block.

+ +

In non-strict code, function declarations inside blocks behave strangely. Do not use them.

+ +

With let, const or function declaration in strict mode

+ +

By contrast, identifiers declared with {{jsxref("Statements/let", "let")}} and {{jsxref("Statements/const", "const")}} do have block scope:

+ +
let x = 1;
+{
+  let x = 2;
+}
+console.log(x); // logs 1
+ +

The x = 2 is limited in scope to the block in which it was defined.

+ +

The same is true of const:

+ +
const c = 1;
+{
+  const c = 2;
+}
+console.log(c); // logs 1 and does not throw SyntaxError...
+ +

Note that the block-scoped const c = 2 does not throw a SyntaxError: Identifier 'c' has already been declared because it can be declared uniquely within the block.

+ +

In strict mode, starting with ES2015, functions inside blocks are scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

+ +

Especificações

+ + + + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-block', 'Block statement')}}
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.statements.block")}}

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/statements/for/index.html b/files/pt-pt/web/javascript/reference/statements/for/index.html new file mode 100644 index 0000000000..ac7586e98b --- /dev/null +++ b/files/pt-pt/web/javascript/reference/statements/for/index.html @@ -0,0 +1,145 @@ +--- +title: for +slug: Web/JavaScript/Reference/Extratos_e_declarações/for +tags: + - Declaração + - Funcionalidade de Linguagem + - JavaScript + - Loop + - Referencia + - Repetição + - for +translation_of: Web/JavaScript/Reference/Statements/for +--- +
{{jsSidebar("Statements")}}
+ +

A declaração "for" cria uma repetição (loop) que consiste de três expressões opcionais, entre parênteses e separados por ponto e vírgula, seguido de uma declaração (normalmente bdeclaraçãod e bloco (block)) para ser executada na repetição.

+ +
{{EmbedInteractiveExample("pages/js/statement-for.html")}}
+ + + +

Sintaxe

+ +
for ([initialization]; [condition]; [final-expression])
+   statement
+ +
+
initialization
+
An expression (including assignment expressions) or variable declaration evaluated once before the loop begins. Typically used to initialize a counter variable. This expression may optionally declare new variables with var or let keywords. Variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in. Variables declared with let are local to the statement.
+
The result of this expression is discarded.
+
condition
+
An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following the for construct.
+
final-expression
+
An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable.
+
statement
+
A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a {{jsxref("Statements/block", "block", "", 0)}} statement ({ ... }) to group those statements. To execute no statement within the loop, use an {{jsxref("Statements/empty", "empty", "", 0)}} statement (;).
+
+ +

Exemplos

+ +

Using for

+ +

The following for statement starts by declaring the variable i and initializing it to 0. It checks that i is less than nine, performs the two succeeding statements, and increments i by 1 after each pass through the loop.

+ +
for (let i = 0; i < 9; i++) {
+   console.log(i);
+   // more statements
+}
+
+ +

Optional for expressions

+ +

All three expressions in the head of the for loop are optional.

+ +

For example, in the initialization block it is not required to initialize variables:

+ +
var i = 0;
+for (; i < 9; i++) {
+    console.log(i);
+    // more statements
+}
+
+ +

Like the initialization block, the condition block is also optional. If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop.

+ +
for (let i = 0;; i++) {
+   console.log(i);
+   if (i > 3) break;
+   // more statements
+}
+ +

You can also omit all three blocks. Again, make sure to use a {{jsxref("Statements/break", "break")}} statement to end the loop and also modify (increase) a variable, so that the condition for the break statement is true at some point.

+ +
var i = 0;
+
+for (;;) {
+  if (i > 3) break;
+  console.log(i);
+  i++;
+}
+
+ +

Using for without a statement

+ +

The following for cycle calculates the offset position of a node in the final-expression section, and therefore it does not require the use of a statement section, a semicolon is used instead.

+ +
function showOffsetPos(sId) {
+
+  var nLeft = 0, nTop = 0;
+
+  for (
+
+    var oItNode = document.getElementById(sId); /* initialization */
+
+    oItNode; /* condition */
+
+    nLeft += oItNode.offsetLeft, nTop += oItNode.offsetTop, oItNode = oItNode.offsetParent /* final-expression */
+
+  ); /* semicolon */
+
+  console.log('Offset position of \'' + sId + '\' element:\n left: ' + nLeft + 'px;\n top: ' + nTop + 'px;');
+
+}
+
+/* Example call: */
+
+showOffsetPos('content');
+
+// Output:
+// "Offset position of "content" element:
+// left: 0px;
+// top: 153px;"
+ +
Note: This is one of the few cases in JavaScript where the semicolon is mandatory. Indeed, without the semicolon the line that follows the cycle declaration will be considered a statement.
+ +

Especificações

+ + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-for-statement', 'for statement')}}
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.statements.for")}}

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/statements/index.html b/files/pt-pt/web/javascript/reference/statements/index.html new file mode 100644 index 0000000000..af841906a1 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/statements/index.html @@ -0,0 +1,150 @@ +--- +title: Declarações e instruções +slug: Web/JavaScript/Reference/Extratos_e_declarações +tags: + - JavaScript + - Referencia + - declarações + - instruções +translation_of: Web/JavaScript/Reference/Statements +--- +
{{jsSidebar("Statements")}}
+ +

JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.

+ +

Declarações e instruções por categoria

+ +

For an alphabetical listing see the sidebar on the left.

+ +

Controlo de Fluxo

+ +
+
{{jsxref("Statements/block", "Block")}}
+
A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets.
+
{{jsxref("Statements/break", "break")}}
+
Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
+
{{jsxref("Statements/continue", "continue")}}
+
Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
+
{{jsxref("Statements/Empty", "Empty")}}
+
An empty statement is used to provide no statement, although the JavaScript syntax would expect one.
+
{{jsxref("Statements/if...else", "if...else")}}
+
Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.
+
{{jsxref("Statements/switch", "switch")}}
+
Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.
+
{{jsxref("Statements/throw", "throw")}}
+
Throws a user-defined exception.
+
{{jsxref("Statements/try...catch", "try...catch")}}
+
Marks a block of statements to try, and specifies a response, should an exception be thrown.
+
+ +

Declarações

+ +
+
{{jsxref("Statements/var", "var")}}
+
Declares a variable, optionally initializing it to a value.
+
{{jsxref("Statements/let", "let")}}
+
Declares a block scope local variable, optionally initializing it to a value.
+
{{jsxref("Statements/const", "const")}}
+
Declares a read-only named constant.
+
+ +

Funções e classes

+ +
+
{{jsxref("Statements/function", "function")}}
+
Declara as funções com parâmetros especificados.
+
{{jsxref("Statements/function*", "function*")}}
+
Generators functions enable writing iterators more easily.
+
{{jsxref("Statements/async_function", "async function")}}
+
Declares an async function with the specified parameters.
+
{{jsxref("Statements/return", "return")}}
+
Specifies the value to be returned by a function.
+
{{jsxref("Statements/class", "class")}}
+
Declara uma Classe.
+
+ +

Iterações

+ +
+
{{jsxref("Statements/do...while", "do...while")}}
+
Creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
+
{{jsxref("Statements/for", "for")}}
+
Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
+
{{deprecated_inline}} {{non-standard_inline()}} {{jsxref("Statements/for_each...in", "for each...in")}}
+
Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.
+
{{jsxref("Statements/for...in", "for...in")}}
+
Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
+
{{jsxref("Statements/for...of", "for...of")}}
+
Iterates over iterable objects (including {{jsxref("Global_Objects/Array","arrays","","true")}}, array-like objects, iterators and generators), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
+
{{jsxref("Statements/while", "while")}}
+
Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.
+
+ +

Outros

+ +
+
{{jsxref("Statements/debugger", "debugger")}}
+
Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.
+
{{jsxref("Statements/export", "export")}}
+
Used to export functions to make them available for imports in external modules, another scripts.
+
{{jsxref("Statements/import", "import")}}
+
Used to import functions exported from an external module, another script.
+
import.meta
+
A meta-property exposing context-specific metadata to a JavaScript module.
+
{{jsxref("Statements/label", "label")}}
+
Provides a statement with an identifier that you can refer to using a break or continue statement.
+
+ +
+
{{deprecated_inline}} {{jsxref("Statements/with", "with")}}
+
Extends the scope chain for a statement.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES1', '#sec-12', 'Statements')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES3', '#sec-12', 'Statements')}}{{Spec2('ES3')}} 
{{SpecName('ES5.1', '#sec-12', 'Statements')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ES6')}}New: function*, let, for...of, yield, class
{{SpecName('ESDraft', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.statements")}}

+ +

Consultar também

+ + diff --git a/files/pt-pt/web/javascript/reference/statements/return/index.html b/files/pt-pt/web/javascript/reference/statements/return/index.html new file mode 100644 index 0000000000..6cec134992 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/statements/return/index.html @@ -0,0 +1,148 @@ +--- +title: return +slug: Web/JavaScript/Reference/Extratos_e_declarações/return +tags: + - Declaração + - JavaScript +translation_of: Web/JavaScript/Reference/Statements/return +--- +
{{jsSidebar("Statements")}}
+ +

The return statement ends function execution and specifies a value to be returned to the function caller.

+ +

Sintaxe

+ +
return [[expression]]; 
+ +
+
expression
+
The expression whose value is to be returned. If omitted, undefined is returned instead.
+
+ +

Descrição

+ +

When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, x, where x is a number.

+ +
function square(x) {
+   return x * x;
+}
+var demo = square(3);
+// demo will equal 9
+
+ +

If the value is omitted, undefined is returned instead.

+ +

The following return statements all break the function execution:

+ +
return;
+return true;
+return false;
+return x;
+return x + y / 3;
+
+ +

Inserção Automática de Ponto e Vírgula

+ +

The return statement is affected by automatic semicolon insertion (ASI). No line terminator is allowed between the return keyword and the expression.

+ +
return
+a + b;
+
+ +

is transformed by ASI into:

+ +
return;
+a + b;
+
+ +

The console will warn "unreachable code after return statement".

+ +
Starting with Gecko 40 {{geckoRelease(40)}}, a warning is shown in the console if unreachable code is found after a return statement.
+ +

Exemplos

+ +

Interromper uma função

+ +

A function immediately stops at the point where return is called.

+ +
function counter() {
+  for (var count = 1; ; count++) {  // infinite loop
+    console.log(count + 'A'); // until 5
+      if (count === 5) {
+        return;
+      }
+      console.log(count + 'B');  // until 4
+    }
+  console.log(count + 'C');  // never appears
+}
+
+counter();
+
+// Output:
+// 1A
+// 1B
+// 2A
+// 2B
+// 3A
+// 3B
+// 4A
+// 4B
+// 5A
+
+ +

Devolver uma função

+ +

See also the article about Closures.

+ +
function magic(x) {
+  return function calc(x) { return x * 42; };
+}
+
+var answer = magic();
+answer(1337); // 56154
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-12.9', 'Return statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-return-statement', 'Return statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-return-statement', 'Return statement')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.statements.return")}}

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/statements/throw/index.html b/files/pt-pt/web/javascript/reference/statements/throw/index.html new file mode 100644 index 0000000000..9e7a8bf54e --- /dev/null +++ b/files/pt-pt/web/javascript/reference/statements/throw/index.html @@ -0,0 +1,271 @@ +--- +title: throw +slug: Web/JavaScript/Reference/Extratos_e_declarações/throw +tags: + - Comando + - Declaração + - JavaScript +translation_of: Web/JavaScript/Reference/Statements/throw +--- +
{{jsSidebar("Statements")}}
+ +

A declaração throw lança uma exeção definida pelo utilizador. A execução da função atual irá parar (os comandos depois de throw não serão executados), e o controle será passado para o primeiro bloco catch no conjunto de chamadas. Se não existir nenhum bloco catch entre as funções de caller, o programa irá terminar.

+ +

Sintaxe

+ +
expressão throw; 
+ +
+
expressão
+
A expressão para throw.
+
+ +

Descrição

+ +

Use the throw statement to throw an exception. When you throw an exception, expression specifies the value of the exception. Each of the following throws an exception:

+ +
throw 'Error2'; // generates an exception with a string value
+throw 42;       // generates an exception with the value 42
+throw true;     // generates an exception with the value true
+ +

Also note that the throw statement is affected by automatic semicolon insertion (ASI) as no line terminator between the throw keyword and the expression is allowed.

+ +

Exemplos

+ +

Throw um objeto

+ +

You can specify an object when you throw an exception. You can then reference the object's properties in the catch block. The following example creates an object of type UserException and uses it in a throw statement.

+ +
function UserException(message) {
+   this.message = message;
+   this.name = 'UserException';
+}
+function getMonthName(mo) {
+   mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec)
+   var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
+      'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+   if (months[mo] !== undefined) {
+      return months[mo];
+   } else {
+      throw new UserException('InvalidMonthNo');
+   }
+}
+
+try {
+   // statements to try
+   var myMonth = 15; // 15 is out of bound to raise the exception
+   var monthName = getMonthName(myMonth);
+} catch (e) {
+   monthName = 'unknown';
+   console.log(e.message, e.name); // pass exception object to err handler
+}
+
+ +

Outro exemplo de throwing um objeto

+ +

The following example tests an input string for a U.S. zip code. If the zip code uses an invalid format, the throw statement throws an exception by creating an object of type ZipCodeFormatException.

+ +
/*
+ * Creates a ZipCode object.
+ *
+ * Accepted formats for a zip code are:
+ *    12345
+ *    12345-6789
+ *    123456789
+ *    12345 6789
+ *
+ * If the argument passed to the ZipCode constructor does not
+ * conform to one of these patterns, an exception is thrown.
+ */
+
+function ZipCode(zip) {
+   zip = new String(zip);
+   pattern = /[0-9]{5}([- ]?[0-9]{4})?/;
+   if (pattern.test(zip)) {
+      // zip code value will be the first match in the string
+      this.value = zip.match(pattern)[0];
+      this.valueOf = function() {
+         return this.value
+      };
+      this.toString = function() {
+         return String(this.value)
+      };
+   } else {
+      throw new ZipCodeFormatException(zip);
+   }
+}
+
+function ZipCodeFormatException(value) {
+   this.value = value;
+   this.message = 'does not conform to the expected format for a zip code';
+   this.toString = function() {
+      return this.value + this.message;
+   };
+}
+
+/*
+ * This could be in a script that validates address data
+ * for US addresses.
+ */
+
+const ZIPCODE_INVALID = -1;
+const ZIPCODE_UNKNOWN_ERROR = -2;
+
+function verifyZipCode(z) {
+   try {
+      z = new ZipCode(z);
+   } catch (e) {
+      if (e instanceof ZipCodeFormatException) {
+         return ZIPCODE_INVALID;
+      } else {
+         return ZIPCODE_UNKNOWN_ERROR;
+      }
+   }
+   return z;
+}
+
+a = verifyZipCode(95060);         // returns 95060
+b = verifyZipCode(9560);          // returns -1
+c = verifyZipCode('a');           // returns -1
+d = verifyZipCode('95060');       // returns 95060
+e = verifyZipCode('95060 1234');  // returns 95060 1234
+
+ +

Rethrow uma exceção

+ +

You can use throw to rethrow an exception after you catch it. The following example catches an exception with a numeric value and rethrows it if the value is over 50. The rethrown exception propagates up to the enclosing function or to the top level so that the user sees it.

+ +
try {
+   throw n; // throws an exception with a numeric value
+} catch (e) {
+   if (e <= 50) {
+      // statements to handle exceptions 1-50
+   } else {
+      // cannot handle this exception, so rethrow
+      throw e;
+   }
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.4
{{SpecName('ES5.1', '#sec-12.13', 'throw statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-throw-statement', 'throw statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-throw-statement', 'throw statement')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.statements.throw")}}

+ +

Consulte também

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