๐ ๐ผ๐ฟ๐ฒ ๐๐ฏ๐ผ๐๐ ๐๐ฆ ๐๐๐ป๐ฐ๐๐ถ๐ผ๐ป๐
Functions stop code duplication.
If you add numbers repeatedly without functions, you write the same logic over and over. This makes code hard to read and hard to fix.
Using a function allows you to write the logic once and use it many times.
Functions help with:
- Reusability
- Readability
- Maintainability
- Modularity
Naming Rules Do not use spaces in names. Use camelCase. The first word starts with lowercase. Every other word starts with uppercase.
Good names:
- calculateTotal()
- findMaximum()
- printDetails()
Bad names:
- abc()
- xyz()
- temp()
Parameters vs Arguments This is a common interview topic.
Parameters are variables in the function definition. They receive values. Example: function add(a, b)
Arguments are the actual values you pass when you call the function. They supply values. Example: add(10, 20)
Default Parameters You can set a fallback value. Example: function greet(name = "Guest")
If you call greet() without a name, it uses "Guest".
The Return Statement Use return when you need to use the result elsewhere. Use return to store a value in a variable. Use return to send data to another function.
If you do not use return, your function returns undefined.
Important Rules:
- Once a return runs, the function stops.
- You can use multiple return statements in if/else blocks.
- Only one return executes.
- To return multiple values, return an array or an object.
Hoisting JavaScript moves function declarations to the top of your code before execution. This means you can call a function before you write it in your file.
Passing Values JavaScript passes values, not the variables themselves. If you change a parameter inside a function, the original variable outside stays the same.
Source: https://dev.to/annapoo/more-about-function-in-js-5b19