java script functions and how to utilize them

What is a JavaScript Function?
A JavaScript function is a block of code designed to perform a specific task. You can reuse this code whenever needed by simply calling the function
Example; function sayHello() {
alert("Hello!"); }
How to Declare a Function in JavaScript.
There are 3 main ways to declare a function in JavaScript.
1.Function declaration
function greet() {
console.log("Hello!"); }
then to call the function again, you call it like this
greet(); Output: Hello!
2. Function expression;
This function is stored inside a variable. Its useful when passing functions around or using them inside other functions
const greet = function() {
console.log("Hello!"); }; then to express the function expression, you call it like this
greet(); Output: Hello!
3. Arrow functions;
const greet = () => {
console.log("Hello!");
}; to call this expression you use
greet(); Output: Hello!
WE HAVE JAVASCRIPT FUNCTION WITH PARAMETERS
Function with parameters;
function greet(klaus) {
console.log("Hello, " + name + "!");
} greet("Klaus"); Output: Hello, Klaus!
WE HAVE JAVASCRIPT FUNCTIONS THAT RETURNS A VALUE
Functions that returns a value;
function add(a, b) {
return a + b; }
let sum = add(5, 3);
console.log(sum);Output: 8
FUNCTIONS AND ARGUMENTS
function greet(name) { ~ name is a parameter
console.log("Hi " + name);
} greet("Ada"); ~ "Ada" is an argument
Parameters: Variables you set in the function
Arguments: Actual values you pass when calling the function
RETURN AND NO RETURN FUNCTIONS:
- If a function uses return, it gives you a value back
function multiply(x, y) {
return x * y; } let result = multiply(3, 4); // result is 12
- If it doesn’t return, it just does something (like show a message) like this;
function greet() {
alert("Hello!"); }
Why Are Functions Useful?
1.Reusability – Write code once and reuse it.
2.Cleaner Code – Functions help break down complex code into smaller, readable parts.
3.Debugging is Easier – You can test individual functions to find bugs.
4.Organization – Makes code organized and modular.
Thank you for reading, see you next time.. Adios!
Subscribe to my newsletter
Read articles from Edeh Paul directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
