About Lesson
JavaScript Functions
-
Reusable Blocks of Code: Functions are reusable blocks of code that perform a specific task.
-
Defining a Function:
JavaScriptfunction myFunction(parameter1, parameter2) { // Code to be executed return result; }
-
Parameters and Arguments:
- Parameters: Placeholders for values that are passed into the function when it’s called.
- Arguments: The actual values that are passed to the function when it’s invoked.
-
Calling a Function:
JavaScriptconst result = myFunction(argument1, argument2);
-
Return Statement:
- The
return
statement specifies the value that the function should output. - If no
return
statement is used, the function will returnundefined
.
- The
-
Function Types:
- Named Functions: Defined using the
function
keyword (as shown above). - Anonymous Functions: Functions without a name, often used as callback functions.
- Arrow Functions: A concise syntax for writing functions:
const myArrowFunction = (param1, param2) => { ... }
- Named Functions: Defined using the
-
Examples:
-
Simple Function:
JavaScriptfunction greet(name) { return "Hello, " + name + "!"; } const greeting = greet("John");
-
Function with Multiple Parameters:
JavaScriptfunction add(a, b) { return a + b; } const sum = add(5, 3);
-
-
Importance:
- Reusability: Avoid code duplication by defining functions for commonly used tasks.
- Modularity: Break down complex problems into smaller, more manageable functions.
- Readability: Improve code readability and maintainability by using meaningful function names.
Functions are essential building blocks in JavaScript, enabling you to write organized, efficient, and reusable code.