Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Funzioni | Section
Basi di JavaScript

bookFunzioni

Scorri per mostrare il 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
copy

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.

1234567
function 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
copy

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.

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 1. Capitolo 9

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 1. Capitolo 9
some-alt