Function is an important and powerful concept. Functions allow us to reuse code, create independent blocks of code, and perform specific tasks.
To create a function in JavaScript, we use the keyword 'function', followed by the name of the function and a list of parameters (if any).
function tenFunction(thamSo1, thamSo2) {
// Mã lệnh của function
}
To use a function in JavaScript, we need to call it by name and pass arguments (if any) in parentheses.
Here is an example of creating and using a function:
function calculateSum(a, b) {
let sum = a + b;
return sum;
}
let result = calculateSum(5, 3);
console.log(result); // Kết quả: 8
In the example above, we created a function called calculateSum and two parameters a and b. This function calculates the sum of two numbers and returns the result. Then, we call this function, and it returns the sum result and stores it in the variable result, and prints the value of result.
In JavaScript, we can also create anonymous functions, which means functions without a name.
Anonymous functions are often used when we only need to use a function once or as a parameter of another function.
let tenBien = function(thamSo1, thamSo2, ...) {
// Mã lệnh của hà m
};
Here is an example of using an anonymous function:
let greet = function(name) {
console.log("Xin chà o, " + name + "!");
};
greet("John"); // Kết quả: "Xin chà o, John!"
In the above example, we created an anonymous function and assigned it to the variable 'greet'. This function will print a welcome message with the name passed in.
Here are some examples of using and creating functions in JavaScript:
// SỠdụng function
function greet(name) {
console.log("Xin chà o, " + name + "!");
}
greet("John"); // Kết quả: "Xin chà o, John!"
// Tạo function
function calculateSum(a, b) {
let sum = a + b;
return sum;
}
let result = calculateSum(5, 3);
console.log(result); // Kết quả: 8
// SỠdụng hà m vô danh
let greet = function(name) {
console.log("Xin chà o, " + name + "!");
};
greet("John"); // Kết quả: "Xin chà o, John!"