Functions · Funções
Functions
- A function is a named block of code you can run again and again.
function name(params) { ... return value; }. Theparamsare the inputs.returnhands a value back to whoever called the function.
Funções
- Uma função é um bloco de código nomeado que você pode executar repetidamente.
function name(params) { ... return value; }. Osparamssão as entradas.returndevolve um valor para quem chamou a função.
function square(n) {
return n * n;
}
console.log(square(6)); // → 36
Functions that just do something
- A function can do something (like print) instead of returning a value.
- Call it by writing its name and brackets:
greet("Ada").
Funções que apenas fazem algo
- Uma função pode fazer algo (como imprimir) em vez de retornar um valor.
- Chame-a escrevendo seu nome e colchetes:
greet("Ada").
function greet(name) {
console.log("Hi, " + name); // → Hi, Ada
}
greet("Ada");
Call and return · Chamar e retornar
Each call runs the body with its own input, then return hands a value back. · Cada chamada executa o corpo com sua própria entrada, então return devolve um valor.
Watch out
- The names in the brackets (
n,name) are parameters — they only exist inside the function. - A function with no
returngives backundefined. Addreturnwhen you want an answer out.
Atenção
- Os nomes entre colchetes (
n,name) são parâmetros — eles existem apenas dentro da função. - Uma função sem
returnretornaundefined. Adicionereturnquando quiser uma resposta de volta.
Common mistakes
returngives back a value; without it a function returnsundefined.- Call the function with
().
Erros comuns
returndevolve um valor; sem ela, uma função retornaundefined.- Chame a função com
().
Now you try
- Write each function — it is called for you in the check.
- Press Check answer to test it.
Agora você tenta
- Escreva cada função — ela será chamada por você no verificador.
- Pressione Check answer para testá-lo.
Write a function double(n) that returns · decrescentes n times 2. · Escreva uma função double(n) que retorna n vezes 2.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Write a function add(a, b) that returns a + b. · Escreva uma função add(a, b) que retorne a + b.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Write a function greet(name) that logs Hi, then the name, then call greet("Ada"). Output should be Hi, Ada. · Escreva uma função greet(name) que faça log de Hi, depois o nome, depois chame greet("Ada"). A saída deve ser Hi, Ada.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.