You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
4
4
5
-
## Code structure
5
+
## Estrutura do código
6
6
7
-
Statements are delimited with a semicolon:
7
+
Instruções são delimitadas por ponto-e-vírgula:
8
8
9
9
```js run no-beautify
10
-
alert('Hello'); alert('World');
10
+
alert('Olá'); alert('Mundo');
11
11
```
12
12
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:
14
14
15
15
```js run no-beautify
16
-
alert('Hello')
17
-
alert('World')
16
+
alert('Olá')
17
+
alert('Mundo')
18
18
```
19
19
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:
21
21
22
22
```js run
23
-
alert("There will be an error after this message")
23
+
alert("Haverá um erro depois desta mensagem")
24
24
25
25
[1, 2].forEach(alert)
26
26
```
27
27
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.
29
29
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*):
31
31
32
32
```js
33
33
functionf() {
34
-
// no semicolon needed after function declaration
35
-
}
34
+
...
35
+
}// nenhum ponto-e-vírgula necessário depois da declaração de função
36
36
37
37
for(;;) {
38
-
// no semicolon needed after the loop
39
-
}
38
+
...
39
+
}// nenhum ponto-e-vírgula necessário depois do laço
40
40
```
41
41
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.
43
43
44
-
More in: <info:structure>.
44
+
Mais em: <info:structure>.
45
45
46
-
## Strict mode
46
+
## Modo *strict*
47
47
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"`.
49
49
50
50
```js
51
51
'use strict';
52
52
53
53
...
54
54
```
55
55
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.
57
57
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.
59
59
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.
61
61
62
-
More in: <info:strict-mode>.
62
+
Mais em: <info:strict-mode>.
63
63
64
-
## Variables
64
+
## Variáveis
65
65
66
-
Can be declared using:
66
+
Podem ser declaradas usando:
67
67
68
68
-`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)
71
71
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.
76
76
77
-
Variables are dynamically typed. They can store any value:
77
+
Variáveis obtêm tipos dinâmicamente. Elas podem armazenar qualquer valor:
78
78
79
79
```js
80
80
let x =5;
81
81
x ="John";
82
82
```
83
83
84
-
There are 7 data types:
84
+
Existem 7 tipos de dados:
85
85
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*),
: 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".
107
107
108
108
[`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).
110
110
111
111
[`alert(message)`](mdn:api/Window/alert)
112
-
: Output a`message`.
112
+
: Mostra`message`.
113
113
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.
115
115
116
-
For instance:
116
+
Por exemplo:
117
117
118
118
```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á?");
121
121
122
-
alert( "Visitor: "+ userName ); // Alice
123
-
alert( "Tea wanted: "+ isTeaWanted ); // true
122
+
alert( "Visitante: "+ userName ); // Alice
123
+
alert( "Chá aceite: "+ isTeaWanted ); // true
124
124
```
125
125
126
-
More in: <info:alert-prompt-confirm>.
126
+
Mais em: <info:alert-prompt-confirm>.
127
127
128
-
## Operators
128
+
## Operadores
129
129
130
-
JavaScript supports the following operators:
130
+
JavaScript suporta os seguintes operadores:
131
131
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.
134
134
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*:
136
136
137
137
```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*
140
140
```
141
141
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`.
144
144
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.
147
147
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`.
150
150
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.
153
153
154
154
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:
156
156
157
157
```js run
158
-
alert( 0 == false ); // true
159
-
alert( 0 == '' ); // true
158
+
alert( 0 == false ); // verdadeiro
159
+
alert( 0 == '' ); // verdadeiro
160
160
```
161
161
162
-
Other comparisons convert to a number as well.
162
+
Em outras comparações também são convertidos para números.
163
163
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:
165
165
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.
167
167
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.
169
169
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.
172
172
173
-
More in: <info:operators>, <info:comparison>, <info:logical-operators>.
173
+
Mais em: <info:operators>, <info:comparison>, <info:logical-operators>.
174
174
175
-
## Loops
175
+
## Laços
176
176
177
-
-We covered 3 types of loops:
177
+
-Vimos 3 tipos de laços:
178
178
179
179
```js
180
180
// 1
@@ -193,42 +193,42 @@ More in: <info:operators>, <info:comparison>, <info:logical-operators>.
193
193
}
194
194
```
195
195
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 breaknested 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. Useetiquetas (*labels*) para sair (*break*) de laços aninhados (*nested loops*)..
198
198
199
-
Details in:<info:while-for>.
199
+
Detalhes em:<info:while-for>.
200
200
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.
202
202
203
-
## The "switch" construct
203
+
## A construção "*switch*"
204
204
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.
206
206
207
-
For instance:
207
+
Por exemplo:
208
208
209
209
```js run
210
-
let age = prompt('Your age?', 18);
210
+
let age = prompt('Que idade tem?', 18);
211
211
212
212
switch (age) {
213
213
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
215
215
216
216
case "18":
217
-
alert("This works!");
217
+
alert("Isto funciona!");
218
218
break;
219
219
220
220
default:
221
-
alert("Any value not equal to one above");
221
+
alert("Qualquer valor não igual aos dos 'case' acima");
222
222
}
223
223
```
224
224
225
-
Details in: <info:switch>.
225
+
Detalhes em:<info:switch>.
226
226
227
-
## Functions
227
+
## Funções
228
228
229
-
We covered three ways to create a function in JavaScript:
229
+
Vimos três formas de criar uma função em JavaScript:
230
230
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
232
232
233
233
```js
234
234
function sum(a, b) {
@@ -238,7 +238,7 @@ We covered three ways to create a function in JavaScript:
238
238
}
239
239
```
240
240
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
242
242
243
243
```js
244
244
let sum = function(a, b) {
@@ -248,40 +248,40 @@ We covered three ways to create a function in JavaScript:
248
248
}
249
249
```
250
250
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.
252
252
253
253
3. Arrow functions:
254
254
255
255
```js
256
-
// expression at the right side
256
+
// expressão no lado direito
257
257
let sum = (a, b) => a + b;
258
258
259
-
// or multi-line syntax with { ... }, need return here:
259
+
// ou em sintaxe multi-linha com { ... }, aqui precisa de return
260
260
let sum = (a, b) => {
261
261
// ...
262
262
return a + b;
263
263
}
264
264
265
-
// without arguments
266
-
let sayHi = () => alert("Hello");
265
+
// sem argumentos
266
+
let sayHi = () => alert("Olá");
267
267
268
-
// with a single argument
268
+
// com um único argumento
269
269
let double = n => n * 2;
270
270
```
271
271
272
272
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`.
276
276
277
277
278
-
| Function Declaration | Function Expression |
278
+
|Declaração de Função | Expressão de Função|
279
279
|----------------------|---------------------|
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|
282
282
283
-
More: see <info:function-basics>, <info:function-expressions-arrows>.
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