JavaScript · JavaScript Beginner

JavaScript Functions

Run this in the Online JavaScript editor

Hello, emerging JavaScript developers!

We now reach a crucial element of programming as we continue our journey: functions. By encapsulating a piece of code that completes a certain purpose in a JavaScript function, we may make our code more modular, reusable, and readable.

Understanding Functions in JavaScript

Functions can be visualized as mini-programs within our main program. They are defined once and can be called multiple times, sometimes with different inputs. Here's the basic structure of a function:

function functionName(parameters) {
  // body of the function
  return returnValue;
}
  • function: A keyword that tells JavaScript you're defining a function.
  • functionName: The name you give to your function, allowing you to call it later by this name.
  • parameters: Values you pass into the function. They are optional.
  • return: This keyword allows the function to send a value back to where it was called. The return statement is also optional.

Defining and Calling Functions

To create a function that adds two numbers:

function addNumbers(a, b) {
  return a + b;
}

To call this function:

let sum = addNumbers(5, 3);
console.log(sum); // Outputs: 8

Exercise

Craft a function following these quick steps:

  • Function Name: calculateArea
  • Parameters:length: Length of the rectangle.width: Width of the rectangle.
  • Function Body: Return the product of length and width.
  • Testing: Invoke the function with different length and width values and log the results.

This exercise will help you practice defining and using functions in JavaScript.

Conclusion

Congratulations on finishing this crucial functions module! You are now equipped with the power of functions to develop more logical, effective, and modular code. We'll be building more on these fundamental abilities as we go along.

Keep coding and stay curious!

This website uses cookies to ensure you get the best experience on our website.