diff --git a/1-js/02-first-steps/13-switch/article.md b/1-js/02-first-steps/13-switch/article.md index 873699feb..258f24068 100644 --- a/1-js/02-first-steps/13-switch/article.md +++ b/1-js/02-first-steps/13-switch/article.md @@ -1,22 +1,22 @@ -# A instrução "switch" +# The "switch" statement -Uma instrução `switch` pode substituir muitas comparações `se`. +A `switch` statement can replace multiple `if` checks. -Ela é uma forma mais descritiva de comparar um valor com múltiplas variantes. +It gives a more descriptive way to compare a value with multiple variants. -## A sintaxe +## The syntax -O `switch` tem um ou mais blocos `case` (caso) e um `default` (padrão) opcional. +The `switch` has one or more `case` blocks and an optional default. -Tem uma apresentação similar a: +It looks like this: ```js no-beautify switch(x) { - case 'valor1': // if (x === 'valor1') + case 'value1': // if (x === 'value1') ... [break] - case 'valor2': // if (x === 'valor2') + case 'value2': // if (x === 'value2') ... [break] @@ -26,71 +26,71 @@ switch(x) { } ``` -- O valor de `x` é comparado por meio de uma igualdade exata ao valor do primeiro `case` (isto é, ao `valor1`), a seguir ao do segundo (`valor2`) e assim sucessivamente. -- Se uma igualdade é encontrada, o `switch` começa a executar o código a partir do início do `case` correspondente, até ao próximo `break` (ou até ao fim do `switch`). -- Se nenhum `case` é equiparado então o código em `default` é executado (se existir). +- The value of `x` is checked for a strict equality to the value from the first `case` (that is, `value1`) then to the second (`value2`) and so on. +- If the equality is found, `switch` starts to execute the code starting from the corresponding `case`, until the nearest `break` (or until the end of `switch`). +- If no case is matched then the `default` code is executed (if it exists). -## Um exemplo +## An example -Um exemplo de `switch` (o código executado está em destaque): +An example of `switch` (the executed code is highlighted): ```js run let a = 2 + 2; switch (a) { case 3: - alert( 'Muito baixo' ); + alert( 'Too small' ); break; *!* case 4: - alert( 'Exacto!' ); + alert( 'Exactly!' ); break; */!* case 5: - alert( 'Muito alto' ); + alert( 'Too large' ); break; default: - alert( "Não conheço tais valores" ); + alert( "I don't know such values" ); } ``` -Aqui o `switch` começa por comparar `a` à variante no primeiro `case`, que é `3`. A correspondência falha. +Here the `switch` starts to compare `a` from the first `case` variant that is `3`. The match fails. -Então a `4`. Existe uma correspondência, e assim a execução começa a partir do `case 4` até ao próximo `break`. +Then `4`. That's a match, so the execution starts from `case 4` until the nearest `break`. -**Se não existir um `break` então a execução continua pelo próximo `case` sem quaisquer verificações.** +**If there is no `break` then the execution continues with the next `case` without any checks.** -Um exemplo sem `break`: +An example without `break`: ```js run let a = 2 + 2; switch (a) { case 3: - alert( 'Muito baixo' ); + alert( 'Too small' ); *!* case 4: - alert( 'Exacto!' ); + alert( 'Exactly!' ); case 5: - alert( 'Muito alto' ); + alert( 'Too big' ); default: - alert( "Não conheço tais valores" ); + alert( "I don't know such values" ); */!* } ``` -No exemplo acima, vemos uma execução sequential de três `alert`'s: +In the example above we'll see sequential execution of three `alert`s: ```js -alert( 'Exacto!' ); -alert( 'Muito alto' ); -alert( "Não conheço tais valores" ); +alert( 'Exactly!' ); +alert( 'Too big' ); +alert( "I don't know such values" ); ``` -````smart header="Any expression can be a switch/case argument" -Ambos `switch` e `case` permitem expressões arbitrárias. +````smart header="Any expression can be a `switch/case` argument" +Both `switch` and `case` allow arbitrary expressions. -Por exemplo: +For example: ```js run let a = "1"; @@ -99,75 +99,74 @@ let b = 0; switch (+a) { *!* case b + 1: - alert("isto executa, porque +a é 1, e é exatamente igual a b+1"); + alert("this runs, because +a is 1, exactly equals b+1"); break; */!* default: - alert("isto não executa"); + alert("this doesn't run"); } ``` -Aqui `+a` dá `1`, o que é comparado a `b + 1` no `case`, e o código correspondente é executado. +Here `+a` gives `1`, that's compared with `b + 1` in `case`, and the corresponding code is executed. ```` -## Grupos de "case" +## Grouping of "case" -Múltiplas variantes de `case` que partihem o mesmo código podem ser agrupadas. +Several variants of `case` which share the same code can be grouped. -Por exemplo, se quisermos que o mesmo código corra por `case 3` e `case 5`: +For example, if we want the same code to run for `case 3` and `case 5`: ```js run no-beautify let a = 2 + 2; switch (a) { case 4: - alert('Certo!'); + alert('Right!'); break; *!* - case 3: // (*) dois cases agrupados + case 3: // (*) grouped two cases case 5: - alert('Errado!'); - alert("Porque não tem aulas de matemática?"); + alert('Wrong!'); + alert("Why don't you take a math class?"); break; */!* default: - alert('O resultado é stranho. Realmente.'); + alert('The result is strange. Really.'); } ``` -Agora ambos `3` e `5` mostram a mesma mensagem. +Now both `3` and `5` show the same message. -A habilidade para "agrupar" cases é um efeito secundário de como `switch/case` funciona sem `break`. Aqui a execução do `case 3` começa pela linha `(*)` e prossegue pelo `case 5`, por não existir `break`. +The ability to "group" cases is a side-effect of how `switch/case` works without `break`. Here the execution of `case 3` starts from the line `(*)` and goes through `case 5`, because there's no `break`. -## O tipo importa +## Type matters -Vamos emfatizar que a verificação da igualdade é sempre exata. Os valores devem também ser do mesmo tipo para existir correspondência. +Let's emphasize that the equality check is always strict. The values must be of the same type to match. -Por exemplo, consideremos o código: +For example, let's consider the code: ```js run -let arg = prompt("Insira um valor?"); +let arg = prompt("Enter a value?"); switch (arg) { case '0': case '1': - alert( 'Um ou zero' ); + alert( 'One or zero' ); break; case '2': - alert( 'Dois' ); + alert( 'Two' ); break; case 3: - alert( 'Nunca executa!' ); + alert( 'Never executes!' ); break; default: - alert( 'Um valor desconhecido' ); + alert( 'An unknown value' ); } ``` -1. Para `0`, `1`, o primeiro `alert` executa. -2. Para `2` o segundo `alert` corre. -3. Mas para `3`, o resultado do `prompt` á a string `"3"`, que não é estritamente igual `===` ao número `3`. Assim temos código não -executável em `case 3`! A variante `default` será executada. +1. For `0`, `1`, the first `alert` runs. +2. For `2` the second `alert` runs. +3. But for `3`, the result of the `prompt` is a string `"3"`, which is not strictly equal `===` to the number `3`. So we've got a dead code in `case 3`! The `default` variant will execute. diff --git a/1-js/02-first-steps/15-function-expressions-arrows/article.md b/1-js/02-first-steps/15-function-expressions-arrows/article.md index 7e03a028e..b4ea19bac 100644 --- a/1-js/02-first-steps/15-function-expressions-arrows/article.md +++ b/1-js/02-first-steps/15-function-expressions-arrows/article.md @@ -1,71 +1,72 @@ -# Expressões de função e Arrow functions +# Function expressions and arrows -Em JavaScript, uma função não é uma "estrutura mágica da linguagem", mas um tipo especial de valor. +In JavaScript, a function is not a "magical language structure", but a special kind of value. -A sintaxe que usámos antes é chamada de *Declaração de Função* (*Function Declaration*): +The syntax that we used before is called a *Function Declaration*: ```js function sayHi() { - alert( "Olá" ); + alert( "Hello" ); } ``` -Existe outra sintaxe para criar uma função que é chamada de *Expressão de Função* (*Function Expression*). +There is another syntax for creating a function that is called a *Function Expression*. -É similar a: +It looks like this: ```js let sayHi = function() { - alert( "Olá" ); + alert( "Hello" ); }; ``` -Aqui, a função é criada e atribuida explícitamente à variável, como qualquer outro valor. Não importa como a função é definida, é apenas um valor atribuido a uma variável `sayHi`. +Here, the function is created and assigned to the variable explicitly, like any other value. No matter how the function is defined, it's just a value stored in the variable `sayHi`. -O significado destas amostras de código é o mesmo: "crie uma função e a coloque na variável `sayHi`". -Podemos até exibir esse valor usando `alert`: +The meaning of these code samples is the same: "create a function and put it into the variable `sayHi`". + +We can even print out that value using `alert`: ```js run function sayHi() { - alert( "Olá" ); + alert( "Hello" ); } *!* -alert( sayHi ); // mostra o código da função +alert( sayHi ); // shows the function code */!* ``` -Por favor, note que a última linha não executa a função, porque não existem parênteses depois de `sayHi`. Existem linguagens de programação onde qualquer menção ao nome de uma função provoca a sua execução, mas em JavaScript não é assim. +Please note that the last line does not run the function, because there are no parentheses after `sayHi`. There are programming languages where any mention of a function name causes its execution, but JavaScript is not like that. -Em JavaScript, uma função é um valor, então podemos lidar com ela como com um valor. O código acima mostra a sua representação em formato de texto (string), que é o código fonte. +In JavaScript, a function is a value, so we can deal with it as a value. The code above shows its string representation, which is the source code. -Óbviamente que é um valor especial, porque podemos invocá-lo usando `sayHi()`. +It is a special value of course, in the sense that we can call it like `sayHi()`. -Mas ainda assim é um valor. Então, podemos manuseá-lo como com outros tipos de valores. +But it's still a value. So we can work with it like with other kinds of values. -Podemos copiar uma função para outra variável: +We can copy a function to another variable: ```js run no-beautify -function sayHi() { // (1) crie - alert( "Olá" ); +function sayHi() { // (1) create + alert( "Hello" ); } -let func = sayHi; // (2) copie +let func = sayHi; // (2) copy -func(); // Olá // (3) execute a cópia (funciona)! -sayHi(); // Olá // isto também ainda funciona (porque não?) +func(); // Hello // (3) run the copy (it works)! +sayHi(); // Hello // this still works too (why wouldn't it) ``` -Aqui está o que acima acontece, em detalhe: +Here's what happens above in detail: -1. A Declaração de Função `(1)` cria uma função e a coloca na variável chamada `sayHi`. -2. Na linha em `(2)` é copiada para a variável `func`. +1. The Function Declaration `(1)` creates the function and puts it into the variable named `sayHi`. +2. Line `(2)` copies it into the variable `func`. - Por favor, note outra vez: não existem parênteses depois de `sayHi`. Se os houvessem, então `func = sayHi()` escreveria *o resultado da chamada* `sayHi()` em `func`, não a própria *função* `sayHi`. -3. Agora, a função pode ser invocada tanto como `sayHi()` como `func()`. + Please note again: there are no parentheses after `sayHi`. If there were, then `func = sayHi()` would write *the result of the call* `sayHi()` into `func`, not *the function* `sayHi` itself. +3. Now the function can be called as both `sayHi()` and `func()`. -Note que poderíamos também ter uma Expressão de Função para declarar `sayHi`, na primeira linha: +Note that we could also have used a Function Expression to declare `sayHi`, in the first line: ```js let sayHi = function() { ... }; @@ -74,11 +75,11 @@ let func = sayHi; // ... ``` -Tudo funcionaria do mesmo modo. Seria ainda mais óbvio o que se passa, não? +Everything would work the same. Even more obvious what's going on, right? ````smart header="Why is there a semicolon at the end?" -Poderá perguntar-se, porque terá uma Expressão de Função um ponto-e-vírgula `;` no final, mas a Declaração de Função não: +You might wonder, why does Function Expression have a semicolon `;` at the end, but Function Declaration does not: ```js function sayHi() { @@ -90,27 +91,27 @@ let sayHi = function() { }*!*;*/!* ``` -A resposta é simples: -- Não há necessidade para um `;` no fim de blocos de código e estruturas sintáticas que os usem como `if { ... }`, `for { }`, `function f { }` etc. -- Uma Expressão de Função é usada dentro de uma instrução: `let sayHi = ...;`, tal como o é um valor. Não é um bloco de código. O ponto-e-vírgula é recomendado no final de instruções, independentemente do seu valor. Assim, o ponto-e-vírgula aqui não está relacionado à Função de Expressão em si, mas simplesmente termina a instrução. +The answer is simple: +- There's no need for `;` at the end of code blocks and syntax structures that use them like `if { ... }`, `for { }`, `function f { }` etc. +- A Function Expression is used inside the statement: `let sayHi = ...;`, as a value. It's not a code block. The semicolon `;` is recommended at the end of statements, no matter what is the value. So the semicolon here is not related to the Function Expression itself in any way, it just terminates the statement. ```` ## Callback functions -Vejamos mais exemplos de passagem de funções como valores e de uso de expressões de função. +Let's look at more examples of passing functions as values and using function expressions. -Escreveremos uma função `ask(question, yes, no)` com três parametros: +We'll write a function `ask(question, yes, no)` with three parameters: `question` -: Texto da questão +: Text of the question `yes` -: Função a executar se a resposta for "Sim" +: Function to run if the answer is "Yes" `no` -: Função a executar se a resposta for "Não" +: Function to run if the answer is "No" -A função deverá efetuar a `question` e, dependendo da resposta do utilizador, chamar `yes()` ou `no()`: +The function should ask the `question` and, depending on the user's answer, call `yes()` or `no()`: ```js run *!* @@ -121,24 +122,24 @@ function ask(question, yes, no) { */!* function showOk() { - alert( "Você concordou." ); + alert( "You agreed." ); } function showCancel() { - alert( "Você cancelou a execução." ); + alert( "You canceled the execution." ); } -// uso: as funções showOk, showCancel são passadas como argumentos a ask -ask("Você concorda?", showOk, showCancel); +// usage: functions showOk, showCancel are passed as arguments to ask +ask("Do you agree?", showOk, showCancel); ``` -Antes de explorarmos em como poderemos escrevê-lo de uma forma mais curta, convém notar que no navegador [browser] (e em certos casos do lado do servidor [server-side]) tais funções são muito populares. A maior difereça entre uma implementação em tempo-real [real-life] e o exemplo acima, é que funções em tempo-real usam formas mais complexas de interagir com o utilizador do que um simples `confirm`. No navegador, geralmente tal função desenha uma agradável janela contendo a questão a formular. Mas isso é outra história. +Before we explore how we can write it in a much shorter way, let's note that in the browser (and on the server-side in some cases) such functions are quite popular. The major difference between a real-life implementation and the example above is that real-life functions use more complex ways to interact with the user than a simple `confirm`. In the browser, such a function usually draws a nice-looking question window. But that's another story. -**Os argumentos de `ask` são chamados de *funções de retorno de chamada* (callback functions) ou apenas *callbacks*.** +**The arguments of `ask` are called *callback functions* or just *callbacks*.** -A ideia é que nós passamos uma função e esperamos que ela seja "chamada" mais tarde se necessário. No nosso caso, `showOk` se torna na função de retorno de chamada (callback) para a resposta "yes", e `showCancel` para a resposta "no". +The idea is that we pass a function and expect it to be "called back" later if necessary. In our case, `showOk` becomes the callback for the "yes" answer, and `showCancel` for the "no" answer. -Podemos utilizar Expressões de Funções para escrever uma versão mais curta da mesma função: +We can use Function Expressions to write the same function much shorter: ```js run no-beautify function ask(question, yes, no) { @@ -148,228 +149,228 @@ function ask(question, yes, no) { *!* ask( - "Você concorda?", - function() { alert("Você concordou."); }, - function() { alert("Você cancelou a execução."); } + "Do you agree?", + function() { alert("You agreed."); }, + function() { alert("You canceled the execution."); } ); */!* ``` -Aqui, as funções são declaradas justamente dentro da chamada a `ask(...)`. Elas não têm nome, e por isso são chamadas de *anónimas*. Tais funções não podem ser acedidas fora de `ask` (porque não estão atribuidas a variáveis), mas é apenas o que queremos para aqui. -Código semelhante aparece nos nossos programas (scripts) muito naturalmente, está no espírito de JavaScript. +Here, functions are declared right inside the `ask(...)` call. They have no name, and so are called *anonymous*. Such functions are not accessible outside of `ask` (because they are not assigned to variables), but that's just what we want here. + +Such code appears in our scripts very naturally, it's in the spirit of JavaScript. ```smart header="A function is a value representing an \"action\"" -Valores comuns como cadeias-de-caráteres (strings) ou números representam os *dados*. +Regular values like strings or numbers represent the *data*. -Uma função pode ser tida como uma *ação*. +A function can be perceived as an *action*. -Podemos passá-la entre variáveis e executá-la quando pretendermos. +We can pass it between variables and run when we want. ``` -## Expressões de função vs Declarações de função +## Function Expression vs Function Declaration -Vamos formular diferenças chave entre Declarações de Função e Expressões. +Let's formulate the key differences between Function Declarations and Expressions. -Primeiro, a sintaxe: como verificar qual é qual no código. +First, the syntax: how to see what is what in the code. -- *Declaração de Função:* uma função, declarada como uma instrução em separado, no fluxo do código principal. +- *Function Declaration:* a function, declared as a separate statement, in the main code flow. ```js - // Declaração de Função + // Function Declaration function sum(a, b) { return a + b; } ``` -- *Expressão de Função:* uma função, criada dentro de uma expressão ou dentro de outra construção sintática. Aqui, a função é criada no lado direito da "expressão de atribuição" `=`: +- *Function Expression:* a function, created inside an expression or inside another syntax construct. Here, the function is created at the right side of the "assignment expression" `=`: ```js - // Expressão de Função + // Function Expression let sum = function(a, b) { return a + b; }; ``` -A mais subtil diferença é *quando* uma função é criada pelo interpretador de JavaScript [JavaScript engine]. +The more subtle difference is *when* a function is created by the JavaScript engine. -**Uma Expressão de Função é criada quando a execução chega até si, e é utilizável a partir daí.** +**A Function Expression is created when the execution reaches it and is usable from then on.** -Ao passar o fluxo de execução para o lado direito da atribuição `let sum = function…` -- aí é que é, a função é criada e pode ser utilizada (atribuida, chamada, etc.) a partir daí. +Once the execution flow passes to the right side of the assignment `let sum = function…` -- here we go, the function is created and can be used (assigned, called, etc. ) from now on. -Declarações de Função sao diferentes. +Function Declarations are different. -**Uma Declaração de Função é utilizável ao longo de todo o script/bloco de código.** +**A Function Declaration is usable in the whole script/code block.** -Por outras palavras, quando JavaScript se *prepara* para correr o programa (script) ou bloco de código, primeiro procura nele por Declarações de Função e cria as funções. Podemos pensar nisto como um "estágio de inicialização". +In other words, when JavaScript *prepares* to run the script or a code block, it first looks for Function Declarations in it and creates the functions. We can think of it as an "initialization stage". -Após o processamento de todas as Declarações de Função, a execução prossegue. +And after all of the Function Declarations are processed, the execution goes on. -Como resultado, a função declarada como Declaração de Função pode ser chamada antes da sua definição no programa. +As a result, a function declared as a Function Declaration can be called earlier than it is defined. -Por exemplo, isto funciona: +For example, this works: ```js run refresh untrusted *!* -sayHi("John"); // Olá, John +sayHi("John"); // Hello, John */!* function sayHi(name) { - alert( `Olá, ${name}` ); + alert( `Hello, ${name}` ); } ``` -A Declaração de Função `sayHi` é criada quando JavaScript se prepara para iniciar o script e é visível em todo o lugar nele. +The Function Declaration `sayHi` is created when JavaScript is preparing to start the script and is visible everywhere in it. -...Se fosse uma Expressão de Função, então não funcionaria: +...If it was a Function Expression, then it wouldn't work: ```js run refresh untrusted *!* -sayHi("John"); // erro! +sayHi("John"); // error! */!* -let sayHi = function(name) { // (*) nenhuma mágica mais - alert( `Olá, ${name}` ); +let sayHi = function(name) { // (*) no magic any more + alert( `Hello, ${name}` ); }; ``` -As Expressões de Função são criadas quando a execução as alcança. O que aconteceria apenas na linha `(*)`. Tarde demais. +Function Expressions are created when the execution reaches them. That would happen only in the line `(*)`. Too late. -**Quando uma Declaração de Função é feita dentro de um bloco de código, ela é visível em todo o lugar dentro desse bloco. Mas não fora dele.** +**When a Function Declaration is made within a code block, it is visible everywhere inside that block. But not outside of it.** -Por vezes, é prático declarar uma função local apenas necessária num dado bloco. Mas essa possibilidade também pode causar problemas. +Sometimes that's handy to declare a local function only needed in that block alone. But that feature may also cause problems. -Por exemplo, imaginemos que precisamos de declarar uma função `welcome()` que dependa da variável `age` que obtemos durante o tempo de execução (runtime). E que planejamos utilizá-la algures mais tarde. +For instance, let's imagine that we need to declare a function `welcome()` depending on the `age` variable that we get during runtime. And then we plan to use it some time later. -O código abaixo não funciona: +The code below doesn't work: ```js run -let age = prompt("Que idade tem?", 18); +let age = prompt("What is your age?", 18); -// condicionalmente declare uma função +// conditionally declare a function if (age < 18) { function welcome() { - alert("Olá!"); + alert("Hello!"); } } else { function welcome() { - alert("Saudações!"); + alert("Greetings!"); } } -// ...utilize-a mais tarde +// ...use it later *!* -welcome(); // Erro: welcome não está definida +welcome(); // Error: welcome is not defined */!* ``` -Isto porque uma Declaração de Função apenas é visível dentro do bloco de código onde reside. +That's because a Function Declaration is only visible inside the code block in which it resides. -Aqui está outro exemplo: +Here's another example: ```js run -let age = 16; // tenha 16 como um exemplo +let age = 16; // take 16 as an example if (age < 18) { *!* - welcome(); // \ (executa) + welcome(); // \ (runs) */!* // | function welcome() { // | - alert("Olá!"); // | Declaração de Função está disponível - } // | em todo o lugar no bloco onde é feita + alert("Hello!"); // | Function Declaration is available + } // | everywhere in the block where it's declared // | *!* - welcome(); // / (executa) + welcome(); // / (runs) */!* } else { - function welcome() { // para age = 16, esta "welcome" nunca é criada - alert("Saudações!"); + function welcome() { // for age = 16, this "welcome" is never created + alert("Greetings!"); } } -// Aqui estamos fora das chavetas, portanto não é -// possível ver-se uma Declaração de Função feita dentro delas. +// Here we're out of curly braces, +// so we can not see Function Declarations made inside of them. *!* -welcome(); // Erro: welcome não está definida +welcome(); // Error: welcome is not defined */!* ``` -O que poderemos fazer para tonar `welcome` visível fora do `if`? +What can we do to make `welcome` visible outside of `if`? -O correto seria empregar uma Função de Expressão e atribuir `welcome` a uma variável declarada fora do `if` e que tenha uma visibilidade adequada. +The correct approach would be to use a Function Expression and assign `welcome` to the variable that is declared outside of `if` and has the proper visibility. -Agora funciona como pretendido: +Now it works as intended: ```js run -let age = prompt("Que idade tem?", 18); +let age = prompt("What is your age?", 18); let welcome; if (age < 18) { welcome = function() { - alert("Olá!"); + alert("Hello!"); }; } else { welcome = function() { - alert("Saudações!"); + alert("Greetings!"); }; } *!* -welcome(); // bem, agora +welcome(); // ok now */!* ``` -Ou poderíamos simplificar mais ainda utilizando o operador ponto-de-interrogação `?`: +Or we could simplify it even further using a question mark operator `?`: ```js run -let age = prompt("Que idade tem?", 18); +let age = prompt("What is your age?", 18); let welcome = (age < 18) ? - function() { alert("Olá!"); } : - function() { alert("Saudações!"); }; + function() { alert("Hello!"); } : + function() { alert("Greetings!"); }; *!* -welcome(); // bem, agora +welcome(); // ok now */!* ``` ```smart header="When should you choose Function Declaration versus Function Expression?" -Como uma regra do polegar, quando precisarmos de declarar uma função, o primeiro a considerar é uma sintaxe de Declaração de Função, como utilizámos acima. Ela providencia mais liberdade para organizar o código, porque podemos chamar tais funções antes de serem declaradas. - +As a rule of thumb, when we need to declare a function, the first to consider is Function Declaration syntax, the one we used before. It gives more freedom in how to organize our code, because we can call such functions before they are declared. -Também é um pouco mais fácil procurar por `function f(…) {…}` no código do que `let f = function(…) {…}`. Declarações de Função "sobressaem" mais à vista. +It's also a little bit easier to look up `function f(…) {…}` in the code than `let f = function(…) {…}`. Function Declarations are more "eye-catching". -...Mas se por alguma razão uma Declaração de Função não nos for útil, (vimos um exemplo acima), então uma Expressão de Função será a escolha. +...But if a Function Declaration does not suit us for some reason (we've seen an example above), then Function Expression should be used. ``` ## Arrow functions [#arrow-functions] -Existe mais uma sintaxe muito simples e concisa para criar funções, e que frequentemente é melhor do que Expressões de Funções. É chamada de "Arrow functions", porque se assemelha a: +There's one more very simple and concise syntax for creating functions, that's often better than Function Expressions. It's called "arrow functions", because it looks like this: ```js let func = (arg1, arg2, ...argN) => expression ``` -...Isto cria a função `func` com os argumentos `arg1..argN`, evalua a `expression` no lado direito utilizando os mesmos e retorna o seu resultado. +...This creates a function `func` that has arguments `arg1..argN`, evaluates the `expression` on the right side with their use and returns its result. -Por outras palavras, é aproximadamente o mesmo que: +In other words, it's roughly the same as: ```js let func = function(arg1, arg2, ...argN) { @@ -377,14 +378,14 @@ let func = function(arg1, arg2, ...argN) { }; ``` -...Mas muito mais concisa. +...But much more concise. -Vejamos um exemplo: +Let's see an example: ```js run let sum = (a, b) => a + b; -/* A função seta é uma forma mais curta de: +/* The arrow function is a shorter form of: let sum = function(a, b) { return a + b; @@ -395,10 +396,10 @@ alert( sum(1, 2) ); // 3 ``` -Se tivermos apenas um argumento, então os parênteses podem ser omitidos, tornando-a ainda mais curta: +If we have only one argument, then parentheses can be omitted, making that even shorter: ```js run -// o mesmo que +// same as // let double = function(n) { return n * 2 } *!* let double = n => n * 2; @@ -407,45 +408,45 @@ let double = n => n * 2; alert( double(3) ); // 6 ``` -Se não houver argumentos, devem existir parênteses vazios (mas devem estar presentes): +If there are no arguments, parentheses should be empty (but they should be present): ```js run -let sayHi = () => alert("Olá!"); +let sayHi = () => alert("Hello!"); sayHi(); ``` -Arrow functions podem ser empregues da mesma forma que Expressões de Função. +Arrow functions can be used in the same way as Function Expressions. -A exemplo, aqui re-escrito está o código com `welcome()`: +For instance, here's the rewritten example with `welcome()`: ```js run -let age = prompt("Que idade tem?", 18); +let age = prompt("What is your age?", 18); let welcome = (age < 18) ? - () => alert('Olá') : - () => alert("Saudações!"); + () => alert('Hello') : + () => alert("Greetings!"); -welcome(); // bem, agora +welcome(); // ok now ``` -Arrow functions podem parecer não familiares e não muito legíveis a princípio, mas isso rápidamente muda à medida que os olhos habituam-se à estrutura. +Arrow functions may appear unfamiliar and not very readable at first, but that quickly changes as the eyes get used to the structure. -Elas são muito convenientes para simples ações numa única-linha, quando estamos preguiçosos demais para escrever muitas palavras. +They are very convenient for simple one-line actions, when we're just too lazy to write many words. ```smart header="Multiline arrow functions" -Os exemplos acima tomaram argumentos à esqerda de `=>` e evaluaram a expressão à direita com eles. +The examples above took arguments from the left of `=>` and evaluated the right-side expression with them. -Por vezes, precisamos de algo um pouco mais complexo, como múltiplas expressões e instruções. Também é possível, mas deveríamos envolvê-las em chavetas. Aí, usamos um `return` normal com elas. +Sometimes we need something a little bit more complex, like multiple expressions or statements. It is also possible, but we should enclose them in curly braces. Then use a normal `return` within them. -Desta forma: +Like this: ```js run -let sum = (a, b) => { // a chaveta abre uma função multi-linha +let sum = (a, b) => { // the curly brace opens a multiline function let result = a + b; *!* - return result; // ao utilizarmos chavetas, usamos `return` para obter o resultado + return result; // if we use curly braces, use return to get results */!* }; @@ -453,25 +454,25 @@ alert( sum(1, 2) ); // 3 ``` ```smart header="More to come" -Aqui enaltecemos Arrow functions pela brevidade. Mas não é tudo! Arrow functions têm outras particulariedades interessantes. Voltaremos a elas mais adiante no capitulo . +Here we praised arrow functions for brevity. But that's not all! Arrow functions have other interesting features. We'll return to them later in the chapter . -Por ora, podemos já usá-las para ações de única-linha e callbacks. +For now, we can already use them for one-line actions and callbacks. ``` -## Sumário +## Summary -- Funções são valores. Elas podem ser atribuidas, copiadas ou declaradas em qualquer parte do código. -- Se a função for declarada como uma instrução separada no fluxo do código principal, é chamada de "Declaração de Função". -- Se a função for criada como parte de uma expressão, é chamada de "Expressão de função". -- Declarações de Função são processadas antes de um bloco de código ser executado. Elas são visíveis em qualquer lugar dentro do bloco. -- Expressões de função são criadas quando o fluxo de execução as alcança. +- Functions are values. They can be assigned, copied or declared in any place of the code. +- If the function is declared as a separate statement in the main code flow, that's called a "Function Declaration". +- If the function is created as a part of an expression, it's called a "Function Expression". +- Function Declarations are processed before the code block is executed. They are visible everywhere in the block. +- Function Expressions are created when the execution flow reaches them. -Na maior parte dos casos, quando precisarmos de declarar uma função, uma Declaração de Função é preferível, porque é visível antes da própria definição. Isso dá-nos mais flexibilidade para a organização do código, e geralmente é mais legível. +In most cases when we need to declare a function, a Function Declaration is preferable, because it is visible prior to the declaration itself. That gives us more flexibility in code organization, and is usually more readable. -Assim, deveríamos empregar uma Expressão de Função apenas quando a Declaração de Função não se adequasse à tarefa. Vimos alguns exemplos disso no capítulo, e veremos mais no futuro. +So we should use a Function Expression only when a Function Declaration is not fit for the task. We've seen a couple of examples of that in this chapter, and will see more in the future. -Arrow functions são apropriadas para ações única-linha. Elas vêm em dois sabores: +Arrow functions are handy for one-liners. They come in two flavors: -1. Sem chavetas: `(...args) => expression` -- o lado direito é uma expressão: a função a evalua e retorna o resultado. -2. Com chavetas: `(...args) => { body }` -- chavetas permitem-nos escrever múltiplas instruções dentro da função, mas precisamos de um explícito `return` para retornar alguma coisa. +1. Without curly braces: `(...args) => expression` -- the right side is an expression: the function evaluates it and returns the result. +2. With curly braces: `(...args) => { body }` -- brackets allow us to write multiple statements inside the function, but we need an explicit `return` to return something.