๐๐ฎ๐๐ฎ๐ฆ๐ฐ๐ฟ๐ถ๐ฝ๐ ๐๐๐ป๐ฐ๐๐ถ๐ผ๐ป๐ ๐๐ ๐ฝ๐น๐ฎ๐ถ๐ป๐ฒ๐ฑ
Functions are reusable blocks of code. They perform specific tasks. Think of a function as a machine. You provide input. The machine processes it. It gives you an output.
Functions stop you from writing the same code over and over. If you need to print a message 100 times, you write one function instead of 100 lines of code.
Benefits of functions:
- Less code
- Easier to read
- Simple maintenance
- Better reusability
Naming your functions matters. Use names that describe the action.
- Use: calculateSalary() or getUserData()
- Avoid: a() or xyz()
Rules for names:
- Use letters and numbers
- Do not start with a number
- Use underscores or dollar signs
- Do not use hyphens
Key parts of a function:
- Keyword: function
- Name: add
- Parameters: Placeholders for your inputs
- Body: The logic inside the curly braces
- Invocation: Calling the function to make it run
Do not confuse parameters with arguments. Parameters are the placeholders. Arguments are the actual values you pass in.
Return vs Console.log: Many beginners mix these up.
- console.log prints a value to the screen. You cannot use that value later.
- return sends a value back to your code. You can store it in a variable or use it in another calculation.
Professional developers use return to keep code flexible.
Three ways to write functions:
- Function Declaration: function add(a, b) { return a + b; }
- Function Expression: const add = function(a, b) { return a + b; };
- Arrow Functions: const add = (a, b) => a + b;
Arrow functions are standard in modern frameworks like React.
Commonly used methods:
- Math: Math.max(), Math.random(), Math.floor()
- Strings: toUpperCase(), trim(), includes()
- Arrays: push(), pop(), map(), filter()
- Timers: setTimeout(), setInterval()
Break your large applications into small, manageable functions. It makes testing and fixing bugs much easier.
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