Funções
Deslize para mostrar o menu
Functions help you organize and reuse code in JavaScript. A function is a named block of code that performs a specific task. You can define a function once, and then run (or "call") it as many times as you need.
There are two main ways to create functions: function declarations and function expressions.
A function declaration uses the function keyword followed by the function name, a set of parentheses for parameters, and a block of code inside curly braces.
A function expression assigns a function to a variable, often using the const or let keyword. Both approaches let you encapsulate logic and keep your code DRY (Don’t Repeat Yourself).
123456789101112// Function Declaration function add(a, b) { return a + b; } // Function Expression const multiply = function(a, b) { return a * b; }; console.log(add(3, 4)); // Output: 7 console.log(multiply(3, 4)); // Output: 12
Scope
Understanding function scope is important for writing reliable code. Variables declared inside a function are only accessible within that function. This is called local scope.
This helps prevent naming conflicts and keeps your logic organized.
1234567function greet(name) { const message = "Hello, " + name + "!"; return message; } console.log(greet("Sam")); // Output: Hello, Sam! // console.log(message); // This would cause an error: message is not defined
As a best practice, use functions to break your code into small, focused pieces that each do one thing well. Give your functions clear, descriptive names, and avoid relying on variables from outside the function unless absolutely necessary. This makes your code easier to read, test, and maintain.
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo