Skip to content

Commit a2a1805

Browse files
authored
Transfer #66 translation
1 parent bc77708 commit a2a1805

File tree

1 file changed

+114
-114
lines changed
  • 1-js/02-first-steps/18-javascript-specials

1 file changed

+114
-114
lines changed
Lines changed: 114 additions & 114 deletions
Original file line numberDiff line numberDiff line change
@@ -1,180 +1,180 @@
1-
# JavaScript specials
1+
# Especiais em JavaScript
22

3-
This chapter briefly recaps the features of JavaScript that we've learned by now, paying special attention to subtle moments.
3+
Este capítulo brevemente revê as funcionalidades de JavaScript que aprendemos até agora, dando atenção especial a momentos subtis.
44

5-
## Code structure
5+
## Estrutura do código
66

7-
Statements are delimited with a semicolon:
7+
Instruções são delimitadas por ponto-e-vírgula:
88

99
```js run no-beautify
10-
alert('Hello'); alert('World');
10+
alert('Olá'); alert('Mundo');
1111
```
1212

13-
Usually, a line-break is also treated as a delimiter, so that would also work:
13+
Geralmente, uma quebra de linha é também tratada como um delimitador, assim o acima também funcionaria como:
1414

1515
```js run no-beautify
16-
alert('Hello')
17-
alert('World')
16+
alert('Olá')
17+
alert('Mundo')
1818
```
1919

20-
That's called "automatic semicolon insertion". Sometimes it doesn't work, for instance:
20+
Isto chama-se "inserção automática de ponto-e-vírgula". Por vezes, não funciona, a exemplo:
2121

2222
```js run
23-
alert("There will be an error after this message")
23+
alert("Haverá um erro depois desta mensagem")
2424

2525
[1, 2].forEach(alert)
2626
```
2727

28-
Most codestyle guides agree that we should put a semicolon after each statement.
28+
A maioria dos guias de estilo-de-código concorda que deveríamos colocar um ponto-e-vírgula após cada instrução.
2929

30-
Semicolons are not required after code blocks `{...}` and syntax constructs with them like loops:
30+
Pontos-e-vírgula não são necessários depois de blocos de código `{...}` e outras construções sintáticas que os utilizem, como laços (*loops*):
3131

3232
```js
3333
function f() {
34-
// no semicolon needed after function declaration
35-
}
34+
...
35+
} // nenhum ponto-e-vírgula necessário depois da declaração de função
3636

3737
for(;;) {
38-
// no semicolon needed after the loop
39-
}
38+
...
39+
} // nenhum ponto-e-vírgula necessário depois do laço
4040
```
4141

42-
...But even if we can put an "extra" semicolon somewhere, that's not an error. It will be ignored.
42+
...Mas mesmo que coloquemos um ponto-e-vírgula "extra" algures, isso não é um erro. Será ignorado.
4343

44-
More in: <info:structure>.
44+
Mais em: <info:structure>.
4545

46-
## Strict mode
46+
## Modo *strict*
4747

48-
To fully enable all features of modern JavaScript, we should start scripts with `"use strict"`.
48+
Para activar completamente todas as funcionalidades do JavaScript moderno, devemos começar programas (*scripts*) com `"use strict"`.
4949

5050
```js
5151
'use strict';
5252

5353
...
5454
```
5555

56-
The directive must be at the top of a script or at the beginning of a function.
56+
A diretiva deve estar no topo de um *script* ou no início de uma função.
5757

58-
Without `"use strict"`, everything still works, but some features behave in the old-fashion, "compatible" way. We'd generally prefer the modern behavior.
58+
Sem `"use strict"`, tudo ainda funciona, mas algumas funcionalidades comportam-se à forma antiga, no modo "compatível". Nós geralmente preferiríamos o comportamento moderno.
5959

60-
Some modern features of the language (like classes that we'll study in the future) enable strict mode implicitly.
60+
Algumas funcionalidades modernas da linguagem (como classes que estudaremos no futuro) ativam o modo *strict* implícitamente.
6161

62-
More in: <info:strict-mode>.
62+
Mais em: <info:strict-mode>.
6363

64-
## Variables
64+
## Variáveis
6565

66-
Can be declared using:
66+
Podem ser declaradas usando:
6767

6868
- `let`
69-
- `const` (constant, can't be changed)
70-
- `var` (old-style, will see later)
69+
- `const` (constante, não pode ser alterada)
70+
- `var` (estilo-antigo, veremos mais tarde)
7171

72-
A variable name can include:
73-
- Letters and digits, but the first character may not be a digit.
74-
- Characters `$` and `_` are normal, on par with letters.
75-
- Non-Latin alphabets and hieroglyphs are also allowed, but commonly not used.
72+
O nome de uma varável pode incluir:
73+
- Letras e dígitos, mas o primeiro caráter não pode ser um dígito.
74+
- Carateres `$` e `_` são normais, *on par* às letras.
75+
- Alfabetos não-latinos e hieróglifos também são permitidos, mas geralmente não utilizados.
7676

77-
Variables are dynamically typed. They can store any value:
77+
Variáveis obtêm tipos dinâmicamente. Elas podem armazenar qualquer valor:
7878

7979
```js
8080
let x = 5;
8181
x = "John";
8282
```
8383

84-
There are 7 data types:
84+
Existem 7 tipos de dados:
8585

86-
- `number` for both floating-point and integer numbers,
87-
- `string` for strings,
88-
- `boolean` for logical values: `true/false`,
89-
- `null` -- a type with a single value `null`, meaning "empty" or "does not exist",
90-
- `undefined` -- a type with a single value `undefined`, meaning "not assigned",
91-
- `object` and `symbol` -- for complex data structures and unique identifiers, we haven't learnt them yet.
86+
- `number` para números, quer inteiros (*integer*) como em ponto-flutuante (*floating-point*),
87+
- `string` para cadeias-de-carateres (*strings*),
88+
- `boolean` para valores lógicos: `true/false` (verdadeiro/falso),
89+
- `null` -- um tipo de dados com apenas um valor `null`, significando "vazio" ou "não existe",
90+
- `undefined` -- um tipo de dados com apenas um valor `undefined`, significando "não atribuido",
91+
- `object` and `symbol` -- para estruturas de dados complexas e identificadores únicos, que ainda não aprendemos.
9292

93-
The `typeof` operator returns the type for a value, with two exceptions:
93+
O operador `typeof` retorna o tipo de um valor, com duas exceções:
9494
```js
95-
typeof null == "object" // error in the language
96-
typeof function(){} == "function" // functions are treated specially
95+
typeof null == "object" // erro da linguagem
96+
typeof function(){} == "function" // funções são tratadas especialmente
9797
```
9898

99-
More in: <info:variables> and <info:types>.
99+
Mais em: <info:variables> e <info:types>.
100100

101-
## Interaction
101+
## Interação
102102

103-
We're using a browser as a working environment, so basic UI functions will be:
103+
Estamos a utilizar um navegador (*browser*) como ambiente de trabalho, assim funções básicas de *UI* (Interface/interação com o Utilizador) serão:
104104

105105
[`prompt(question, [default])`](mdn:api/Window/prompt)
106-
: Ask a `question`, and return either what the visitor entered or `null` if they pressed "cancel".
106+
: Faz uma `question`, e retorna o que o visitante inseriu ou `null` se a pessoa "cancelou".
107107

108108
[`confirm(question)`](mdn:api/Window/confirm)
109-
: Ask a `question` and suggest to choose between Ok and Cancel. The choice is returned as `true/false`.
109+
: Faz uma `question` e sugere que a pessoa escolha entre *Ok* e *Cancel*. A escolha é retornada como `true/false` (verdadeiro/falso).
110110

111111
[`alert(message)`](mdn:api/Window/alert)
112-
: Output a `message`.
112+
: Mostra `message`.
113113

114-
All these functions are *modal*, they pause the code execution and prevent the visitor from interacting with the page until they answer.
114+
Todas estas funções são *modal* (modais), elas suspendem o código em execução e impedem o visitante de interagir com a página até obterem uma resposta.
115115

116-
For instance:
116+
Por exemplo:
117117

118118
```js run
119-
let userName = prompt("Your name?", "Alice");
120-
let isTeaWanted = confirm("Do you want some tea?");
119+
let userName = prompt("Como se chama?", "Alice");
120+
let isTeaWanted = confirm("Quer chá?");
121121

122-
alert( "Visitor: " + userName ); // Alice
123-
alert( "Tea wanted: " + isTeaWanted ); // true
122+
alert( "Visitante: " + userName ); // Alice
123+
alert( "Chá aceite: " + isTeaWanted ); // true
124124
```
125125

126-
More in: <info:alert-prompt-confirm>.
126+
Mais em: <info:alert-prompt-confirm>.
127127

128-
## Operators
128+
## Operadores
129129

130-
JavaScript supports the following operators:
130+
JavaScript suporta os seguintes operadores:
131131

132-
Arithmetical
133-
: Regular: `* + - /`, also `%` for the remainder and `**` for power of a number.
132+
Aritmétricos
133+
: Regulares: `* + - /`, e também `%` para o resto de uma divisão inteira, e `**` para a potência de um número.
134134

135-
The binary plus `+` concatenates strings. And if any of the operands is a string, the other one is converted to string too:
135+
O operador binário mais `+` concatena *strings*. E se um dos operandos for uma *string*, o outro também é convertido para *string*:
136136

137137
```js run
138-
alert( '1' + 2 ); // '12', string
139-
alert( 1 + '2' ); // '12', string
138+
alert( '1' + 2 ); // '12', *string*
139+
alert( 1 + '2' ); // '12', *string*
140140
```
141141

142-
Assignments
143-
: There is a simple assignment: `a = b` and combined ones like `a *= 2`.
142+
De atribuição
143+
: Existe uma atribuição simples: `a = b` e combinadas como `a *= 2`.
144144

145-
Bitwise
146-
: Bitwise operators work with integers on bit-level: see the [docs](mdn:/JavaScript/Reference/Operators/Bitwise_Operators) when they are needed.
145+
*Bit-a-bit*
146+
: Operadores *bit-a-bit* (*bitwise operators*) trabalham com números inteiros ao nível do *bit*: veja em [docs](mdn:/JavaScript/Reference/Operators/Bitwise_Operators) quando são necessários.
147147

148-
Ternary
149-
: The only operator with three parameters: `cond ? resultA : resultB`. If `cond` is truthy, returns `resultA`, otherwise `resultB`.
148+
Ternários
149+
: O único operador com três parâmetros: `condition ? resultA : resultB`. Se `condition` for verdadeira, retorna `resultA`, senão `resultB`.
150150

151-
Logical operators
152-
: Logical AND `&&` and OR `||` perform short-circuit evaluation and then return the value where it stopped. Logical NOT `!` converts the operand to boolean type and returns the inverse value.
151+
Lógicos
152+
: Os lógicos *AND* (E) `&&` e OR (OU) `||` executam evaluação em curto-circuito (*short-circuit evaluation*) e depois retornam o valor em que pararam. O lógico *NOT* (NÃO) `!` converte o operando para o tipo boleano e retorna o valor inverso desse boleano.
153153

154154
Comparisons
155-
: 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:
155+
: O de verificação de igualdade `==` para valores de tipos diferentes, os converte para números (exceto `null` e `undefined` que igualam-se a si próprios, e a nada mais); assim os seguintes são similares:
156156

157157
```js run
158-
alert( 0 == false ); // true
159-
alert( 0 == '' ); // true
158+
alert( 0 == false ); // verdadeiro
159+
alert( 0 == '' ); // verdadeiro
160160
```
161161

162-
Other comparisons convert to a number as well.
162+
Em outras comparações também são convertidos para números.
163163

164-
The strict equality operator `===` doesn't do the conversion: different types always mean different values for it, so:
164+
O operador de igualdade exata (*strict equality*) `===` não executa a conversão; para ele com tipos diferentes sempre são valores diferentes, assim:
165165

166-
Values `null` and `undefined` are special: they equal `==` each other and don't equal anything else.
166+
Os valores `null` e `undefined` são especiais: eles são iguais `==` a si próprios e a mais nenhum outro.
167167

168-
Greater/less comparisons compare strings character-by-character, other types are converted to a number.
168+
Comparações maior/menor, comparam *strings* (cadeias-de-carateres) caráter-por-caráter, outros tipos são convertidos para número.
169169

170-
Other operators
171-
: There are few others, like a comma operator.
170+
Outros operadores
171+
: Existem mais uns outros poucos, como o operador vírgula.
172172

173-
More in: <info:operators>, <info:comparison>, <info:logical-operators>.
173+
Mais em: <info:operators>, <info:comparison>, <info:logical-operators>.
174174

175-
## Loops
175+
## Laços
176176

177-
- We covered 3 types of loops:
177+
- Vimos 3 tipos de laços:
178178

179179
```js
180180
// 1
@@ -193,42 +193,42 @@ More in: <info:operators>, <info:comparison>, <info:logical-operators>.
193193
}
194194
```
195195

196-
- The variable declared in `for(let...)` loop is visible only inside the loop. But we can also omit `let` and reuse an existing variable.
197-
- Directives `break/continue` allow to exit the whole loop/current iteration. Use labels to break nested loops.
196+
- A variável declarada no laço `for(let...)` apenas é visível dentro do laço. Mas também podemos omitir `let` e reusar uma variável já existente.
197+
- As diretivas `break/continue` permitem sair completamente-do-laço/da-actual-iteração. Use etiquetas (*labels*) para sair (*break*) de laços aninhados (*nested loops*)..
198198

199-
Details in: <info:while-for>.
199+
Detalhes em: <info:while-for>.
200200

201-
Later we'll study more types of loops to deal with objects.
201+
Mais adiante estudaremos outros tipos de laços para lidar com objetos.
202202

203-
## The "switch" construct
203+
## A construção "*switch*"
204204

205-
The "switch" construct can replace multiple `if` checks. It uses `===` (strict equality) for comparisons.
205+
A construção "*switch*" permite substituir múltiplas verificações `if`. Ela emprega `===` (igualdade exata - *strict equality*) nas comparações.
206206

207-
For instance:
207+
Por exemplo:
208208

209209
```js run
210-
let age = prompt('Your age?', 18);
210+
let age = prompt('Que idade tem?', 18);
211211
212212
switch (age) {
213213
case 18:
214-
alert("Won't work"); // the result of prompt is a string, not a number
214+
alert("Não funcionará"); // o resultado de *prompt* é uma *string*, não um número
215215
216216
case "18":
217-
alert("This works!");
217+
alert("Isto funciona!");
218218
break;
219219
220220
default:
221-
alert("Any value not equal to one above");
221+
alert("Qualquer valor não igual aos dos 'case' acima");
222222
}
223223
```
224224

225-
Details in: <info:switch>.
225+
Detalhes em: <info:switch>.
226226

227-
## Functions
227+
## Funções
228228

229-
We covered three ways to create a function in JavaScript:
229+
Vimos três formas de criar uma função em JavaScript:
230230

231-
1. Function Declaration: the function in the main code flow
231+
1. Declaração de função: a função no fluxo principal do código
232232

233233
```js
234234
function sum(a, b) {
@@ -238,7 +238,7 @@ We covered three ways to create a function in JavaScript:
238238
}
239239
```
240240

241-
2. Function Expression: the function in the context of an expression
241+
2. Expressão de função: a função no contexto de uma expressão
242242

243243
```js
244244
let sum = function(a, b) {
@@ -248,40 +248,40 @@ We covered three ways to create a function in JavaScript:
248248
}
249249
```
250250

251-
Function expressions can have a name, like `sum = function name(a, b)`, but that `name` is only visible inside that function.
251+
Expressões de função podem ter um nome, como `sum = function name(a, b)`, mas esse `name` apenas é visível dentro da função.
252252

253253
3. Arrow functions:
254254

255255
```js
256-
// expression at the right side
256+
// expressão no lado direito
257257
let sum = (a, b) => a + b;
258258
259-
// or multi-line syntax with { ... }, need return here:
259+
// ou em sintaxe multi-linha com { ... }, aqui precisa de return
260260
let sum = (a, b) => {
261261
// ...
262262
return a + b;
263263
}
264264
265-
// without arguments
266-
let sayHi = () => alert("Hello");
265+
// sem argumentos
266+
let sayHi = () => alert("Olá");
267267
268-
// with a single argument
268+
// com um único argumento
269269
let double = n => n * 2;
270270
```
271271

272272

273-
- Functions may have local variables: those declared inside its body. Such variables are only visible inside the function.
274-
- Parameters can have default values: `function sum(a = 1, b = 2) {...}`.
275-
- Functions always return something. If there's no `return` statement, then the result is `undefined`.
273+
- Funções podem ter variáveis locais: aquelas declaradas no seu corpo. Tais variáveis apenas são visíveis dentro da função.
274+
- Parâmetros podem ter valores por defeito: `function sum(a = 1, b = 2) {...}`.
275+
- Funções sempre retornam algo. Se não houver uma instrução `return`, então o resultado é `undefined`.
276276

277277

278-
| Function Declaration | Function Expression |
278+
| Declaração de Função | Expressão de Função |
279279
|----------------------|---------------------|
280-
| visible in the whole code block | created when the execution reaches it |
281-
| - | can have a name, visible only inside the function |
280+
| visível em todo o bloco de código | criada quando a execução a alcança |
281+
| - | pode ter um nome, visível apenas dentro da função |
282282

283-
More: see <info:function-basics>, <info:function-expressions-arrows>.
283+
Mais: veja <info:function-basics>, <info:function-expressions-arrows>.
284284

285-
## More to come
285+
## Mais adiante
286286

287-
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.
287+
Esta foi uma breve lista de funcionalidades de JavaScript. Até agora apenas estudámos o básico. Mais adiante no tutorial encontrará mais funcionalidades especiais e avançadas de JavaScript.

0 commit comments

Comments
 (0)