DEV Community

Cover image for Functions in JavaScript
Mohammad Moiz Ali
Mohammad Moiz Ali

Posted on • Edited on • Originally published at makstyle119.Medium

Functions in JavaScript

Functions are a fundamental building block in JavaScript that allow you to encapsulate code and reuse it throughout your program. In this blog post, we'll explore functions in JavaScript, including their syntax, parameters, and return values.

Syntax of Functions in JavaScript:

In JavaScript, functions are declared using the function keyword, followed by the function name, a set of parentheses, and a set of curly braces. Here's an example of a simple function that logs a message to the console:

In this code, we declare a function called myFunction that logs the message "Hello, world!" to the console when it is called. To call the function, we simply use its name followed by a set of parentheses:

Parameters in Functions:

Functions can also accept input values called parameters, which allow you to pass data into the function when it is called. Parameters are declared inside the parentheses when the function is declared. Here's an example of a function that takes two parameters and logs their sum to the console:

In this code, we declare a function called addNumbers that takes two parameters: num1 and num2. When the function is called, it logs the sum of num1 and num2 to the console. To call the function with specific values for the parameters, we pass them in as arguments inside the parentheses:

Return Values in Functions:

Functions can also return values back to the calling code using the return keyword. Here's an example of a function that takes two parameters and returns their sum:

In this code, we declare a function called addNumbers that takes two parameters: num1 and num2. When the function is called, it returns the sum of num1 and num2 using the return keyword. To use the return value, we assign the function call to a variable:

Conclusion:

Functions are a powerful tool in JavaScript that allow you to encapsulate code and reuse it throughout your program. In JavaScript, functions are declared using the function keyword, followed by the function name, a set of parentheses, and a set of curly braces. Functions can also accept input values called parameters, and return values using the return keyword. By understanding how to use functions in JavaScript, you can write more efficient and maintainable code.

Top comments (4)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

I think your post might be more readable if you were to highlight fewer words.

Collapse
 
jareechang profile image
Jerry

It seems fine to me 😂🤣

Collapse
 
makstyle119 profile image
Mohammad Moiz Ali

us bro us 😂😂

Collapse
 
makstyle119 profile image
Mohammad Moiz Ali

can you explain a litter bit more 😅