JavaScript is a high-level, interpreted programming language primarily used for creating interactive and dynamic content on webpages. It was initially developed by Netscape Communications Corporation in collaboration with Sun Microsystems in 1995. JavaScript is now one of the core technologies of web development along with HTML and CSS.
Functions are fundamental building blocks in JavaScript, and enable us to write modular, reusable code and are a key aspect of JavaScript's flexibility and power.
In JavaScript, a function is a block of reusable code that performs a specific task. Functions allow us to encapsulate logic, organize code into smaller, manageable units, and promote reusability.
1. Function Declaration:
- We can declare a function using the `function` keyword followed by the function name, parameters (if any), and the function body enclosed in curly braces `{}`.
Example:
function greet(name) {
console.log("Hello, " + name + "!");
}
2. Function Expression:
- We can also define a function using a function expression, which involves assigning a function to a variable.
Example:
const greet = function(name) {
console.log("Hello, " + name + "!");
};
3. Arrow Function:
- Arrow functions are a concise way of defining functions, introduced in ES6.
- They provide a shorter syntax compared to traditional function expressions.
Example:
const greet = (name) => {
console.log("Hello, " + name + "!");
};
4. Function Parameters:
- Parameters are variables that we define in the function declaration, and their values are provided when the function is called.
- Functions can have zero or more parameters.
Example:
function add(a, b) {
return a + b;
}
5. Return Statement:
- Functions can optionally return a value using the `return` statement.
- The `return` statement terminates the function execution and specifies the value to be returned to the caller.
Example:
function add(a, b) {
return a + b;
}
6. Function Invocation:
- Functions are invoked (called) using their name followed by parentheses `()`.
- When a function is invoked, the code inside the function body is executed.
Example:
greet("John"); // Output: Hello, John!
7. Function Scope:
- Variables declared inside a function are scoped to that function and are not accessible outside of it.
- This concept is known as function scope.
Example:
function sayHello() {
let message = "Hello!";
console.log(message);
}
sayHello(); // Output: Hello!
console.log(message); // Error: message is not defined