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
Copy file name to clipboardExpand all lines: 1-js/02-first-steps/04-variables/article.md
+92-92Lines changed: 92 additions & 92 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -93,238 +93,238 @@ A palavra-chave `var` é quase a mesma que `let`. Ela também declara uma variá
93
93
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>.
94
94
````
95
95
96
-
## A real-life analogy
96
+
## Uma analogia da vida real
97
97
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.
99
99
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á"`!:
101
101
102
102

103
103
104
-
We can put any value in the box.
104
+
Podemos pôr qualquer valor na box.
105
105
106
-
We can also change it as many times as we want:
106
+
Também podemos mudá-lo quantas vezes quisermos:
107
107
```js run
108
108
let message;
109
109
110
-
message = 'Hello!';
110
+
message = 'Olá!';
111
111
112
-
message = 'World!'; // value changed
112
+
message = 'Mundo!'; // valor modificado
113
113
114
114
alert(message);
115
115
```
116
116
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:
118
118
119
119

120
120
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.
122
122
123
123
```js run
124
-
let hello = 'Hello world!';
124
+
let hello = 'Olá Mundo!';
125
125
126
126
let message;
127
127
128
128
*!*
129
-
// copy 'Hello world' from hello into message
129
+
// copiar 'Olá Mundo' do hello para message
130
130
message = hello;
131
131
*/!*
132
132
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!
136
136
```
137
137
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.
140
140
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.
142
142
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.
144
144
```
145
145
146
-
## Variable naming [#variable-naming]
146
+
## Nomeação de variável [#variable-naming]
147
147
148
-
There are two limitations on variable names in JavaScript:
148
+
Existem duas limitações em nomes de variáveis no JavaScript:
149
149
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.
152
152
153
-
Examples of valid names:
153
+
Exemplos de nomes válidos:
154
154
155
155
```js
156
156
let userName;
157
157
let test123;
158
158
```
159
159
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`.
161
161
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.
163
163
164
-
These names are valid:
164
+
Estes nomes são válidos:
165
165
166
166
```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 "_"
169
169
170
170
alert($ + _); // 3
171
171
```
172
172
173
-
Examples of incorrect variable names:
173
+
Exemplos de nomes de variável incorretos:
174
174
175
175
```js no-beautify
176
-
let 1a; // cannot start with a digit
176
+
let 1a; // não pode começar com um dígito
177
177
178
-
let my-name; // hyphens '-' aren't allowed in the name
178
+
let my-name; // hífens '-' não são permitidos no nome
179
179
```
180
180
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.
183
183
```
184
184
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:
187
187
188
188
```js
189
189
let имя = '...';
190
190
let 我 = '...';
191
191
```
192
192
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.
194
194
````
195
195
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.
198
198
199
-
For example: `let`, `class`, `return`, and `function` are reserved.
199
+
Por exemplo: `let`, `class`, `return`, e `function` são reservadas.
200
200
201
-
The code below gives a syntax error:
201
+
O código abaixo dá um erro de sintaxe:
202
202
203
203
```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!
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.
212
212
213
213
```js run no-strict
214
-
//note: no "use strict" in this example
214
+
//nota: nenhum "use strict" neste exemplo
215
215
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
217
217
218
218
alert(num); // 5
219
219
```
220
220
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:
222
222
223
223
```js
224
224
"use strict";
225
225
226
226
*!*
227
-
num =5; //error: num is not defined
227
+
num =5; //erro: o número não está definido
228
228
*/!*
229
229
```
230
230
````
231
231
232
-
## Constants
232
+
## Constantes
233
233
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`:
235
235
236
236
```js
237
237
const myBirthday = '18.04.1982';
238
238
```
239
239
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:
241
241
242
242
```js run
243
243
const myBirthday = '18.04.1982';
244
244
245
-
myBirthday = '01.01.2001'; // error, can't reassign the constant!
245
+
myBirthday = '01.01.2001'; // erro, não é possível reatribuir a constante!
246
246
```
247
247
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.
249
249
250
250
251
-
### Uppercase constants
251
+
### Constantes maiúsculas
252
252
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.
254
254
255
-
Such constants are named using capital letters and underscores.
255
+
Tais constantes são nomeadas usando letras maiúsculas e sublinhados.
256
256
257
-
Like this:
257
+
Como estas:
258
258
259
259
```js run
260
260
const COLOR_RED = "#F00";
261
261
const COLOR_GREEN = "#0F0";
262
262
const COLOR_BLUE = "#00F";
263
263
const COLOR_ORANGE = "#FF7F00";
264
264
265
-
// ...when we need to pick a color
265
+
// ...quando precisamos escolher uma cor
266
266
let color = COLOR_ORANGE;
267
267
alert(color); // #FF7F00
268
268
```
269
269
270
-
Benefits:
270
+
Benefícios:
271
271
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`.
275
275
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.
277
277
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.
279
279
280
-
For instance:
280
+
Como por exemplo:
281
281
```js
282
-
const pageLoadTime = /* time taken by a webpage to load */;
282
+
const pageLoadTime = /* tempo necessário para carregar uma página web */;
283
283
```
284
284
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.
286
286
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".
288
288
289
-
## Name things right
289
+
## Nomeie as coisas como devem ser
290
290
291
-
Talking about variables, there's one more extremely important thing.
291
+
Falando em variáveis, há mais uma coisa extremamente importante.
292
292
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.
294
294
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.
296
296
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.
298
298
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.
300
300
301
-
Some good-to-follow rules are:
301
+
Algumas regras boas para seguir são:
302
302
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`.
307
307
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.
309
309
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.
312
312
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.
314
314
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.
316
316
317
-
An extra variable is good, not evil.
317
+
Uma variável extra é o bom, não ruim.
318
318
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.
320
320
```
321
321
322
-
## Summary
322
+
## Resumo
323
323
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`.
325
325
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.
329
329
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.
0 commit comments