Javascript Creating and Using Functions

Functions in JavaScript are considered one of the core building blocks of JavaScript. Functions allow you to group reusable code into a single named unit that can be called whenever needed by its name. We will learn in this lesson about creating and using functions, the difference between function declaration and function expression, and how to work with arguments and return values.

What Are Functions

Functions in JavaScript are blocks of code designed and created to perform particular and specific tasks. Functions help make your code more readable, maintainable, and reusable, which can save your time. Instead of writing the same code multiple times, you can create a function and call it whenever needed by its name.

Function Declaration vs. Function Expression

There are two main ways to define functions in JavaScript: function declarations and function expressions. So let’s understand them in detail.

1. Function Declaration

A function declaration creates a function with a specific name. As follows:

javascript
          function greet() {
    console.log("Hello, World!");
}
        

Here we create a function named greet. To execute the function, you simply call it by its name followed by parentheses like that:

javascript
          greet(); // Output: Hello, World!
        

Features of Function Declarations Way:

  • The function has a name, which we can execute the function with.
  • Hoisting (using the function even though we did not create it) allows it to be called before its definition. For example:
javascript
          sayHi(); // Output: Hi there!

function sayHi() {
    console.log("Hi there!");
}
        

2. Function Expression

A function expression way defines a function and assigns it to a variable. Here’s an example:

javascript
          const greet = function () {
    console.log("Hello, World!");
};
        

Now we can call the function using the variable name:

javascript
          greet(); // Output: Hello, World!
        

Features of Function Expressions Way:

  • Functions can be anonymous (no name) or named (two options are allowed).
  • Unlike declarations, they are not hoisted. You must define the function, then you can call it:
javascript
          sayHi(); // Error: Cannot access 'sayHi' before initialization

const sayHi = function () {
    console.log("Hi there!");
};
        

Passing Arguments to Functions

Functions in JavaScript can take inputs called arguments. These are the values you pass into a function when calling it (we can imagine it like variables specific to its function only).

Example of Using Arguments

javascript
          function greetUser(name) {
    console.log(`Hello, ${name}!`);
}

greetUser("Khaled"); // Output: Hello, Khaled!
greetUser("Waleed");   // Output: Hello, Waleed!
        

Using Multiple Arguments

Functions can accept multiple arguments, separated by commas. Look to this example:

javascript
          function add(a, b) {
    console.log(a + b);
}
add(3, 2); // Output: 5
        

This function works on adding number a and number b, which are their arguments. So when we give it 3 and 2 as arguments, the function returns 3 + 2, which is equal to 5.

Returning Values from Functions

Functions can also send back (or return) a value to the caller using the return keyword.

javascript
          function square(num) {
    return num * num;
}
const result = square(2); // Save the returned value (4) to 'result' variable
console.log(result); // Output: 4
        

Now, you might be confused between logging the result console.log and the return keyword way, So the main difference between console.log and return keywords is that:

  • console.log prints information to the console but does not return a value.
  • return sends a value back to where the function was called (whereever you called your function).

Here’s a clear example of the difference:

javascript
          function multiply(a, b) {
    return a * b;
}



console.log(multiply(2, 3)); // Logged Output: 6

let result = multiply(2, 3); // Save Result To The Variable
console.log("The Output Is: " + result) // Use Returned Value
        

Take care when logging a function not to be confused with parentheses.

So, functions returned values can be assigned to variables or used directly in other operations.

So this is an additional example using the return keyword:

javascript
          function calculateArea(length, width) {
    return length * width;
}

const area = calculateArea(5, 10);
console.log(`The area is ${area}`); // Output: The area is 50
        

Practical Example

Look to this practical example, which is combining everything we’ve learned:

javascript
          // Function Declaration
function calculateSum(a, b) {
    return a + b;
}

// Function Expression
const calculateProduct = function (a, b) {
    return a * b;
};

// Using the functions
const sum = calculateSum(10, 20);
const product = calculateProduct(10, 20);

console.log(`The sum is: ${sum}`); // Output: The sum is: 30
console.log(`The product is: ${product}`); // Output: The product is: 200
        

Best Practices for Using Functions

  1. 1
    Name Functions Clearly: Use descriptive names that indicate the purpose of the function.
  2. 2
    Keep Functions Small: A function should perform one task. If it does more, consider splitting it into smaller functions.
  3. 3
    Avoid Side Effects: A function should not modify variables outside its scope unnecessarily to avoid errors.

Conclusion

In this lesson, you’ve learned how to:

  • Define functions using declarations and expressions and clear differences between them.
  • Pass arguments to functions to make them dynamic and flexable.
  • Use the return keyword to send values back from functions.

Mastering functions is a core step toward writing efficient and maintainable JavaScript code.

Practice these concepts to strengthen your understanding!