From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../bloco/index.html" | 116 +++++++++ .../for/index.html" | 145 +++++++++++ .../index.html" | 150 ++++++++++++ .../return/index.html" | 148 +++++++++++ .../throw/index.html" | 271 +++++++++++++++++++++ 5 files changed, 830 insertions(+) create mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/bloco/index.html" create mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/for/index.html" create mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/index.html" create mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/return/index.html" create mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/throw/index.html" (limited to 'files/pt-pt/web/javascript/reference/extratos_e_declarações') 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" new file mode 100644 index 0000000000..a3104dbeae --- /dev/null +++ "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/bloco/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/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" new file mode 100644 index 0000000000..ac7586e98b --- /dev/null +++ "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/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/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" new file mode 100644 index 0000000000..af841906a1 --- /dev/null +++ "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/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/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" new file mode 100644 index 0000000000..6cec134992 --- /dev/null +++ "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/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/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" new file mode 100644 index 0000000000..9e7a8bf54e --- /dev/null +++ "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/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