JavaScript Functions
Table of contents
No headings in the article.
Functions are a crucial component of JavaScript. They let you to package up code so that you may reuse it across your program. We'll look at some of the most typical uses for JavaScript functions in this post.
Functions Creation
In JavaScript, you use the function keyword, the function's name, and a pair of parentheses to construct a function. Curly braces encapsulate the function's main body. Here's an illustration:
javascriptCopy codefunction greet(name) {
console.log(`Hello, ${name}!`);
}
In this example, we're creating a function called greet
that takes a single argument, name
. When the function is called, it logs a greeting to the console.
Calling Functions
To call a function in JavaScript, you simply use the name of the function followed by a set of parentheses. Here's an example:
javascriptCopy codegreet("John"); // logs "Hello, John!"
In this example, we're calling the greet
function with the argument "John"
. This logs the message "Hello, John!" to the console.
Returning Values
Functions can also return values. To return a value from a function, you use the return
keyword. Here's an example:
javascriptCopy codefunction add(a, b) {
return a + b;
}
let result = add(2, 3);
console.log(result); // logs 5
In this example, we're creating a function called add
that takes two arguments, a
and b
. The function returns the sum of a
and b
. We then call the function with the arguments 2
and 3
, and store the result in a variable called result
. We then log the value of result
to the console.
Function Expressions
In JavaScript, functions can also be defined as expressions. Here's an example:
javascriptCopy codeconst greet = function(name) {
console.log(`Hello, ${name}!`);
}
greet("John"); // logs "Hello, John!"
In this example, we're defining a function expression and assigning it to a constant variable called greet
. We then call the function with the argument "John"
, which logs the message "Hello, John!" to the console.
Conclusion
With the help of JavaScript functions, you may encapsulate code and reuse it across your whole application. You should now have a strong basis to start building your own functions and advance your programming abilities thanks to the fundamental ideas discussed in this tutorial.