Sitemap
Govinda shrestha

Govinda shrestha

Computer Engineer

Function in JavaScript

2 min readSep 25, 2024

--

In JavaScript, a function is a block of reusable code that can be defined once and invoked whenever necessary. This helps reduce redundancy and makes the code more modular and maintainable.

Basic Function Example

Let’s start with a simple function:

function car()
{
console.log("The car is red in color");
console.log("The car has four wheel");
conole.log("The car brand is mercedes");
}

To use this function, simply call it like this:

car();

When invoked, the function outputs:

The car is red in color.
The car has four wheels.
The car brand is Mercedes.

Enhancing the Function with Parameters

Get Govinda shrestha’s stories in your inbox

Join Medium for free to get updates from this writer.

A more flexible approach is to pass parameters to the function, which allows you to customize the output each time the function is called. Here’s an updated version of the car function that accepts two parameters: carColor and carBrand.

function car(carColor, carBrand) {
console.log(` Car is ${carColor} in color .`);
console.log("car has four wheel.");
console.log(`car brand is ${carBrand}`);
}

Now, you can call the function with different values:

car("Red", "Mercedes");
car("Blue", "BMW");

This will output:

The car is Red in color.
The car has four wheels.
The car brand is Mercedes.

The car is Blue in color.
The car has four wheels.
The car brand is BMW.

By adding parameters to the function, we’ve made it reusable in a wider range of situations. Instead of writing new code every time, we can simply call the function with different arguments to get varied outputs.

Why Use Functions?

  • Reusability: Define once, use multiple times.
  • Modularity: Break your code into smaller, manageable parts.
  • Maintainability: Update the function in one place and reflect changes everywhere it’s used.
  • Abstraction: Functions can hide complex logic, making code easier to understand and work with.

Conclusion

Functions are an essential feature in JavaScript that allows developers to write clean, reusable, and organized code. Whether you’re working on small scripts or large applications, functions can help make your code more efficient and easier to maintain.

--

--