Skip to content

Commit 54cbe12

Browse files
author
Márcio Rodrigo
committed
Update 05-types
1 parent 48a6cd4 commit 54cbe12

File tree

4 files changed

+199
-199
lines changed

4 files changed

+199
-199
lines changed

1-js/02-first-steps/04-variables/article.md

Lines changed: 92 additions & 92 deletions
Original file line numberDiff line numberDiff line change
@@ -93,238 +93,238 @@ A palavra-chave `var` é quase a mesma que `let`. Ela também declara uma variá
9393
Existem diferenças sutis entre `let` e `var`, mas elas ainda não são importantes para nós. Nós as abordaremos em detalhes no capítulo <info:var>.
9494
````
9595
96-
## A real-life analogy
96+
## Uma analogia da vida real
9797
98-
We can easily grasp the concept of a "variable" if we imagine it as a "box" for data, with a uniquely-named sticker on it.
98+
Podemos facilmente compreender o conceito de uma "variável" se a imaginarmos como uma "box" de dados, com um adesivo de nome exclusivo.
9999
100-
For instance, the variable `message` can be imagined as a box labeled `"message"` with the value `"Hello!"` in it:
100+
Por exemplo, a variável `mensagem` pode ser imaginada como uma box chamada `"message"`com o valor `"Olá"`!:
101101
102102
![](variable.png)
103103
104-
We can put any value in the box.
104+
Podemos pôr qualquer valor na box.
105105
106-
We can also change it as many times as we want:
106+
Também podemos mudá-lo quantas vezes quisermos:
107107
```js run
108108
let message;
109109
110-
message = 'Hello!';
110+
message = 'Olá!';
111111
112-
message = 'World!'; // value changed
112+
message = 'Mundo!'; // valor modificado
113113
114114
alert(message);
115115
```
116116
117-
When the value is changed, the old data is removed from the variable:
117+
Quando o valor é modificado, os dados antigos são removidos da variável:
118118
119119
![](variable-change.png)
120120
121-
We can also declare two variables and copy data from one into the other.
121+
Nós também podemos declarar duas variáveis e copiar dados de uma para a outra.
122122
123123
```js run
124-
let hello = 'Hello world!';
124+
let hello = 'Olá Mundo!';
125125
126126
let message;
127127
128128
*!*
129-
// copy 'Hello world' from hello into message
129+
// copiar 'Olá Mundo' do hello para message
130130
message = hello;
131131
*/!*
132132
133-
// now two variables hold the same data
134-
alert(hello); // Hello world!
135-
alert(message); // Hello world!
133+
// agora duas variáveis mantêm os mesmos dados
134+
alert(hello); // Olá Mundo!
135+
alert(message); // Olá Mundo!
136136
```
137137
138-
```smart header="Functional languages"
139-
It's interesting to note that [functional](https://en.wikipedia.org/wiki/Functional_programming) programming languages, like [Scala](http://www.scala-lang.org/) or [Erlang](http://www.erlang.org/), forbid changing variable values.
138+
```smart header="Linguagens funcionais"
139+
É interessante notar que linguagens de programação [funcional](https://en.wikipedia.org/wiki/Functional_programming), como [Scala](http://www.scala-lang.org/) or [Erlang](http://www.erlang.org/), proibem a modificação de valores de variáveis.
140140
141-
In such languages, once the value is stored "in the box", it's there forever. If we need to store something else, the language forces us to create a new box (declare a new variable). We can't reuse the old one.
141+
Em tais linguagens, uma vez que o valor é armazenado "na box", ele está lá para sempre. Se precisarmos de armazenar algo mais, a linguagem nos obriga a criar uma nova box (declarar uma nova variável). Não podemos reutilizar a antiga.
142142
143-
Though it may seem a little odd at first sight, these languages are quite capable of serious development. More than that, there are areas like parallel computations where this limitation confers certain benefits. Studying such a language (even if you're not planning to use it soon) is recommended to broaden the mind.
143+
Embora possa parecer um pouco estranho à primeira vista, estas línguas são bastante capazes de um desenvolvimento sério. Mais do que isso, há áreas como cálculos paralelos onde essa limitação confere certos benefícios. Estudar tal linguagem (mesmo que você não esteja planejando usá-la em breve) é recomendado para ampliar a mente.
144144
```
145145
146-
## Variable naming [#variable-naming]
146+
## Nomeação de variável [#variable-naming]
147147
148-
There are two limitations on variable names in JavaScript:
148+
Existem duas limitações em nomes de variáveis no JavaScript:
149149
150-
1. The name must contain only letters, digits, or the symbols `$` and `_`.
151-
2. The first character must not be a digit.
150+
1. O nome deve conter apenas letras, dígitos ou os símbolos `$` e `_`.
151+
2. O primeiro caractere não deve ser um dígito.
152152
153-
Examples of valid names:
153+
Exemplos de nomes válidos:
154154
155155
```js
156156
let userName;
157157
let test123;
158158
```
159159
160-
When the name contains multiple words, [camelCase](https://en.wikipedia.org/wiki/CamelCase) is commonly used. That is: words go one after another, each word except first starting with a capital letter: `myVeryLongName`.
160+
Quando o nome contém várias palavras, [camelCase](https://en.wikipedia.org/wiki/CamelCase) é normalmente utilizado. Isto é: as palavras vão uma após a outra, cada palavra exceto a primeira que começa com uma letra maiúscula: `myVeryLongName`.
161161
162-
What's interesting -- the dollar sign `'$'` and the underscore `'_'` can also be used in names. They are regular symbols, just like letters, without any special meaning.
162+
O que é interessante -- o sinal de dólar `'$'` e o sublinhado `'_'` também podem ser usados em nomes. Eles são símbolos regulares, assim como letras, sem nenhum significado especial.
163163
164-
These names are valid:
164+
Estes nomes são válidos:
165165
166166
```js run untrusted
167-
let $ = 1; // declared a variable with the name "$"
168-
let _ = 2; // and now a variable with the name "_"
167+
let $ = 1; // declarou uma variável com o nome "$"
168+
let _ = 2; // e agora uma variável com o nome "_"
169169
170170
alert($ + _); // 3
171171
```
172172
173-
Examples of incorrect variable names:
173+
Exemplos de nomes de variável incorretos:
174174
175175
```js no-beautify
176-
let 1a; // cannot start with a digit
176+
let 1a; // não pode começar com um dígito
177177
178-
let my-name; // hyphens '-' aren't allowed in the name
178+
let my-name; // hífens '-' não são permitidos no nome
179179
```
180180
181-
```smart header="Case matters"
182-
Variables named `apple` and `AppLE` are two different variables.
181+
```smart header="Questões de caso"
182+
Variáveis chamadas `apple` e `AppLE` são duas variáveis diferentes.
183183
```
184184
185-
````smart header="Non-English letters are allowed, but not recommended"
186-
It is possible to use any language, including cyrillic letters or even hieroglyphs, like this:
185+
````smart header="Letras não inglesas são permitidas, mas não são recomendadas"
186+
É possível usar qualquer idioma, incluindo letras cirílicas ou até hieróglifos, como este:
187187
188188
```js
189189
let имя = '...';
190190
let 我 = '...';
191191
```
192192
193-
Technically, there is no error here, such names are allowed, but there is an international tradition to use English in variable names. Even if we're writing a small script, it may have a long life ahead. People from other countries may need to read it some time.
193+
Tecnicamente, não há erro aqui, tais nomes são permitidos, mas há uma tradição internacional de usar o inglês em nomes de variáveis. Mesmo que estejamos escrevendo um pequeno script, ele pode ter uma longa vida pela frente. Pessoas de outros países podem precisar lê-lo em algum momento.
194194
````
195195

196-
````warn header="Reserved names"
197-
There is a [list of reserved words](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords), which cannot be used as variable names because they are used by the language itself.
196+
````warn header="Nomes reservados"
197+
Existe uma [lista de palavras reservadas](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords), que não pode ser usada como nomes de variáveis porque elas são usadas pela própria linguagem.
198198
199-
For example: `let`, `class`, `return`, and `function` are reserved.
199+
Por exemplo: `let`, `class`, `return`, e `function` são reservadas.
200200
201-
The code below gives a syntax error:
201+
O código abaixo dá um erro de sintaxe:
202202
203203
```js run no-beautify
204-
let let = 5; // can't name a variable "let", error!
205-
let return = 5; // also can't name it "return", error!
204+
let let = 5; // não é possível nomear uma variável "let", erro!
205+
let return = 5; // também não pode nomear como "return", erro!
206206
```
207207
````
208208

209-
````warn header="An assignment without `use strict`"
209+
````warn header="Uma atribuição sem `use strict`"
210210

211-
Normally, we need to define a variable before using it. But in the old times, it was technically possible to create a variable by a mere assignment of the value without using `let`. This still works now if we don't put `use strict` in our scripts to maintain compatibility with old scripts.
211+
Normalmente, precisamos definir uma variável antes de usá-la. Mas nos velhos tempos, era tecnicamente possível criar uma variável através de uma mera atribuição do valor sem usar `let`. Isso ainda funciona se não colocarmos `use strict` em nossos scripts para manter a compatibilidade com scripts antigos.
212212

213213
```js run no-strict
214-
// note: no "use strict" in this example
214+
// nota: nenhum "use strict" neste exemplo
215215

216-
num = 5; // the variable "num" is created if it didn't exist
216+
num = 5; // a variável "num" é criada se não existir
217217

218218
alert(num); // 5
219219
```
220220

221-
This is a bad practice and would cause an error in strict mode:
221+
Esta é uma má prática e causaria um erro no modo estrito:
222222

223223
```js
224224
"use strict";
225225

226226
*!*
227-
num = 5; // error: num is not defined
227+
num = 5; // erro: o número não está definido
228228
*/!*
229229
```
230230
````
231231
232-
## Constants
232+
## Constantes
233233
234-
To declare a constant (unchanging) variable, use `const` instead of `let`:
234+
Para declarar uma variável constante (imutável), use `const` em vez de `let`:
235235
236236
```js
237237
const myBirthday = '18.04.1982';
238238
```
239239
240-
Variables declared using `const` are called "constants". They cannot be changed. An attempt to do so would cause an error:
240+
Variáveis declaradas usando `const` são chamadas de "constantes". Elas não podem ser alteradas. Uma tentativa de fazer isso causaria um erro:
241241
242242
```js run
243243
const myBirthday = '18.04.1982';
244244
245-
myBirthday = '01.01.2001'; // error, can't reassign the constant!
245+
myBirthday = '01.01.2001'; // erro, não é possível reatribuir a constante!
246246
```
247247
248-
When a programmer is sure that a variable will never change, they can declare it with `const` to guarantee and clearly communicate that fact to everyone.
248+
Quando um programador é certo que uma variável nunca mudará, eles podem declará-la com `const` para garantir e comunicar claramente esse fato a todos.
249249
250250
251-
### Uppercase constants
251+
### Constantes maiúsculas
252252
253-
There is a widespread practice to use constants as aliases for difficult-to-remember values that are known prior to execution.
253+
Há uma prática generalizada de usar constantes como aliases para valores difíceis de lembrar que são conhecidos antes da execução.
254254
255-
Such constants are named using capital letters and underscores.
255+
Tais constantes são nomeadas usando letras maiúsculas e sublinhados.
256256
257-
Like this:
257+
Como estas:
258258
259259
```js run
260260
const COLOR_RED = "#F00";
261261
const COLOR_GREEN = "#0F0";
262262
const COLOR_BLUE = "#00F";
263263
const COLOR_ORANGE = "#FF7F00";
264264
265-
// ...when we need to pick a color
265+
// ...quando precisamos escolher uma cor
266266
let color = COLOR_ORANGE;
267267
alert(color); // #FF7F00
268268
```
269269
270-
Benefits:
270+
Benefícios:
271271
272-
- `COLOR_ORANGE` is much easier to remember than `"#FF7F00"`.
273-
- It is much easier to mistype `"#FF7F00"` than `COLOR_ORANGE`.
274-
- When reading the code, `COLOR_ORANGE` is much more meaningful than `#FF7F00`.
272+
- `COLOR_ORANGE` é muito mais fácil de lembrar do que `"#FF7F00"`.
273+
- É muito mais difícil digitar isto `"#FF7F00"` do que `COLOR_ORANGE`.
274+
- Ao ler o código, `COLOR_ORANGE` é muito mais significativo do que `#FF7F00`.
275275
276-
When should we use capitals for a constant and when should we name it normally? Let's make that clear.
276+
Quando devemos usar maiúsculas para uma constante e quando devemos nomeá-la normalmente? Vamos deixar isso bem claro.
277277
278-
Being a "constant" just means that a variable's value never changes. But there are constants that are known prior to execution (like a hexadecimal value for red) and there are constants that are *calculated* in run-time, during the execution, but do not change after their initial assignment.
278+
Ser uma "constante" significa apenas que o valor de uma variável nunca muda. Mas há constantes que são conhecidas antes da execução (como um valor hexadecimal para vermelho) e há constantes que são *calculadas* em tempo de execução, durante a execução, mas não mudam após sua atribuição inicial.
279279
280-
For instance:
280+
Como por exemplo:
281281
```js
282-
const pageLoadTime = /* time taken by a webpage to load */;
282+
const pageLoadTime = /* tempo necessário para carregar uma página web */;
283283
```
284284
285-
The value of `pageLoadTime` is not known prior to the page load, so it's named normally. But it's still a constant because it doesn't change after assignment.
285+
O valor de `pageLoadTime` não é conhecido antes do carregamento da página, portanto é nomeado normalmente. Mas ainda é uma constante porque não muda após a atribuição.
286286
287-
In other words, capital-named constants are only used as aliases for "hard-coded" values.
287+
Em outras palavras, constantes com nomes maiúsculos são usadas apenas como pseudônimos para valores "codificação rígida".
288288
289-
## Name things right
289+
## Nomeie as coisas como devem ser
290290
291-
Talking about variables, there's one more extremely important thing.
291+
Falando em variáveis, há mais uma coisa extremamente importante.
292292
293-
Please name your variables sensibly. Take time to think about this.
293+
Por favor, nomeie as suas variáveis de forma sensata. Tome tempo para pensar sobre isso.
294294
295-
Variable naming is one of the most important and complex skills in programming. A quick glance at variable names can reveal which code was written by a beginner versus an experienced developer.
295+
A nomenclatura variável é uma das habilidades mais importantes e complexas em programação. Uma rápida olhada em nomes de variáveis pode revelar qual código foi escrito por um iniciante versus um desenvolvedor experiente.
296296
297-
In a real project, most of the time is spent modifying and extending an existing code base rather than writing something completely separate from scratch. When we return to some code after doing something else for a while, it's much easier to find information that is well-labeled. Or, in other words, when the variables have good names.
297+
Em um projeto real, a maior parte do tempo é gasto modificando e estendendo uma base de código existente ao invés de escrever algo completamente separado do zero. Quando voltamos a algum código depois de fazer outra coisa por um tempo, é muito mais fácil encontrar informações bem rotuladas. Ou, em outras palavras, quando as variáveis têm bons nomes.
298298
299-
Please spend time thinking about the right name for a variable before declaring it. Doing so will repay you handsomely.
299+
Por favor, gaste tempo pensando sobre o nome certo para uma variável antes de declará-lo. Fazê-lo irá recompensá-lo generosamente.
300300
301-
Some good-to-follow rules are:
301+
Algumas regras boas para seguir são:
302302
303-
- Use human-readable names like `userName` or `shoppingCart`.
304-
- Stay away from abbreviations or short names like `a`, `b`, `c`, unless you really know what you're doing.
305-
- Make names maximally descriptive and concise. Examples of bad names are `data` and `value`. Such names say nothing. It's only okay to use them if the context of the code makes it exceptionally obvious which data or value the variable is referencing.
306-
- Agree on terms within your team and in your own mind. If a site visitor is called a "user" then we should name related variables `currentUser` or `newUser` instead of `currentVisitor` or `newManInTown`.
303+
- Use nomes legíveis por humanos como `userName` ou `shoppingCart`.
304+
- Fique longe de abreviações ou nomes curtos como `a`, `b`, `c`, a menos que você realmente saiba o que está fazendo.
305+
- Faça nomes maximamente descritivos e concisos. Exemplos de nomes ruins são `data` e `value`. Tais nomes não dizem nada. Só é possível usá-los se o contexto do código tornar excepcionalmente óbvio quais dados ou valores a variável está referenciando.
306+
- Concorde em termos dentro da sua equipa e na sua própria mente. Se um visitante do site é chamado de "user", então devemos nomear variáveis relacionadas `currentUser` ou `newUser` em vez de `currentVisitor` ou `newManInTown`.
307307
308-
Sounds simple? Indeed it is, but creating descriptive and concise variable names in practice is not. Go for it.
308+
Parece simples? Na verdade é, mas criar nomes de variáveis descritivas e concisas na prática não é. Vá em frente.
309309
310-
```smart header="Reuse or create?"
311-
And the last note. There are some lazy programmers who, instead of declaring new variables, tend to reuse existing ones.
310+
```smart header="Reutilizar ou criar?"
311+
E a última nota. Existem alguns programadores preguiçosos que, ao invés de declarar novas variáveis, tendem a reutilizar as existentes.
312312
313-
As a result, their variables are like boxes into which people throw different things without changing their stickers. What's inside the box now? Who knows? We need to come closer and check.
313+
Como resultado, suas variáveis são como caixas em que as pessoas jogam coisas diferentes sem mudar seus adesivos. O que está dentro da caixa agora? Quem sabe? Temos de nos aproximar e verificar.
314314
315-
Such programmers save a little bit on variable declaration but lose ten times more on debugging.
315+
Tais programadores economizam um pouco na declaração de variáveis, mas perdem dez vezes mais na depuração.
316316
317-
An extra variable is good, not evil.
317+
Uma variável extra é o bom, não ruim.
318318
319-
Modern JavaScript minifiers and browsers optimize code well enough, so it won't create performance issues. Using different variables for different values can even help the engine optimize your code.
319+
Os minificadores e navegadores JavaScript modernos otimizam o código o suficiente para que ele não crie problemas de desempenho. Usar variáveis diferentes para valores diferentes pode até mesmo ajudar o mecanismo a otimizar seu código.
320320
```
321321
322-
## Summary
322+
## Resumo
323323
324-
We can declare variables to store data by using the `var`, `let`, or `const` keywords.
324+
Podemos declarar variáveis para armazenar dados usando as palavras-chave `var`, `let`, ou `const`.
325325
326-
- `let` -- is a modern variable declaration. The code must be in strict mode to use `let` in Chrome (V8).
327-
- `var` -- is an old-school variable declaration. Normally we don't use it at all, but we'll cover subtle differences from `let` in the chapter <info:var>, just in case you need them.
328-
- `const` -- is like `let`, but the value of the variable can't be changed.
326+
- `let` -- é uma declaração de variável moderna. O código deve estar em modo estrito para usar `let` no Chrome (V8).
327+
- `var` -- é uma declaração de variável da velha escola. Normalmente não a usamos de todo, mas vamos cobrir diferenças sutis de `let` no capítulo <info:var>, para o caso de você precisar delas.
328+
- `const` -- é como `let`, mas o valor da variável não pode ser alterado.
329329
330-
Variables should be named in a way that allows us to easily understand what's inside them.
330+
As variáveis devem ser nomeadas de uma forma que nos permita compreender facilmente o que está dentro delas.
Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11

2-
Backticks embed the expression inside `${...}` into the string.
2+
Acentos graves incorporam a expressão `${...}` dentro da string.
33

44
```js run
55
let name = "Ilya";
66

7-
// the expression is a number 1
8-
alert( `hello ${1}` ); // hello 1
7+
// a expressão é um número 1
8+
alert( `olá ${1}` ); // olá 1
99

10-
// the expression is a string "name"
11-
alert( `hello ${"name"}` ); // hello name
10+
// a expressão é uma string "name"
11+
alert( `olá ${"name"}` ); // olá name
1212

13-
// the expression is a variable, embed it
14-
alert( `hello ${name}` ); // hello Ilya
13+
// a expressão é uma variável, incorpore-a.
14+
alert( `olá ${name}` ); // olá Ilya
1515
```
Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
1-
importance: 5
1+
importância: 5
22

33
---
44

5-
# String quotes
5+
# Aspas de String
66

7-
What is the output of the script?
7+
Qual é o resultado do script?
88

99
```js
1010
let name = "Ilya";
1111

12-
alert( `hello ${1}` ); // ?
12+
alert( `olá ${1}` ); // ?
1313

14-
alert( `hello ${"name"}` ); // ?
14+
alert( `olá ${"name"}` ); // ?
1515

16-
alert( `hello ${name}` ); // ?
16+
alert( `olá ${name}` ); // ?
1717
```

0 commit comments

Comments
 (0)