Welcome back to CodeYourCraft! Today, we're diving into the world of advanced JavaScript functions. If you're new to functions, don't worry! We'll start from the basics and work our way up. Let's get started!
A function is a reusable block of code that performs a specific task. Functions help to keep our code organized, readable, and maintainable.
function greet(name) {
console.log(`Hello, ${name}!`);
}In the example above, we've created a function called greet that takes a parameter name and logs a greeting message.
There are two ways to create functions in JavaScript:
function greet(name) {
console.log(`Hello, ${name}!`);
}const greet = function(name) {
console.log(`Hello, ${name}!`);
}Introduced in ES6, arrow functions offer a more concise syntax for function expressions.
const greet = (name) => {
console.log(`Hello, ${name}!`);
}Functions can take any number of arguments, which we define within the parentheses. However, you should always be mindful of the number and types of parameters you're using.
function greet(name, greeting) {
console.log(`${greeting}, ${name}!`);
}
greet('John', 'Good Morning');If a function call omits a parameter, we can provide a default value using the assignment operator (=).
function greet(name = 'Guest', greeting = 'Hello') {
console.log(`${greeting}, ${name}!`);
}
greet(); // "Hello, Guest!"
greet('Alice'); // "Hello, Alice!"Using the ... (spread operator) syntax, we can collect an indefinite number of arguments as an array.
function greetAll(...names) {
names.forEach(name => console.log(`Hello, ${name}!`));
}
greetAll('John', 'Alice', 'Bob');
// "Hello, John!"
// "Hello, Alice!"
// "Hello, Bob!"A function can return a value using the return keyword. The returned value can be used in our code.
function addNumbers(a, b) {
return a + b;
}
const sum = addNumbers(3, 5);
console.log(sum); // 8By returning early, we can make our functions more efficient and easier to read.
function findMin(numbers) {
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] < numbers[0]) {
[numbers[0], numbers[i]] = [numbers[i], numbers[0]];
}
if (numbers[i] === numbers[0]) {
return `There are multiple minimum values: ${numbers[i]}`;
}
}
return numbers[0];
}
console.log(findMin([3, 5, 2, 1, 7])); // 1A recursive function is a function that calls itself. They are useful for solving problems involving repeated subproblems.
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120What is the purpose of a function in JavaScript?
What is the difference between a function declaration and a function expression?