From c55e1533f4a2f755711122f297c9ea88cb588229 Mon Sep 17 00:00:00 2001 From: Dheyson Alves Date: Sat, 31 Aug 2019 10:16:47 -0300 Subject: [PATCH 1/3] Translate local variables and outer variables --- .../14-function-basics/article.md | 50 +++++++++---------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/1-js/02-first-steps/14-function-basics/article.md b/1-js/02-first-steps/14-function-basics/article.md index f13127a16..be6b0e3db 100644 --- a/1-js/02-first-steps/14-function-basics/article.md +++ b/1-js/02-first-steps/14-function-basics/article.md @@ -47,88 +47,88 @@ Se precisarmos mudar a mensagem ou a maneira que ela é mostrada, basta modifica ## Variáveis locais -A variable declared inside a function is only visible inside that function. +Uma variável declarada dentro de uma função é apenas visível dentro dessa função. -For example: +Por exemplo: ```js run function showMessage() { *!* - let message = "Hello, I'm JavaScript!"; // local variable + let message = "Olá, Eu sou JavaScript!"; // variável local */!* alert( message ); } -showMessage(); // Hello, I'm JavaScript! +showMessage(); // Olá, Eu sou JavaScript! -alert( message ); // <-- Error! The variable is local to the function +alert( message ); // <-- Erro! A variável é local para a função ``` -## Outer variables +## Variáveis externas -A function can access an outer variable as well, for example: +Uma função também pode acessar uma variável externa, por exemplo: ```js run no-beautify let *!*userName*/!* = 'John'; function showMessage() { - let message = 'Hello, ' + *!*userName*/!*; + let message = 'Olá, ' + *!*userName*/!*; alert(message); } -showMessage(); // Hello, John +showMessage(); // Olá, John ``` -The function has full access to the outer variable. It can modify it as well. +A função tem acesso total à variável externa. Pode modificá-la também. -For instance: +Por exemplo: ```js run let *!*userName*/!* = 'John'; function showMessage() { - *!*userName*/!* = "Bob"; // (1) changed the outer variable + *!*userName*/!* = "Bob"; // (1) mudou a variável externa - let message = 'Hello, ' + *!*userName*/!*; + let message = 'Olá, ' + *!*userName*/!*; alert(message); } -alert( userName ); // *!*John*/!* before the function call +alert( userName ); // *!*John*/!* antes da chamada da função showMessage(); -alert( userName ); // *!*Bob*/!*, the value was modified by the function +alert( userName ); // *!*Bob*/!*, o valor foi modificado pela função ``` -The outer variable is only used if there's no local one. So an occasional modification may happen if we forget `let`. +A variável externa é apenas usada se não existir uma local. Então, uma modificação ocasional pode acontencer se esquercermos do `let`. -If a same-named variable is declared inside the function then it *shadows* the outer one. For instance, in the code below the function uses the local `userName`. The outer one is ignored: +Se uma variável com o mesmo nome é declarada dentro da função, então ela *shadows* a externa. Por exemplo, no código abaixo, a função usa o `userName` local. O exterior é ignorado: ```js run let userName = 'John'; function showMessage() { *!* - let userName = "Bob"; // declare a local variable + let userName = "Bob"; // declara uma variável local */!* - let message = 'Hello, ' + userName; // *!*Bob*/!* + let message = 'Olá, ' + userName; // *!*Bob*/!* alert(message); } -// the function will create and use its own userName +// a função criará e usará seu próprio userName showMessage(); -alert( userName ); // *!*John*/!*, unchanged, the function did not access the outer variable +alert( userName ); // *!*John*/!*, inalterado, a função não acessou a variável externa ``` -```smart header="Global variables" -Variables declared outside of any function, such as the outer `userName` in the code above, are called *global*. +```smart header="Variáveis globais" +Variáveis declaradas fora de qualquer função, como o `userName` externo no código acima, são chamados de *globais*. -Global variables are visible from any function (unless shadowed by locals). +Variáveis globais são visíveis por qualquer função (a não ser que sejam sombreadas pelas locais). -Usually, a function declares all variables specific to its task. Global variables only store project-level data, and it's important that these variables are accessible from anywhere. Modern code has few or no globals. Most variables reside in their functions. +Normalmente, uma função declara todas as variáveis específicas de sua tarefa. As variáveis globais armazenam apenas dados em nível de projeto e é importante que essas variáveis sejam acessíveis de qualquer lugar. Código moderno tem poucos ou nenhum globais. A maioria das variáveis reside em suas funções. ``` ## Parameters From 1ce7d7ce8100efd98c609815c97f5efbd66814ce Mon Sep 17 00:00:00 2001 From: Jonnathan Santos Date: Sun, 2 Apr 2023 16:11:22 -0300 Subject: [PATCH 2/3] refactor: fix suggested notes in code review --- 1-js/02-first-steps/15-function-basics/article.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/1-js/02-first-steps/15-function-basics/article.md b/1-js/02-first-steps/15-function-basics/article.md index 6b1dd5c97..038c014a9 100644 --- a/1-js/02-first-steps/15-function-basics/article.md +++ b/1-js/02-first-steps/15-function-basics/article.md @@ -104,10 +104,9 @@ showMessage(); alert( userName ); // *!*Bob*/!*, o valor foi modificado pela função ``` +A variável externa só é usada se não houver uma local. -The outer variable is only used if there's no local one. - -Se uma variável com o mesmo nome é declarada dentro da função, então ela *shadows* a externa. Por exemplo, no código abaixo, a função usa o `userName` local. O exterior é ignorado: +Se uma variável com o mesmo nome é declarada dentro da função, então ela *encobre (shadows)* a externa. Por exemplo, no código abaixo, a função usa o `userName` local. O exterior é ignorado: ```js run let userName = 'John'; @@ -121,7 +120,7 @@ function showMessage() { alert(message); } -// a função criará e usará seu próprio userName +// a função criará e usará o seu próprio userName showMessage(); alert( userName ); // *!*John*/!*, inalterado, a função não acessou a variável externa @@ -132,7 +131,7 @@ Variáveis declaradas fora de qualquer função, como o `userName` externo no c Variáveis globais são visíveis por qualquer função (a não ser que sejam sombreadas pelas locais). -It's a good practice to minimize the use of global variables. Modern code has few or no globals. Most variables reside in their functions. Sometimes though, they can be useful to store project-level data. +É uma boa prática minimizar o uso de variáveis ​​globais. Um código moderno tem poucas ou nenhuma variável global. A maioria das variáveis ​​residem em suas funções. Às vezes, porém, elas podem ser úteis para armazenar dados em nível de projeto. ``` ## Parameters From 506915ac1ba01750e64bdaae7f83d59d45c263e8 Mon Sep 17 00:00:00 2001 From: Jonnathan Santos Date: Sun, 2 Apr 2023 17:20:11 -0300 Subject: [PATCH 3/3] feat: finalizes the translation of the article after updating with the master branch --- .../1-if-else-required/solution.md | 4 +- .../1-if-else-required/task.md | 14 +- .../solution.md | 10 +- .../2-rewrite-function-question-or/task.md | 16 +- .../15-function-basics/4-pow/task.md | 6 +- .../15-function-basics/article.md | 246 +++++++++--------- 6 files changed, 148 insertions(+), 148 deletions(-) diff --git a/1-js/02-first-steps/15-function-basics/1-if-else-required/solution.md b/1-js/02-first-steps/15-function-basics/1-if-else-required/solution.md index e3a0df77c..b7c045d0b 100644 --- a/1-js/02-first-steps/15-function-basics/1-if-else-required/solution.md +++ b/1-js/02-first-steps/15-function-basics/1-if-else-required/solution.md @@ -1,3 +1,3 @@ -No difference! +Nenhuma diferença! -In both cases, `return confirm('Did parents allow you?')` executes exactly when the `if` condition is falsy. \ No newline at end of file +Em ambos os casos, `return confirm('Seus pais permitiram?')` é executado exatamente quando a condição `if` é falsa. \ No newline at end of file diff --git a/1-js/02-first-steps/15-function-basics/1-if-else-required/task.md b/1-js/02-first-steps/15-function-basics/1-if-else-required/task.md index 4f69a5c8c..914f622ae 100644 --- a/1-js/02-first-steps/15-function-basics/1-if-else-required/task.md +++ b/1-js/02-first-steps/15-function-basics/1-if-else-required/task.md @@ -2,11 +2,11 @@ importance: 4 --- -# Is "else" required? +# "else" é obrigatório? -The following function returns `true` if the parameter `age` is greater than `18`. +A função a seguir retorna `true` se o parâmetro `age` for maior que `18`. -Otherwise it asks for a confirmation and returns its result: +Caso contrário, ele pede uma confirmação e retorna seu resultado: ```js function checkAge(age) { @@ -15,13 +15,13 @@ function checkAge(age) { *!* } else { // ... - return confirm('Did parents allow you?'); + return confirm('Seus pais permitiram?'); } */!* } ``` -Will the function work differently if `else` is removed? +A função funcionará de forma diferente se `else` for removido? ```js function checkAge(age) { @@ -30,9 +30,9 @@ function checkAge(age) { } *!* // ... - return confirm('Did parents allow you?'); + return confirm('Seus pais permitiram?'); */!* } ``` -Is there any difference in the behavior of these two variants? +Existe alguma diferença no comportamento dessas duas variantes? diff --git a/1-js/02-first-steps/15-function-basics/2-rewrite-function-question-or/solution.md b/1-js/02-first-steps/15-function-basics/2-rewrite-function-question-or/solution.md index e48502642..a927e2b54 100644 --- a/1-js/02-first-steps/15-function-basics/2-rewrite-function-question-or/solution.md +++ b/1-js/02-first-steps/15-function-basics/2-rewrite-function-question-or/solution.md @@ -1,17 +1,17 @@ -Using a question mark operator `'?'`: +Usando o operador de ponto de interrogação `'?'`: ```js function checkAge(age) { - return (age > 18) ? true : confirm('Did parents allow you?'); + return (age > 18) ? true : confirm('Seus pais permitiram?'); } ``` -Using OR `||` (the shortest variant): +Usando OR `||` (a variante mais curta): ```js function checkAge(age) { - return (age > 18) || confirm('Did parents allow you?'); + return (age > 18) || confirm('Seus pais permitiram?'); } ``` -Note that the parentheses around `age > 18` are not required here. They exist for better readability. +Observe que os parênteses em torno de `age > 18` não são necessários aqui. Eles existem para melhor legibilidade. diff --git a/1-js/02-first-steps/15-function-basics/2-rewrite-function-question-or/task.md b/1-js/02-first-steps/15-function-basics/2-rewrite-function-question-or/task.md index 46da079c0..b7feb805a 100644 --- a/1-js/02-first-steps/15-function-basics/2-rewrite-function-question-or/task.md +++ b/1-js/02-first-steps/15-function-basics/2-rewrite-function-question-or/task.md @@ -2,25 +2,25 @@ importance: 4 --- -# Rewrite the function using '?' or '||' +# Reescreva a função usando '?' ou '||' -The following function returns `true` if the parameter `age` is greater than `18`. +A função a seguir retorna `true` se o parâmetro `age` for maior que `18`. -Otherwise it asks for a confirmation and returns its result. +Caso contrário, ele pede uma confirmação e retorna seu resultado. ```js function checkAge(age) { if (age > 18) { return true; } else { - return confirm('Did parents allow you?'); + return confirm('Seus pais permitiram?'); } } ``` -Rewrite it, to perform the same, but without `if`, in a single line. +Reescreva-o, para executar o mesmo, mas sem `if`, em uma única linha. -Make two variants of `checkAge`: +Faça duas variantes de `checkAge`: -1. Using a question mark operator `?` -2. Using OR `||` +1. Usando o operador de ponto de interrogação `?` +2. Usando OR `||` diff --git a/1-js/02-first-steps/15-function-basics/4-pow/task.md b/1-js/02-first-steps/15-function-basics/4-pow/task.md index f569320c7..bc3bb1bb0 100644 --- a/1-js/02-first-steps/15-function-basics/4-pow/task.md +++ b/1-js/02-first-steps/15-function-basics/4-pow/task.md @@ -4,7 +4,7 @@ importance: 4 # Function pow(x,n) -Write a function `pow(x,n)` that returns `x` in power `n`. Or, in other words, multiplies `x` by itself `n` times and returns the result. +Escreva uma função `pow(x,n)` que retorna `x` na potência `n`. Ou, em outras palavras, multiplica `x` por ele mesmo `n` vezes e retorna o resultado. ```js pow(3, 2) = 3 * 3 = 9 @@ -12,8 +12,8 @@ pow(3, 3) = 3 * 3 * 3 = 27 pow(1, 100) = 1 * 1 * ...* 1 = 1 ``` -Create a web-page that prompts for `x` and `n`, and then shows the result of `pow(x,n)`. +Crie uma página da Web que solicite `x` e `n` e mostre o resultado de `pow(x,n)`. [demo] -P.S. In this task the function should support only natural values of `n`: integers up from `1`. +PS Nesta tarefa, a função deve suportar apenas valores naturais de `n`: inteiros acima de `1`. diff --git a/1-js/02-first-steps/15-function-basics/article.md b/1-js/02-first-steps/15-function-basics/article.md index 038c014a9..461d4978a 100644 --- a/1-js/02-first-steps/15-function-basics/article.md +++ b/1-js/02-first-steps/15-function-basics/article.md @@ -4,13 +4,13 @@ Muitas vezes nós precisamos realizar uma ação semelhante em muitos lugares do Por exemplo, precisamos mostrar uma boa mensagem quando um usuário efetua login, efetua logout e talvez em outro lugar. -Funções são os principais "building blocks" do programa. Elas permitem que o código sejam chamados muitas vezes sem repetição. +Funções são os principais "building blocks" do programa. Elas permitem que o código seja chamado muitas vezes sem repetição. -Nós já vimos exemplos de built-in functions, como `alert(message)`, `prompt(message, default)` e `confirm(question)`. Mas nós podemos criar funções próprias também. +Nós já vimos exemplos de "built-in functions", como `alert(message)`, `prompt(message, default)` e `confirm(question)`. Mas nós podemos criar funções próprias também. -## Function Declaration +## Declaração de função -Para criarmos uma função podemos usar uma *function declaration*. +Para criarmos uma função podemos usar uma *Declaração de função*. Se parece assim: @@ -134,30 +134,30 @@ Variáveis globais são visíveis por qualquer função (a não ser que sejam so É uma boa prática minimizar o uso de variáveis ​​globais. Um código moderno tem poucas ou nenhuma variável global. A maioria das variáveis ​​residem em suas funções. Às vezes, porém, elas podem ser úteis para armazenar dados em nível de projeto. ``` -## Parameters +## Parâmetros -We can pass arbitrary data to functions using parameters. +Podemos passar dados arbitrários para funções usando parâmetros. -In the example below, the function has two parameters: `from` and `text`. +No exemplo abaixo, a função possui dois parâmetros: `from` e `text`. ```js run -function showMessage(*!*from, text*/!*) { // parameters: from, text +function showMessage(*!*from, text*/!*) { // parâmetros: from, text alert(from + ': ' + text); } -*!*showMessage('Ann', 'Hello!');*/!* // Ann: Hello! (*) -*!*showMessage('Ann', "What's up?");*/!* // Ann: What's up? (**) +*!*showMessage('Ann', 'Olá!');*/!* // Ann: Olá! (*) +*!*showMessage('Ann', "E aí?");*/!* // Ann: E aí? (**) ``` -When the function is called in lines `(*)` and `(**)`, the given values are copied to local variables `from` and `text`. Then the function uses them. +Quando a função é chamada nas linhas `(*)` e `(**)`, os valores fornecidos são copiados para as variáveis ​​locais `from` e `text`. Em seguida, a função os usa. -Here's one more example: we have a variable `from` and pass it to the function. Please note: the function changes `from`, but the change is not seen outside, because a function always gets a copy of the value: +Aqui está mais um exemplo: temos uma variável `from` e passamos para a função. Observe: a função muda para a variável `from` do escopo, mas a mudança não é vista fora, porque uma função sempre obtém uma cópia do valor: ```js run function showMessage(from, text) { *!* - from = '*' + from + '*'; // make "from" look nicer + from = '*' + from + '*'; // faz "from" parecer mais bonito */!* alert( from + ': ' + text ); @@ -165,115 +165,115 @@ function showMessage(from, text) { let from = "Ann"; -showMessage(from, "Hello"); // *Ann*: Hello +showMessage(from, "Olá"); // *Ann*: Olá -// the value of "from" is the same, the function modified a local copy +// o valor de "from" é o mesmo, a função modificou uma cópia local alert( from ); // Ann ``` -When a value is passed as a function parameter, it's also called an *argument*. +Quando um valor é passado como um parâmetro de função, ele também é chamado de *argumento*. -In other words, to put these terms straight: +Em outras palavras, para colocar esses termos em ordem: -- A parameter is the variable listed inside the parentheses in the function declaration (it's a declaration time term) -- An argument is the value that is passed to the function when it is called (it's a call time term). +- Um parâmetro é a variável listada entre parênteses na declaração da função (é um termo de tempo de declaração) +- Um argumento é o valor passado para a função quando ela é chamada (é um termo de tempo de chamada). -We declare functions listing their parameters, then call them passing arguments. +Declaramos funções listando seus parâmetros e as chamamos de passagem de argumentos. -In the example above, one might say: "the function `showMessage` is declared with two parameters, then called with two arguments: `from` and `"Hello"`". +No exemplo acima, pode-se dizer: "a função `showMessage` é declarada com dois parâmetros, e então é chamada com dois argumentos: `from` e `"Hello"`". -## Default values +## Valores padrão -If a function is called, but an argument is not provided, then the corresponding value becomes `undefined`. +Se uma função for chamada, mas um argumento não for fornecido, o valor correspondente será `undefined`. -For instance, the aforementioned function `showMessage(from, text)` can be called with a single argument: +Por exemplo, a função acima mencionada `showMessage(from, text)` pode ser chamada com um único argumento: ```js showMessage("Ann"); ``` -That's not an error. Such a call would output `"*Ann*: undefined"`. As the value for `text` isn't passed, it becomes `undefined`. +Isso não é um erro. Tal chamada resultaria em `"*Ann*: undefined"`. Como o valor de `text` não é passado, ele se torna `undefined`. -We can specify the so-called "default" (to use if omitted) value for a parameter in the function declaration, using `=`: +Podemos especificar o chamado valor "padrão" (para usar se omitido) para um parâmetro na declaração da função, usando `=`: ```js run -function showMessage(from, *!*text = "no text given"*/!*) { +function showMessage(from, *!*text = "nenhum texto fornecido"*/!*) { alert( from + ": " + text ); } -showMessage("Ann"); // Ann: no text given +showMessage("Ann"); // Ann: nenhum texto fornecido ``` -Now if the `text` parameter is not passed, it will get the value `"no text given"` +Agora se o parâmetro `text` não for passado, ele receberá o valor `"nenhum texto fornecido"` -Here `"no text given"` is a string, but it can be a more complex expression, which is only evaluated and assigned if the parameter is missing. So, this is also possible: +Aqui `"nenhum texto fornecido"` é uma string, mas pode ser uma expressão mais complexa, que só é avaliada e atribuída se o parâmetro estiver ausente. Então, isso também é possível: ```js run function showMessage(from, text = anotherFunction()) { - // anotherFunction() only executed if no text given - // its result becomes the value of text + // otherFunction() só é executado se nenhum texto for fornecido + // e seu resultado torna-se o valor de text } ``` -```smart header="Evaluation of default parameters" -In JavaScript, a default parameter is evaluated every time the function is called without the respective parameter. +```smart header="Avaliação dos parâmetros padrão" +Em JavaScript, um parâmetro padrão é avaliado toda vez que a função é chamada sem o respectivo parâmetro. -In the example above, `anotherFunction()` isn't called at all, if the `text` parameter is provided. +No exemplo acima, `anotherFunction()` não é chamado se o parâmetro `text` for fornecido. -On the other hand, it's independently called every time when `text` is missing. +Por outro lado, é chamado independentemente toda vez que `text` está faltando. ``` -### Alternative default parameters +### Parâmetros padrão alternativos -Sometimes it makes sense to assign default values for parameters not in the function declaration, but at a later stage. +Às vezes, faz sentido atribuir valores padrão para parâmetros não na declaração da função, mas em um estágio posterior. -We can check if the parameter is passed during the function execution, by comparing it with `undefined`: +Podemos verificar se o parâmetro é passado durante a execução da função, comparando-o com `undefined`: ```js run function showMessage(text) { // ... *!* - if (text === undefined) { // if the parameter is missing - text = 'empty message'; + if (text === undefined) { // se o parâmetro estiver faltando + text = 'mensagem vazia'; } */!* alert(text); } -showMessage(); // empty message +showMessage(); // mensagem vazia ``` -...Or we could use the `||` operator: +...Ou poderíamos usar o operador OR `||`: ```js function showMessage(text) { - // if text is undefined or otherwise falsy, set it to 'empty' - text = text || 'empty'; + // se o texto for indefinido ou falso, defina-o como 'vazio' + text = text || 'vazio'; ... } ``` -Modern JavaScript engines support the [nullish coalescing operator](info:nullish-coalescing-operator) `??`, it's better when most falsy values, such as `0`, should be considered "normal": +Mecanismos JavaScript modernos suportam o [operador de coalescência nula](info:nullish-coalescing-operator) `??`, é melhor quando a maioria dos valores falsos, como `0`, devem ser considerados "normais": ```js run function showCount(count) { - // if count is undefined or null, show "unknown" - alert(count ?? "unknown"); + // se a contagem for indefinida ou nula, mostre "desconhecido" + alert(count ?? "desconhecido"); } showCount(0); // 0 -showCount(null); // unknown -showCount(); // unknown +showCount(null); // desconhecido +showCount(); // desconhecido ``` -## Returning a value +## Retornando um valor -A function can return a value back into the calling code as the result. +Uma função pode retornar um valor de volta ao código de chamada como resultado. -The simplest example would be a function that sums two values: +O exemplo mais simples seria uma função que soma dois valores: ```js run no-beautify function sum(a, b) { @@ -284,9 +284,9 @@ let result = sum(1, 2); alert( result ); // 3 ``` -The directive `return` can be in any place of the function. When the execution reaches it, the function stops, and the value is returned to the calling code (assigned to `result` above). +A diretiva `return` pode estar em qualquer lugar da função. Quando a execução o atinge, a função para e o valor é retornado ao código de chamada (atribuído a `result` acima). -There may be many occurrences of `return` in a single function. For instance: +Pode haver muitas ocorrências de `return` em uma única função. Por exemplo: ```js run function checkAge(age) { @@ -296,23 +296,23 @@ function checkAge(age) { */!* } else { *!* - return confirm('Do you have permission from your parents?'); + return confirm('Você tem permissão de seus pais?'); */!* } } -let age = prompt('How old are you?', 18); +let age = prompt('Quantos anos você tem?', 18); if ( checkAge(age) ) { - alert( 'Access granted' ); + alert( 'Acesso concedido' ); } else { - alert( 'Access denied' ); + alert( 'Acesso negado' ); } ``` -It is possible to use `return` without a value. That causes the function to exit immediately. +É possível usar `return` sem um valor. Isso faz com que a função saia imediatamente. -For example: +Por exemplo: ```js function showMovie(age) { @@ -322,23 +322,23 @@ function showMovie(age) { */!* } - alert( "Showing you the movie" ); // (*) + alert( "Mostrando o filme" ); // (*) // ... } ``` -In the code above, if `checkAge(age)` returns `false`, then `showMovie` won't proceed to the `alert`. +No código acima, se `checkAge(age)` retornar `false`, então `showMovie` não prosseguirá para o `alert`. -````smart header="A function with an empty `return` or without it returns `undefined`" -If a function does not return a value, it is the same as if it returns `undefined`: +````smart header="Uma função com um `return` vazio ou sem ele retorna `undefined`" +Se uma função não retornar um valor, é o mesmo que retornar `undefined`: ```js run -function doNothing() { /* empty */ } +function doNothing() { /* vazio */ } alert( doNothing() === undefined ); // true ``` -An empty `return` is also the same as `return undefined`: +Um `return` vazio também é o mesmo que `return undefined`: ```js run function doNothing() { @@ -349,23 +349,23 @@ alert( doNothing() === undefined ); // true ``` ```` -````warn header="Never add a newline between `return` and the value" -For a long expression in `return`, it might be tempting to put it on a separate line, like this: +````warn header="Nunca adicione uma nova linha entre `return` e o valor" +Para uma expressão longa em `return`, pode ser tentador colocá-la em uma linha separada, assim: ```js return (some + long + expression + or + whatever * f(a) + f(b)) ``` -That doesn't work, because JavaScript assumes a semicolon after `return`. That'll work the same as: +Isso não funciona, porque o JavaScript assume um ponto e vírgula após `return`. Isso funcionará da mesma forma que: ```js return*!*;*/!* (some + long + expression + or + whatever * f(a) + f(b)) ``` -So, it effectively becomes an empty return. +Assim, torna-se efetivamente um retorno vazio. -If we want the returned expression to wrap across multiple lines, we should start it at the same line as `return`. Or at least put the opening parentheses there as follows: +Se quisermos que a expressão retornada seja agrupada em várias linhas, devemos iniciá-la na mesma linha que `return`. Ou pelo menos coloque os parênteses de abertura da seguinte forma: ```js return ( @@ -374,67 +374,67 @@ return ( whatever * f(a) + f(b) ) ``` -And it will work just as we expect it to. +E funcionará exatamente como esperamos. ```` -## Naming a function [#function-naming] +## Nomeando uma função [#function-naming] -Functions are actions. So their name is usually a verb. It should be brief, as accurate as possible and describe what the function does, so that someone reading the code gets an indication of what the function does. +Funções são ações. Portanto, seu nome geralmente é um verbo. Deve ser breve, o mais preciso possível e descrever o que a função faz, para que alguém que leia o código tenha uma indicação do que a função faz. -It is a widespread practice to start a function with a verbal prefix which vaguely describes the action. There must be an agreement within the team on the meaning of the prefixes. +É uma prática comum iniciar uma função com um prefixo verbal que descreva vagamente a ação. Deve haver um acordo em sua equipe sobre o significado dos prefixos. -For instance, functions that start with `"show"` usually show something. +Por exemplo, funções que começam com `"show"` geralmente mostram algo. -Function starting with... +Função que começa com... -- `"get…"` -- return a value, -- `"calc…"` -- calculate something, -- `"create…"` -- create something, -- `"check…"` -- check something and return a boolean, etc. +- `"get…"` -- retorna um valor, +- `"calc…"` -- calcula algo, +- `"create"` -- cria algo, +- `"check…"` -- verifica algo e retorna um valor booleano, etc. -Examples of such names: +Exemplos de tais nomes: ```js no-beautify -showMessage(..) // shows a message -getAge(..) // returns the age (gets it somehow) -calcSum(..) // calculates a sum and returns the result -createForm(..) // creates a form (and usually returns it) -checkPermission(..) // checks a permission, returns true/false +showMessage(..) // mostra uma mensagem +getAge(..) // retorna a idade (obtido de alguma forma) +calcSum(..) // calcula uma soma e retorna o resultado +createForm(..) // cria um formulário (e geralmente o retorna) +checkPermission(..) // verifica uma permissão, retorna true/false ``` -With prefixes in place, a glance at a function name gives an understanding what kind of work it does and what kind of value it returns. +Com os prefixos no lugar, uma olhada no nome de uma função fornece uma compreensão do trabalho que ela faz e qual o valor que ela retorna. -```smart header="One function -- one action" -A function should do exactly what is suggested by its name, no more. +```smart header="Uma função -- uma ação" +Uma função deve fazer exatamente o que é sugerido pelo seu nome, nada mais. -Two independent actions usually deserve two functions, even if they are usually called together (in that case we can make a 3rd function that calls those two). +Duas ações independentes geralmente merecem duas funções, mesmo que sejam normalmente chamadas juntas (nesse caso, podemos fazer uma terceira função que chama essas duas). -A few examples of breaking this rule: +Alguns exemplos de quebra dessa regra: -- `getAge` -- would be bad if it shows an `alert` with the age (should only get). -- `createForm` -- would be bad if it modifies the document, adding a form to it (should only create it and return). -- `checkPermission` -- would be bad if it displays the `access granted/denied` message (should only perform the check and return the result). +- `getAge` -- seria ruim se mostrasse um `alert` com a idade (deveria apenas obter). +- `createForm` -- seria ruim se modificasse o documento, adicionando um formulário a ele (deveria apenas criá-lo e retornar). +- `checkPermission` -- seria ruim se exibisse a mensagem `acesso concedido/negado` (deveria apenas executar a verificação e retornar o resultado). -These examples assume common meanings of prefixes. You and your team are free to agree on other meanings, but usually they're not much different. In any case, you should have a firm understanding of what a prefix means, what a prefixed function can and cannot do. All same-prefixed functions should obey the rules. And the team should share the knowledge. +Esses exemplos assumem significados comuns de prefixos. Você e sua equipe são livres para concordar com outros significados, mas geralmente não são muito diferentes. Em qualquer caso, você deve ter um entendimento firme do que significa um prefixo, o que uma função prefixada pode e não pode fazer. Todas as funções com o mesmo prefixo devem obedecer às regras. E a equipe deve compartilhar o conhecimento. ``` -```smart header="Ultrashort function names" -Functions that are used *very often* sometimes have ultrashort names. +```smart header="Nomes de função ultracurtos" +As funções que são usadas *com muita frequência* às vezes têm nomes ultracurtos. -For example, the [jQuery](http://jquery.com) framework defines a function with `$`. The [Lodash](http://lodash.com/) library has its core function named `_`. +Por exemplo, o framework [jQuery](http://jquery.com) define uma função com `$`. A biblioteca [Lodash](http://lodash.com/) tem sua função central chamada `_`. -These are exceptions. Generally function names should be concise and descriptive. +Estas são exceções. Geralmente, os nomes das funções devem ser concisos e descritivos. ``` -## Functions == Comments +## Funções == Comentários -Functions should be short and do exactly one thing. If that thing is big, maybe it's worth it to split the function into a few smaller functions. Sometimes following this rule may not be that easy, but it's definitely a good thing. +As funções devem ser curtas e fazer exatamente uma coisa. Se essa coisa for grande, talvez valha a pena dividir a função em algumas funções menores. Às vezes, seguir essa regra pode não ser tão fácil, mas é definitivamente uma coisa boa. -A separate function is not only easier to test and debug -- its very existence is a great comment! +Uma função separada não é apenas mais fácil de testar e depurar -- sua própria existência é um ótimo comentário! -For instance, compare the two functions `showPrimes(n)` below. Each one outputs [prime numbers](https://en.wikipedia.org/wiki/Prime_number) up to `n`. +Por exemplo, compare às duas funções `showPrimes(n)` abaixo. Cada uma produz [números primos](https://en.wikipedia.org/wiki/Prime_number) até `n`. -The first variant uses a label: +A primeira variante usa um rótulo: ```js function showPrimes(n) { @@ -444,12 +444,12 @@ function showPrimes(n) { if (i % j == 0) continue nextPrime; } - alert( i ); // a prime + alert( i ); // um primo } } ``` -The second variant uses an additional function `isPrime(n)` to test for primality: +A segunda variante usa uma função adicional `isPrime(n)` para testar a primalidade: ```js function showPrimes(n) { @@ -457,7 +457,7 @@ function showPrimes(n) { for (let i = 2; i < n; i++) { *!*if (!isPrime(i)) continue;*/!* - alert(i); // a prime + alert(i); // um primo } } @@ -469,13 +469,13 @@ function isPrime(n) { } ``` -The second variant is easier to understand, isn't it? Instead of the code piece we see a name of the action (`isPrime`). Sometimes people refer to such code as *self-describing*. +A segunda variante é mais fácil de entender, não é? Em vez do trecho de código, vemos o nome da ação (`isPrime`). Às vezes, as pessoas se referem a esse código como *autodescritivo*. -So, functions can be created even if we don't intend to reuse them. They structure the code and make it readable. +Assim, funções podem ser criadas mesmo que não pretendamos reutilizá-las. Eles estruturam o código e o tornam legível. -## Summary +## Resumo -A function declaration looks like this: +Uma declaração de função se parece com isso: ```js function name(parameters, delimited, by, comma) { @@ -483,18 +483,18 @@ function name(parameters, delimited, by, comma) { } ``` -- Values passed to a function as parameters are copied to its local variables. -- A function may access outer variables. But it works only from inside out. The code outside of the function doesn't see its local variables. -- A function can return a value. If it doesn't, then its result is `undefined`. +- Os valores passados ​​para uma função como parâmetros são copiados para suas variáveis ​​locais. +- Uma função pode acessar variáveis ​​externas. Mas funciona apenas de dentro para fora. O código fora da função não vê suas variáveis ​​locais. +- Uma função pode retornar um valor. Se não, então seu resultado é `undefined`. -To make the code clean and easy to understand, it's recommended to use mainly local variables and parameters in the function, not outer variables. +Para tornar o código limpo e fácil de entender, é recomendável usar principalmente variáveis ​​e parâmetros locais na função, não variáveis ​​externas. -It is always easier to understand a function which gets parameters, works with them and returns a result than a function which gets no parameters, but modifies outer variables as a side-effect. +É sempre mais fácil entender uma função que obtém parâmetros, trabalha com eles e retorna um resultado do que uma função que não obtém parâmetros, mas modifica variáveis ​​externas como efeito colateral. -Function naming: +Nomenclatura da função: -- A name should clearly describe what the function does. When we see a function call in the code, a good name instantly gives us an understanding what it does and returns. -- A function is an action, so function names are usually verbal. -- There exist many well-known function prefixes like `create…`, `show…`, `get…`, `check…` and so on. Use them to hint what a function does. +- Um nome deve descrever claramente o que a função faz. Quando vemos uma chamada de função no código, um bom nome nos dá instantaneamente uma compreensão do que ela faz e retorna. +- Uma função é uma ação, portanto, os nomes das funções geralmente são verbais. +- Existem muitos prefixos de função bem conhecidos como `create…`, `show…`, `get…`, `check…` e assim por diante. Use-os para sugerir o que uma função faz. -Functions are the main building blocks of scripts. Now we've covered the basics, so we actually can start creating and using them. But that's only the beginning of the path. We are going to return to them many times, going more deeply into their advanced features. +As funções são os principais blocos de construção dos scripts. Agora que cobrimos o básico, podemos começar a criá-los e usá-los. Mas isso é só o começo do caminho. Voltaremos a eles muitas vezes, nos aprofundando em seus recursos avançados.