Functions in JavaScript
A function in JavaScript is a block of reusable code that performs a specific task. Functions are used to avoid repetition and to structure code in a more organized way. Functions can be called whenever needed, and they can accept parameters and return a value.
Types of Functions in JavaScript:
- Function Declaration: A function that is declared with the
function
keyword. - Function Expression: A function that is defined inside an expression, often assigned to a variable.
- Arrow Functions: A more concise syntax for writing functions, introduced in ES6.
Syntax of Functions:
Function Declaration Syntax
function myFunction() {
console.log("Hello, World!");
}
Example of Function Declaration in JavaScript:
This example demonstrates a simple function declaration that prints "Hello, World!" when called.
Example
function myFunction() {
console.log("Hello, World!");
}
myFunction();
Output
Hello, World!
Function Expression Syntax:
Function Expression Syntax
const myFunction = function() {
console.log("Function Expression Example");
};
Example of Function Expression in JavaScript:
This example demonstrates a function expression where the function is assigned to a variable and called.
Example
const myFunction = function() {
console.log("Function Expression Example");
};
myFunction();
Output
Function Expression Example
Arrow Function Syntax:
Arrow Function Syntax
const myFunction = () => {
console.log("Arrow Function Example");
};
Example of Arrow Function in JavaScript:
This example demonstrates an arrow function that prints a message.
Example
const myFunction = () => {
console.log("Arrow Function Example");
};
myFunction();
Output
Arrow Function Example
Key Points on Functions:
- Function Declaration: A function defined with the
function
keyword and can be called anywhere in the code after the declaration. - Function Expression: A function defined inside an expression and can be assigned to a variable.
- Arrow Functions: A more concise syntax for writing functions, making the code more readable and avoiding issues with the
this
keyword. - Return Statement: A function can return a value, which can be used elsewhere in the program.
- Parameters: Functions can accept parameters (arguments) that are used within the function to perform tasks.
- Function Scope: Variables inside a function are typically scoped to that function unless declared globally.