Functions
Hello HaWkers! Jeff Bruchado here.
This is another article in our series that will cover our journey to Learn Programming from Scratch.
Today will be another article about extremely important content to proceed with your learning.
Well, without further ado, let's get started!
Today, we're going to talk about one of the most important topics in Programming:
Functions.
Alright, now let's dive into the universe of Functions in JavaScript and understand why they're so fundamental.
Imagine you're creating a website, and there's a part that needs to calculate the tip based on the restaurant bill value. Are you going to repeat the same calculation every time someone enters a different value? Of course not, right?
That's where Functions come in!
Functions are like small robots in your code.
You tell them what to do once, and then you just call them to repeat that task as many times as you want.
They're mega important because:
Organization: Makes code cleaner and more organized. Instead of repeating the same code multiple times, you create a function and call it whenever needed.
Reuse: Once you write a function, you can use it anywhere in your project, or even in other projects.
Maintenance: If you need to change the logic, you just change it in the function. This way, the change applies everywhere the function is called.
Scalability: As your project grows, functions help deal with complexity, keeping things more manageable.
Think of Functions as mathematical formulas. You put in some values (parameters), the function processes these values (executes a code block) and, often, returns a result (function return).
For example, a function to calculate a tip could be something like:
function calculateTip(billValue) {
return billValue * 0.1;
}And every time you want to calculate the tip, you just call calculateTip(billValue) with the bill value as a parameter.
So, see how Functions are essential:
They reduce repetition, keep your code organized, and make changes and scalability easier.
Without them, programming would be a truly giant and confusing puzzle.
Functions transform complexity into simplicity!
Function Parameters
Basically, they're the arguments or parameters passed to a function when it's called.
For example, in the following function, a and b are the function parameters:
function sum(a, b) {
return a + b;
}You declare them inside the () in the function declaration.
And when you call, you pass the parameter values, inside the () of the call, in declaration order.
That is, when the function is called, the passed arguments are assigned to the corresponding parameters.
For example:
function sum(a, b) {
return a + b;
}
let result = sum(1, 2);
console.log(result); // 3Well, now you understood what function parameters are, but you might be wondering, what if I want to execute a function that has parameters, but I don't want to pass values for those parameters, I just want the default result, is there a way to do that?
And that's exactly what I'll explain to you now.
Default Parameters
Let's understand about Default Params, which are parameters that already have a predefined default value.
They're useful when we want a parameter to have a default value if the user doesn't pass a value for it.
In other words, this parameter becomes optional.
The syntax for defining a default parameter is as follows:
function greet(name = 'Jeff') {
console.log(`Hello, ${name}!`);
}In this example, if the user doesn't pass a value for the name parameter, the default value Jeff will be used.
Otherwise, the value passed by the user will be used.
For example:
greet(); // "Hello, Jeff!"
greet('Mary'); // "Hello, Mary!"Well, as you can see, they're quite useful for some specific situations, right?!
Rest Parameter (Rest Params)
It's a special syntax for passing an indeterminate number of arguments to a function.
And to do this, just define your function parameter with the following syntax:
(...parameterName), using the 3 dots (...), before declaring the name.
It's useful when we don't know how many arguments will be passed.
The syntax is as follows:
function sum(...numbers) {
let result = 0;
for (let number of numbers) {
result += number;
}
return result;
}In the example above, the numbers parameter is an array that will contain all the arguments passed to the function.
For example:
function sum(...numbers) {
let result = 0;
for (let number of numbers) {
result += number;
}
return result;
}
let result = sum(1, 2, 3, 4, 5);
console.log(result); // 15IIFEs (Immediately Invoked Function Expressions)
They're functions that are defined and called immediately.
They're commonly used to create local scopes and protect variables and functions from being accessed globally.
Example of an IIFE:
(function () {
// function code here
})();Generally IIFE is used when you're initializing your application, and need to make some request before it's created, like querying the user, and validating if they have permission to load the application.
Built-in Functions
They're predefined functions that you can use to perform common tasks in JavaScript, meaning you don't need to declare them.
These are examples of Built-in Functions:
- parseInt() to convert strings to integers,
- Math.max() to find the largest value in a list of numbers
- console.log() to print messages in the console.
Example of how to use the built-in function parseInt():
let myString = '123';
let myInt = parseInt(myString);
console.log(myInt); // 123Example of how to use the built-in function Math.max():
let numbers = [1, 2, 3, 4, 5];
let max = Math.max(...numbers);
console.log(max); // "5"
Scope and Function Stack (Call Stack)
I already talked about Scope in previous articles, and now I'll talk more in detail about it in relation to functions.
So don't be shy if you feel like you're repeating something you've already studied. (This is even better for retaining the content!)
Let's understand the concept of scope again:
Scope refers to how a variable is visible in different parts of your code.
In other words, scope determines the "visibility" of a variable.
There are two main types of scope in JavaScript:
- Block scope
- Function scope
Block scope is created by any type of control statement, like if and for, and limits the visibility of variables declared within the block to the block itself.
Function scope is created by a function and limits the visibility of variables declared within the function to that function and all functions nested within it.
Below is an example of code that demonstrates block scope:
if (true) {
const x = 5;
}
console.log(x); // Uncaught ReferenceError: x is not definedIn this example, the variable x is declared within the if block, so it's only visible within the block itself. Trying to access the variable outside the block results in an error.
Below is an example of code that demonstrates function scope:
function foo() {
const x = 5;
}
console.log(x); // Uncaught ReferenceError: x is not definedIn this example, the variable x is declared within the foo function, so it's only visible within the foo function and any function nested within it. Trying to access the variable outside the function results in an error.
Now, I'll start talking about the function stack (or "call stack"):
When a function is called, it's placed on the "call stack".
When the function returns, meaning when it finishes execution, it's removed from the stack.
Right, understanding that, I'll show you an example that allows you to see the path the code took to get to where it is, meaning see how the call stack works and task stacking.
Example of code that demonstrates how the function stack works:
function foo() {
console.log('Calling foo');
bar();
console.log('Returning from foo');
}
function bar() {
console.log('Calling bar');
baz();
console.log('Returning from bar');
}
function baz() {
console.log('Calling baz');
console.log('Returning from baz');
}
foo();When you execute this code, the output will be:
Calling foo
Calling bar
Calling baz
Returning from baz
Returning from bar
Returning from fooHere, we can see that functions are added to the function stack when called and removed from the stack when they return.
When a function is called, it's added to the top of the stack and the next function is called.
When the function returns, it's removed from the top of the stack and the next function in the stack is called. This continues until the stack is empty and script execution ends.
Conclusion
Functions are a very important part, as they allow us to write code in a more organized and reusable way.
I, Jeff, emphasize that:
It's important to dedicate time to understand how functions work and how to use them efficiently, as this can help a lot when creating your applications.
Remember that it's important to practice what you're learning, as this will help solidify the concepts and improve your abstraction skills.
Try creating your own applications, and play with functions, passing different parameters and arguments.
Well HaWker, we've reached the end of another article.
I hope this article has added to your repertoire of programming knowledge.
As always, if you have any questions or want to explore any point further, just reply with your question to this email.
And remember, I'm here to help you improve 1% with each new article!
If you made it this far, as usual, please reply to this email with "I managed to learn and understand about functions in programming".
This way I'll know that this article series is being useful for you, and that you're following along and taking advantage.
As you already know! Only a true HaWker makes it to the end.
Congratulations!
I'm happy to have you here.
See you soon.
Let's go! 🦅
- Jeff Bruchado
Congratulations on making it this far, HaWker! 🎉
Now that you've learned about functions in programming, how about testing your knowledge? Take the quiz below and see how much you absorbed from our article.
It's a great way to reinforce learning and prepare for the next steps in your programming journey.
Good luck and have fun!

