#5 Javascript Functions | Javascript Hindi Course For Beginners ( 2023 )

A function in programming is a reusable piece of code that performs a specific task when called or invoked. Think of it as a mini-program within a program that can be executed as many times as needed, without having to write the code over and over again. Functions take inputs, perform actions, and return a result. They help to make your code more organised, readable, and maintainable.
 
Why we should use functions ?
  1. Reusability: Functions can be called multiple times in a program, reducing the need to write similar code multiple times.
  1. Modularity: Functions provide a way to divide a large and complex program into smaller, more manageable parts, making the code easier to understand, debug, and maintain.
  1. Abstraction: Functions can be used to hide the implementation details of a task from the rest of the program, allowing for a higher level of abstraction and making it easier to change the implementation without affecting the rest of the program.
  1. Readability: Functions provide a clear and concise way to describe what a section of code does, making the code more readable and easier to understand.
  1. Debugging: Functions can be individually tested and debugged, making it easier to identify and fix problems in your code.
  1. Improved Performance: Functions can be optimised for speed and efficiency, leading to improved performance of the overall program.
  1. Code Reuse: Functions can be easily reused across different projects and programs, reducing the amount of time and effort needed to write new code.
 
The syntax of a function in JavaScript
  • function: The function keyword is used to declare a function.
  • functionName: This is the name of the function, which can be any valid JavaScript identifier.
  • parameter1, parameter2, ...: These are optional parameters that can be passed to the function. When the function is called, the values passed as arguments are assigned to these parameters.
  • {}: The curly braces define the body of the function, which contains the statements to be executed when the function is called.
  • return: The return statement is used to return a value from the function. The function execution stops when a return statement is executed.
Here's an example of a simple function in JavaScript that takes two parameters and returns their sum:
 
Default Parameters
Variable Scrope
Anonymous function
Callback function
IIFE ( Immediately invoked function expression)
Arrow Function → ES6 new function Syntax
 
Question: