diff --git a/1-js/02-first-steps/18-javascript-specials/article.md b/1-js/02-first-steps/18-javascript-specials/article.md index 016214e3b..646e28179 100644 --- a/1-js/02-first-steps/18-javascript-specials/article.md +++ b/1-js/02-first-steps/18-javascript-specials/article.md @@ -1,51 +1,51 @@ -# JavaScript specials +# Especiais do JavaScript -This chapter briefly recaps the features of JavaScript that we've learned by now, paying special attention to subtle moments. +Este capítulo recapitula brevemente os recursos do JavaScript que aprendemos até agora, prestando atenção especial a momentos sutis. -## Code structure +## Estrutura do código -Statements are delimited with a semicolon: +As instruções são delimitadas com um ponto e vírgula: ```js run no-beautify -alert('Hello'); alert('World'); +alert('Olá'); alert('Mundo'); ``` -Usually, a line-break is also treated as a delimiter, so that would also work: +Normalmente, uma quebra de linha também é tratada como um delimitador, então isso também funcionaria: ```js run no-beautify -alert('Hello') -alert('World') +alert('Olá') +alert('Mundo') ``` -That's called "automatic semicolon insertion". Sometimes it doesn't work, for instance: +Isso é chamado de "inserção automática de ponto e vírgula". Às vezes não funciona, por exemplo: ```js run -alert("There will be an error after this message") +alert("Haverá um erro após esta mensagem") [1, 2].forEach(alert) ``` -Most codestyle guides agree that we should put a semicolon after each statement. +A maioria dos guias de estilo de código concorda que devemos colocar um ponto e vírgula após cada instrução. -Semicolons are not required after code blocks `{...}` and syntax constructs with them like loops: +Ponto e vírgula não são necessários após blocos de código `{...}` e construções de sintaxe com eles, como laços: ```js function f() { - // no semicolon needed after function declaration + // não é necessário ponto e vírgula após a declaração da função } for(;;) { - // no semicolon needed after the loop + // não é necessário ponto e vírgula após o laço } ``` -...But even if we can put an "extra" semicolon somewhere, that's not an error. It will be ignored. +...Mas mesmo que possamos colocar um ponto e vírgula "extra" em algum lugar, isso não é um erro. Será ignorado. -More in: . +Mais em: . -## Strict mode +## Modo estrito -To fully enable all features of modern JavaScript, we should start scripts with `"use strict"`. +Para habilitar totalmente todos os recursos do JavaScript moderno, devemos iniciar os scripts com `"use strict"`. ```js 'use strict'; @@ -53,143 +53,143 @@ To fully enable all features of modern JavaScript, we should start scripts with ... ``` -The directive must be at the top of a script or at the beginning of a function body. +A diretiva deve estar no topo de um script ou no início do corpo de uma função. -Without `"use strict"`, everything still works, but some features behave in the old-fashioned, "compatible" way. We'd generally prefer the modern behavior. +Sem `"use strict"`, tudo ainda funciona, mas alguns recursos se comportam da maneira antiga, "compatível". Geralmente, preferimos o comportamento moderno. -Some modern features of the language (like classes that we'll study in the future) enable strict mode implicitly. +Alguns recursos modernos da linguagem (como classes que estudaremos no futuro) ativam o modo estrito implicitamente. -More in: . +Mais em: . -## Variables +## Variáveis -Can be declared using: +Podem ser declaradas usando: - `let` -- `const` (constant, can't be changed) -- `var` (old-style, will see later) +- `const` (constante, não pode ser alterada) +- `var` (estilo antigo, veremos mais tarde) -A variable name can include: -- Letters and digits, but the first character may not be a digit. -- Characters `$` and `_` are normal, on par with letters. -- Non-Latin alphabets and hieroglyphs are also allowed, but commonly not used. +Um nome de variável pode incluir: +- Letras e dígitos, mas o primeiro caractere não pode ser um dígito. +- Os caracteres `$` e `_` são normais, assim como as letras. +- Alfabetos não latinos e hieróglifos também são permitidos, mas comumente não são usados. -Variables are dynamically typed. They can store any value: +As variáveis são de tipo dinâmico. Elas podem armazenar qualquer valor: ```js let x = 5; -x = "John"; +x = "João"; ``` -There are 8 data types: +Existem 8 tipos de dados: -- `number` for both floating-point and integer numbers, -- `bigint` for integer numbers of arbitrary length, -- `string` for strings, -- `boolean` for logical values: `true/false`, -- `null` -- a type with a single value `null`, meaning "empty" or "does not exist", -- `undefined` -- a type with a single value `undefined`, meaning "not assigned", -- `object` and `symbol` -- for complex data structures and unique identifiers, we haven't learnt them yet. +- `number` para números de ponto flutuante e inteiros, +- `bigint` para números inteiros de comprimento arbitrário, +- `string` para strings, +- `boolean` para valores lógicos: `true/false`, +- `null` -- um tipo com um único valor `null`, significando "vazio" ou "não existe", +- `undefined` -- um tipo com um único valor `undefined`, significando "não atribuído", +- `object` e `symbol` -- para estruturas de dados complexas e identificadores únicos, ainda não os aprendemos. -The `typeof` operator returns the type for a value, with two exceptions: +O operador `typeof` retorna o tipo de um valor, com duas exceções: ```js -typeof null == "object" // error in the language -typeof function(){} == "function" // functions are treated specially +typeof null == "object" // erro na linguagem +typeof function(){} == "function" // as funções são tratadas de forma especial ``` -More in: and . +Mais em: e . -## Interaction +## Interação -We're using a browser as a working environment, so basic UI functions will be: +Estamos usando um navegador como ambiente de trabalho, então as funções básicas da interface do usuário serão: -[`prompt(question, [default])`](mdn:api/Window/prompt) -: Ask a `question`, and return either what the visitor entered or `null` if they clicked "cancel". +[`prompt(pergunta, [padrão])`](https://developer.mozilla.org/pt-BR/docs/Web/API/Window/prompt) +: Faz uma `pergunta` e retorna o que o visitante inseriu ou `null` se ele clicou em "cancelar". -[`confirm(question)`](mdn:api/Window/confirm) -: Ask a `question` and suggest to choose between Ok and Cancel. The choice is returned as `true/false`. +[`confirm(pergunta)`](https://developer.mozilla.org/pt-BR/docs/Web/API/Window/confirm) +: Faz uma `pergunta` e sugere a escolha entre Ok e Cancelar. A escolha é retornada como `true/false`. -[`alert(message)`](mdn:api/Window/alert) -: Output a `message`. +[`alert(mensagem)`](https://developer.mozilla.org/pt-BR/docs/Web/API/Window/alert) +: Exibe uma `mensagem`. -All these functions are *modal*, they pause the code execution and prevent the visitor from interacting with the page until they answer. +Todas essas funções são *modais*, elas pausam a execução do código e impedem que o visitante interaja com a página até que responda. -For instance: +Por exemplo: ```js run -let userName = prompt("Your name?", "Alice"); -let isTeaWanted = confirm("Do you want some tea?"); +let nomeDeUsuario = prompt("Qual é o seu nome?", "Alice"); +let querCha = confirm("Você quer um pouco de chá?"); -alert( "Visitor: " + userName ); // Alice -alert( "Tea wanted: " + isTeaWanted ); // true +alert( "Visitante: " + nomeDeUsuario ); // Alice +alert( "Chá desejado: " + querCha ); // true ``` -More in: . +Mais em: . -## Operators +## Operadores -JavaScript supports the following operators: +O JavaScript suporta os seguintes operadores: -Arithmetical -: Regular: `* + - /`, also `%` for the remainder and `**` for power of a number. +Aritméticos +: Regulares: `* + - /`, também `%` para o resto e `**` para a potência de um número. - The binary plus `+` concatenates strings. And if any of the operands is a string, the other one is converted to string too: + O `+` binário concatena strings. E se um dos operandos for uma string, o outro também será convertido em string: ```js run alert( '1' + 2 ); // '12', string alert( 1 + '2' ); // '12', string ``` -Assignments -: There is a simple assignment: `a = b` and combined ones like `a *= 2`. +Atribuições +: Existe uma atribuição simples: `a = b` e as combinadas como `a *= 2`. Bitwise -: Bitwise operators work with 32-bit integers at the lowest, bit-level: see the [docs](mdn:/JavaScript/Guide/Expressions_and_Operators#bitwise_operators) when they are needed. +: Os operadores bitwise trabalham com inteiros de 32 bits no nível mais baixo, o nível de bit: veja a [documentação](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Guide/Expressions_and_operators#operadores_bit_a_bit) quando forem necessários. -Conditional -: The only operator with three parameters: `cond ? resultA : resultB`. If `cond` is truthy, returns `resultA`, otherwise `resultB`. +Condicional +: O único operador com três parâmetros: `cond ? resultadoA : resultadoB`. Se `cond` for verdadeiro, retorna `resultadoA`, caso contrário, `resultadoB`. -Logical operators -: Logical AND `&&` and OR `||` perform short-circuit evaluation and then return the value where it stopped (not necessary `true`/`false`). Logical NOT `!` converts the operand to boolean type and returns the inverse value. +Operadores lógicos +: O E lógico `&&` e o OU lógico `||` realizam avaliação de curto-circuito e, em seguida, retornam o valor onde pararam (não necessariamente `true`/`false`). O NÃO lógico `!` converte o operando para o tipo booleano e retorna o valor inverso. -Nullish coalescing operator -: The `??` operator provides a way to choose a defined value from a list of variables. The result of `a ?? b` is `a` unless it's `null/undefined`, then `b`. +Operador de coalescência nula +: O operador `??` fornece uma maneira de escolher um valor definido de uma lista de variáveis. O resultado de `a ?? b` é `a`, a menos que seja `null/undefined`, então é `b`. -Comparisons -: Equality check `==` for values of different types converts them to a number (except `null` and `undefined` that equal each other and nothing else), so these are equal: +Comparações +: A verificação de igualdade `==` para valores de tipos diferentes, os converte em um número (exceto `null` e `undefined`, que são iguais entre si e a mais nada). Então estas são equivalentes: ```js run alert( 0 == false ); // true alert( 0 == '' ); // true ``` - Other comparisons convert to a number as well. + Outras comparações também convertem para um número. - The strict equality operator `===` doesn't do the conversion: different types always mean different values for it. + O operador de igualdade estrita `===` não faz a conversão: tipos diferentes sempre significam valores diferentes para ele. - Values `null` and `undefined` are special: they equal `==` each other and don't equal anything else. + Os valores `null` e `undefined` são especiais: eles são iguais `==` um ao outro e não são iguais a mais nada. - Greater/less comparisons compare strings character-by-character, other types are converted to a number. + As comparações de maior/menor comparam strings caractere por caractere, outros tipos são convertidos em um número. -Other operators -: There are few others, like a comma operator. +Outros operadores +: Existem alguns outros, como o operador vírgula. -More in: , , , . +Mais em: , , , . -## Loops +## Laços -- We covered 3 types of loops: +- Cobrimos 3 tipos de laços: ```js // 1 - while (condition) { + while (condicao) { ... } // 2 do { ... - } while (condition); + } while (condicao); // 3 for(let i = 0; i < 10; i++) { @@ -197,88 +197,88 @@ More in: , , , . +Detalhes em: . -Later we'll study more types of loops to deal with objects. +Mais tarde, estudaremos mais tipos de laços para lidar com objetos. -## The "switch" construct +## A construção "switch" -The "switch" construct can replace multiple `if` checks. It uses `===` (strict equality) for comparisons. +A construção "switch" pode substituir várias verificações `if`. Ela usa `===` (igualdade estrita) para comparações. -For instance: +Por exemplo: ```js run -let age = prompt('Your age?', 18); +let idade = prompt('Qual é a sua idade?', 18); -switch (age) { +switch (idade) { case 18: - alert("Won't work"); // the result of prompt is a string, not a number + alert("Não vai funcionar"); // o resultado do prompt é uma string, não um número break; case "18": - alert("This works!"); + alert("Isso funciona!"); break; default: - alert("Any value not equal to one above"); + alert("Qualquer valor não igual a um dos anteriores"); } ``` -Details in: . +Detalhes em: . -## Functions +## Funções -We covered three ways to create a function in JavaScript: +Cobrimos três maneiras de criar uma função em JavaScript: -1. Function Declaration: the function in the main code flow +1. Declaração de Função: a função no fluxo principal do código ```js - function sum(a, b) { - let result = a + b; + function soma(a, b) { + let resultado = a + b; - return result; + return resultado; } ``` -2. Function Expression: the function in the context of an expression +2. Expressão de Função: a função no contexto de uma expressão ```js - let sum = function(a, b) { - let result = a + b; + let soma = function(a, b) { + let resultado = a + b; - return result; + return resultado; }; ``` -3. Arrow functions: +3. Funções de Seta: ```js - // expression on the right side - let sum = (a, b) => a + b; + // expressão do lado direito + let soma = (a, b) => a + b; - // or multi-line syntax with { ... }, need return here: - let sum = (a, b) => { + // ou sintaxe de várias linhas com { ... }, precisa de return aqui: + let soma = (a, b) => { // ... return a + b; } - // without arguments - let sayHi = () => alert("Hello"); + // sem argumentos + let digaOi = () => alert("Olá"); - // with a single argument - let double = n => n * 2; + // com um único argumento + let dobro = n => n * 2; ``` -- Functions may have local variables: those declared inside its body or its parameter list. Such variables are only visible inside the function. -- Parameters can have default values: `function sum(a = 1, b = 2) {...}`. -- Functions always return something. If there's no `return` statement, then the result is `undefined`. +- As funções podem ter variáveis locais: aquelas declaradas dentro de seu corpo ou em sua lista de parâmetros. Tais variáveis são visíveis apenas dentro da função. +- Os parâmetros podem ter valores padrão: `function soma(a = 1, b = 2) {...}`. +- As funções sempre retornam algo. Se não houver uma instrução `return`, o valor retornado será `undefined`. -Details: see , . +Detalhes: veja , . -## More to come +## Mais por vir -That was a brief list of JavaScript features. As of now we've studied only basics. Further in the tutorial you'll find more specials and advanced features of JavaScript. +Essa foi uma breve lista de recursos do JavaScript. Até agora, estudamos apenas o básico. Mais adiante no tutorial, você encontrará mais especiais e recursos avançados do JavaScript. \ No newline at end of file