Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Fonctions | Section
Bases de JavaScript

bookFonctions

Glissez pour afficher le 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.

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 1. Chapitre 9

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Section 1. Chapitre 9
some-alt