While learning JavaScript, one topic that I found really important was functions.
A function is basically a block of code that we can write once and use whenever we need it.
For example:
function greet() {
console.log("Hello!");
}
We can run the function by calling it:
greet();
Functions with Parameters
Sometimes we want to give some information to a function. That's where parameters come in.
function greet(name) {
console.log("Hello " + name);
}
Now we can pass different names when calling the function.
Return
A function can also give a value back using return.
function add(a, b) {
return a + b;
}
We can then store the result in a variable and use it wherever we need.
Why are functions useful?
Without functions, we might end up writing the same code again and again.
Functions help us:
- Reuse code
- Keep code organized
- Avoid repetition
- Make programs easier to understand
The main thing I learned is that functions are not just about writing code in a different format. They help us break a bigger problem into smaller, reusable pieces.
Top comments (0)