Welcome ðŸŽ‰

logo

ReactLMS

Search
Light Mode
Contact Us

4 min to read

Contact us

No results for your search.
Sorry, an unexpected error occurred

Concept


Function is an important and powerful concept. Functions allow us to reuse code, create independent blocks of code, and perform specific tasks.


How to create and use a Function


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.


Anonymous Function


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.


Example with Code


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!"









Read more
On This Page