Skip to content

JavaScript specials #117

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
228 changes: 114 additions & 114 deletions 1-js/02-first-steps/16-javascript-specials/article.md
Original file line number Diff line number Diff line change
@@ -1,234 +1,236 @@
# JavaScript specials
# Especiais em JavaScript

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

## Code structure
## Estrutura do código

Statements are delimited with a semicolon:
Instruções são delimitadas por 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:
Geralmente, uma quebra de linha é também tratada como um delimitador, assim o exemplo acima também funcionaria como:

```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:
Isto chama-se "inserção automática de ponto-e-vírgula". Por vezes, não funciona, a exemplo:

```js run
alert("There will be an error after this message")
alert("Haverá um erro depois desta 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 deveríamos 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:
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):

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

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

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

More in: <info:structure>.
Mais em: <info:structure>.

## Strict mode
## Modo *strict*

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

```js
'use strict';

...
```

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

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

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

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

## 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.
O nome de uma varável pode incluir:

Variables are dynamically typed. They can store any value:
- Letras e dígitos, mas o primeiro caráter não pode ser um dígito.
- Carateres `$` e `_` são normais, on par às letras.
- Alfabetos não-latinos e hieróglifos também são permitidos, mas geralmente não utilizados.

Variáveis obtêm tipos dinâmicamente. Elas podem armazenar qualquer valor:

```js
let x = 5;
x = "John";
```

There are 7 data types:
Existem 7 tipos de dados:

- `number` para números, quer inteiros (*integer*) como em ponto-flutuante (*floating-point*),
- `string` para cadeias-de-carateres (*strings*),
- `boolean` para valores lógicos: `true/false` (verdadeiro/falso),
- `null` -- um tipo de dados com apenas um valor `null`, significando "vazio" ou "não existe",
- `undefined` -- um tipo de dados com apenas um valor `undefined`, significando "não atribuído",
- `object` e `symbol` -- para estruturas de dados complexas e identificadores únicos, que ainda não aprendemos.

- `number` for both floating-point and integer numbers,
- `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.
O operador `typeof` retorna o tipo de um valor, com duas exceções:

The `typeof` operator returns the type for a value, with two exceptions:
```js
typeof null == "object" // error in the language
typeof function(){} == "function" // functions are treated specially
typeof null == "object" // erro da linguagem
typeof function(){} == "function" // funções são tratadas de uma forma especial
```

More in: <info:variables> and <info:types>.
Mais em: <info:variables> e <info:types>.

## Interaction
## Interação

We're using a browser as a working environment, so basic UI functions will be:
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:

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

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

[`alert(message)`](mdn:api/Window/alert)
: Output a `message`.
: Mostra o conteúdo de `message`.

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

For instance:
Por exemplo:

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

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

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

## Operators
## Operadores

JavaScript supports the following operators:
JavaScript suporta os seguintes operadores:

Arithmetical
: Regular: `* + - /`, also `%` for the remainder and `**` for power of a number.
Aritméticos
: Regulares: `* + - /`, e também `%` para o resto de uma divisão inteira, 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 operador binário mais `+` concatena *strings*. E se um dos operandos for uma *string*, o outro também é convertido para *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`.
De atribuição
: Existe uma atribuição simples: `a = b` e composta como `a *= 2`.

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

Ternary
: The only operator with three parameters: `cond ? resultA : resultB`. If `cond` is truthy, returns `resultA`, otherwise `resultB`.
Ternário
: O único operador com três parâmetros: `cond ? resultA : resultB`. Se `cond` (condição) for verdadeira, retorna `resultA`, senão `resultB`.

Logical operators
: 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.
Lógicos
: Os lógicos *AND* (E) `&&` e OR (OU) `||` executam avaliação em curto-circuito (*short-circuit evaluation*) e depois retornam o valor onde pararam. O lógico NOT (NÃO) `!` converte o operando para o tipo boleano e retorna o valor inverso desse boleano.

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

```js run
alert( 0 == false ); // true
alert( 0 == '' ); // true
alert( 0 == false ); // true (verdadeiro)
alert( 0 == '' ); // true (verdadeiro)
```

Other comparisons convert to a number as well.
Outras comparações também convertem para números.

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

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 `==` a si próprios, e a mais nenhum outro.

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

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

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

## Loops

- We covered 3 types of loops:
- Vimos 3 tipos de laços (*loops*):

```js
// 1
while (condition) {
while (condição) {
...
}

// 2
do {
...
} while (condition);
} while (condição);

// 3
for(let i = 0; i < 10; i++) {
...
}
```

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

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

Later we'll study more types of loops to deal with objects.
Mais adiante, estudaremos outros tipos de ciclos (*loops*) 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*" permite substituir múltiplas verificações `if`. Ela emprega `===` (igualdade exata - *strict equality*) nas comparações.

For instance:
Por exemplo:

```js run
let age = prompt('Your age?', 18);
let age = prompt('Que idade tem?', 18);

switch (age) {
case 18:
alert("Won't work"); // the result of prompt is a string, not a number
alert("Não funcionará"); // o resultado de 'prompt' é uma 'string', não um número

case "18":
alert("This works!");
alert("Isto funciona!");
break;

default:
alert("Any value not equal to one above");
alert("Qualquer valor não igual aos dos 'case' acima");
}
```

Details in: <info:switch>.
Detalhes em: <info:switch>.

## Functions
## Funções

We covered three ways to create a function in JavaScript:
Vimos três formas 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) {
Expand All @@ -238,7 +240,7 @@ We covered three ways to create a function in JavaScript:
}
```

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) {
Expand All @@ -248,40 +250,38 @@ We covered three ways to create a function in JavaScript:
}
```

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

3. Arrow functions:
3. Funções seta (*arrow functions*):

```js
// expression at the right side
// expressão no lado direito
let sum = (a, b) => a + b;

// or multi-line syntax with { ... }, need return here:
// ou em sintaxe multi-linha com { ... }; aqui precisa de return:
let sum = (a, b) => {
// ...
return a + b;
}

// without arguments
// sem argumentos
let sayHi = () => alert("Hello");

// with a single argument
// com um único argumento
let double = n => n * 2;
```

- Funções podem ter variáveis locais: aquelas declaradas no seu corpo (*body*). Tais variáveis apenas são visíveis dentro da função.
- Parâmetros podem ter valores por defeito: `function sum(a = 1, b = 2) {...}`.
- Funções sempre retornam algo. Se não houver uma instrução `return`, então o resultado é `undefined`.

- Functions may have local variables: those declared inside its body. 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`.


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

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

## More to come
## Mais adiante

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.
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.