Programming / Basics / Functions
Function
-
1. What are Functions
Functions in Programming is a block of code that encapsulates a specific task or related group of tasks.
Functions are defined by a name, may have parameters and may return a value.
The main idea behind functions is to take a large program, break it into smaller, more manageable pieces (or functions), each of which accomplishes a specific task.
-
Functions Declaration & Usage
A function declaration tells the compiler about a function’s name, return type, and parameters.
1. declaration
2. function call// Function declaration function sum(a, b, c) { return a + b + c; } sum(5, 6, 7); -
3. Importance of Functions
eg:
find area of defferent shapes
//find area of Circle var area = π × r2; //find area of Triangle var area = ½ × b × h //find area of Square var area = a2 //find area of Rectangle var area = l × w //find area of Parallelogram var area = b × h //find area of Ellipse var area = πab //find area of Circle2 var area = π × r2; //find area of Circle3 var area = π × r2; the above code is rewritten using function
1. Modularity of code:function circle(){ var area = π × r2; } function triangle(){ var area = ½ × b × h } circle() circle() circle() triangle() Functions in Programming help break down a program into smaller, manageable modules. Each function can be developed, tested, and debugged independently, making the overall program more organized and easier to understand.
2. Abstraction:Functions in Programming allow programmers to abstract the details of a particular operation. Instead of dealing with the entire implementation, a programmer can use a function with a clear interface, relying on its functionality without needing to understand the internal complexities.
3. Code Reusability:Functions in Programming enable the reuse of code by encapsulating a specific functionality. Once a function is defined, it can be called multiple times from different parts of the program, reducing redundancy and promoting efficient code maintenance. Functions can be called multiple times, reducing code duplication.
4. Code is easily maintainable5. Testing and debugging