๐๐ฎ๐๐ฎ๐ฆ๐ฐ๐ฟ๐ถ๐ฝ๐ ๐๐๐ป๐ฐ๐๐ถ๐ผ๐ป๐ ๐๐ ๐ฝ๐น๐ฎ๐ถ๐ป๐ฒ๐ฑ
A function is a reusable block of code. It performs one specific task.
Think of a function as a machine.
- You provide input.
- The machine processes the input.
- The machine gives you an output.
Functions stop you from writing the same code repeatedly. If you need to show a message 100 times, you use one function instead of 100 lines of code.
Why you need functions:
- Less code to write.
- Better readability.
- Easier maintenance.
- High reusability.
Naming your functions matters. Use names that describe the action.
- Good: calculateSalary(), getUserData(), printInvoice()
- Bad: a(), xyz(), temp()
Rules for function names:
- Use letters and numbers.
- Do not start with a number.
- Use underscores (_) or dollar signs ($).
- Do not use hyphens (-).
Key Concepts:
- Parameters vs. Arguments
- Parameters are placeholders defined in the function.
- Arguments are the actual values you pass when you call the function. Example: In add(a, b), a and b are parameters. In add(10, 20), 10 and 20 are arguments.
Return Statement A function can work without a return statement. It just performs an action like logging to the console. The return keyword sends a value back to your code. This allows you to store the result in a variable or use it in another calculation. Professional developers use return to keep code flexible.
Types of Functions
- Function Declaration: The traditional way using the function keyword.
- Function Expression: Storing a function inside a variable.
- Arrow Functions: Modern syntax used in frameworks like React. It is shorter and cleaner.
Functions help you break large applications into small, manageable pieces. You can test each piece individually.
Commonly used methods to learn:
- Math: Math.max(), Math.random(), Math.floor()
- Strings: toUpperCase(), trim(), includes()
- Arrays: push(), pop(), map(), filter(), reduce()
- Timers: setTimeout(), setInterval()
Source: https://www.geeksforgeeks.org/javascript/functions-in-javascript/ Source: https://www.w3schools.com/js/js_functions.asp
Full post: https://dev.to/dev_saravanan_journey/javascript-functions-explained-1706