Functions
In programming, a Function is a block of code that performs a specific task and optionally returns a result. Functions allow you to organize your code into reusable units, making it easier to read, understand, and maintain.
To define a Function, you need to specify its name, input parameters (if any), and the task it performs. To use a Function, you need to call it and pass any required input parameters. The function will then execute the task it was designed to perform and return a result. Like a dog that does the same trick only when asked.
Functions can also have default values for their input parameters. This means that if you don’t pass a value for that parameter when calling the Function, it will use the default value instead. It also gives us a way to structure larger programs, to reduce repetition, to associate names with subprograms, and to isolate these subprograms from each other.
Functions can be defined and called within other functions, allowing you to build more complex programs by combining smaller, reusable units of code. It is a fundamental concept in programming and are used in almost all programming languages. They help you write more efficient and organized code, making it easier to build and maintain complex programs.
You can function using the ‘function’ keyword followed by the function name , input parameters (if any), and the task it performs.
This function is called sumofNumbers and it takes two input parameters: a and b . The function calculates the sum of Numbers by Adding a and b , and then it returns the result using the return statement.
Different ways for writing a function
- Function declaration
Here we declare it using the keyword “function”. Then we write the function name and then parameters.
2. Function Expression
Get Aimanfatimaahmed’s stories in your inbox
Join Medium for free to get updates from this writer.
Here we define a function using a variable and store the returned value in that variable.
3. Fat Arrow Function
Here we do not use the “function” keyword and use the arrow symbol.
There are several advantages to using functions in JavaScript:
- Code reuse: Functions allow you to reuse code blocks, making it easier to write and maintain complex programs.
- Improved readability: Functions help you organize your code into smaller, more manageable units, making it easier to read and understand.
- Better separation of concerns: Functions allow you to divide your code into logical units that perform specific tasks, improving the separation of concerns in your code.
- Modularity: Functions can be defined and called within otherunctions, allowing you to build more complex programs by combining smaller, reusable units of code.
- Testing and debugging: Functions make it easier to test and debug your code, as you can isolate specific sections of your code and test them independently.
Overall, using functions in JavaScript can help you write more efficient, organized, and maintainable code.






