𝗝𝗮𝘃𝗮𝘀𝗰𝗿𝗶𝗽𝘁 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀

Functions are blocks of code that perform specific tasks. They help you organize your code and prevent repetition. This follows the DRY principle: Do Not Repeat Yourself.

Key concepts to know:

• Parameters vs Arguments Parameters are placeholders in the function definition. Arguments are the real values you pass during the call. Example: function greet(name) { ... } Here, name is the parameter. greet("Karthika"); Here, "Karthika" is the argument.

• Default Parameters You can set a fallback value if no argument is provided. Example: function greet(name = "Guest") { ... }

• Return Statement The return statement sends a result back to you. Once a function hits a return, it stops running. You can store this result in a variable.

Common Types of Functions:

  • Named Functions: Functions with a specific name.
  • Anonymous Functions: Functions without a name.
  • Function Expressions: Functions assigned to a variable.
  • Arrow Functions: A shorter way to write functions using the => syntax.
  • IIFE: Functions that run immediately after they are defined. This keeps your variables out of the global scope.
  • Callback Functions: Functions passed as arguments to other functions. These are vital for handling asynchronous tasks like timers or event listeners.

Example of a Callback: setTimeout(function() { console.log("End"); }, 3000);

The code keeps running while the timer waits in the background.

Source: https://dev.to/karthika_jasinska_443e83f/javascript-functions-4gng