Reviewing Functions | JavaScript 🔥 | Lecture 034

The Coding Classroom
5 Apr 202315:38

Summary

TLDRThis comprehensive video lecture delves into the intricacies of functions in programming. It covers the three types of functions: function declarations, function expressions, and arrow functions, highlighting their distinct characteristics and use cases. The lecturer meticulously breaks down the structure of a typical function, explaining the components such as function names, parameters, function bodies, and return statements. Additionally, the video explores the concepts of function invocation, argument passing, and how functions process and output data. Through clear examples and explanations, the lecturer aims to solidify the viewers' understanding of functions, laying a strong foundation for their coding journey.

Takeaways

  • 🔑 The script reviews the three types of functions in JavaScript: function declarations, function expressions, and arrow functions. It explains their differences and when to use each.
  • 🧩 Functions have a structure consisting of a name, parameters (placeholders for input data), a body (where the code logic resides), and often a return statement to output a value.
  • 🚀 Calling a function is done by using parentheses after the function name, and passing arguments (actual values) to the parameters.
  • 🔄 The return statement immediately terminates the function execution and returns the specified value.
  • 🔍 console.log() is a function itself, used for printing messages to the developer console, distinct from returning values from a function.
  • ✨ Functions can receive input data, transform it, and output data, though these steps are optional.
  • 🔁 Functions are useful for reusing code logic across different parts of a program.
  • 🎯 The script emphasizes understanding the data flow and variable scoping within functions.
  • 🌐 Parameter names can be reused across different functions without conflict, as they are treated as separate local variables within their respective functions.
  • 🔖 The script prepares the learner for an upcoming coding challenge involving writing their first function.

Q & A

  • What are the three types of functions discussed in the script?

    -The three types of functions discussed are: 1) Function declarations, 2) Function expressions, and 3) Arrow functions (which are a special form of function expressions).

  • What is the main difference between function declarations and function expressions?

    -Function declarations can be used before they are declared in the code, while function expressions are essentially function values stored in a variable and cannot be used before they are defined.

  • What are the advantages of using arrow functions?

    -Arrow functions are great for writing quick one-line functions, as they don't require the explicit use of the 'return' keyword or curly braces. They also don't have their own 'this' keyword.

  • What are the three main operations that functions can perform?

    -Functions can receive input data (parameters), transform or process that data (function body), and output data (return statement).

  • What is the purpose of the 'return' statement in a function?

    -The 'return' statement is used to output a value from the function, and it also immediately terminates the function's execution.

  • How do you call or invoke a function?

    -A function is called or invoked by writing its name followed by parentheses, e.g., 'functionName()'.

  • What is the difference between parameters and arguments in a function?

    -Parameters are placeholders for input values in a function declaration, while arguments are the actual values passed into the function when it is called.

  • What is the purpose of the 'console.log()' function in JavaScript?

    -The 'console.log()' function is used to print messages or values to the developer console in the browser. It is a separate function call within another function and is not related to the 'return' statement.

  • Can you explain the data flow when calling a function from another function?

    -When a function is called from within another function, the arguments are first passed to the inner function, which then performs its operations and returns a value. This returned value can then be used or processed further in the outer function.

  • What is the purpose of the 'if-else' statement used in the script?

    -The 'if-else' statement is used to handle different scenarios based on a condition. In the script, it is used to return a specific value (e.g., -1) if the 'retirement' value is less than or equal to zero, indicating that the person has already retired.

Outlines

00:00

🔍 Review of Functions and Function Expressions

This paragraph reviews the key concepts related to functions, including regular function expressions, arrow functions, and how they receive input data, transform it, and output results. It demonstrates converting an arrow function to a regular function expression, introduces the `calcAge` function, and explores how parameters are local variables within functions. It also explains how the `return` statement immediately exits a function and demonstrates its usage.

05:02

🧭 Handling Return Values and Terminating Functions

This paragraph focuses on handling return values from functions based on conditions. It introduces an `if-else` statement to conditionally return different values from the `yearsUntilRetirement` function based on whether the calculated retirement value is positive or negative. It also illustrates how the `return` statement immediately terminates the function execution, preventing any subsequent code from running. The paragraph demonstrates moving `console.log` statements before the `return` statements to ensure they execute.

10:02

🔄 Comprehensive Review of Function Concepts

This paragraph provides a comprehensive review of the key concepts related to functions learned so far. It discusses the three types of functions: function declarations, function expressions, and arrow functions, highlighting their differences and similarities. It also explains the structure of a typical function, including its name, parameters, function body, and return statement. The paragraph clarifies the distinction between `console.log` and `return`, emphasizing that `console.log` is a function call used for debugging purposes, while `return` outputs a value from the function.

15:02

🎯 Conclusion and Preview of the Coding Challenge

This concluding paragraph summarizes the key points covered about functions and encourages the learner to ensure they fully understand the concepts. It also previews the upcoming coding challenge, which will involve writing a function for the first time, and expresses excitement for the learner to tackle the challenge.

Mindmap

Keywords

💡Function

A function is a reusable block of code that performs a specific task. In the video, functions are presented as a way to organize and reuse code, taking input data, transforming it, and optionally returning an output. Functions are essential for writing modular and maintainable code in programming. The video discusses different types of functions, such as function declarations, function expressions, and arrow functions.

💡Parameters

Parameters are placeholders or variables that receive input values when a function is called. They act as local variables within the function's scope, allowing the function to work with external data. In the video, the instructor explains that parameters are like local variables of a function, defined only inside that specific function. For example, the `calcAge` function has a `birthYear` parameter that receives the birth year value passed as an argument when calling the function.

💡Return statement

The return statement is used to output a value from a function. It specifies the data that the function should produce after executing its code. The video emphasizes that the return statement not only outputs the desired value but also immediately terminates the function's execution. This means that any code after the return statement in the function will not be executed. Understanding the return statement is crucial for controlling the flow of a program and managing the output of functions.

💡Function call

A function call, also known as invoking or executing a function, is the act of running a function's code. This is done by writing the function's name followed by parentheses, optionally with arguments passed inside the parentheses. The video demonstrates function calls using examples like `calcAge(1991)` and explains that the parentheses are necessary to execute the function's code, as opposed to just referring to the function value itself.

💡Arguments

Arguments are the actual values passed to a function when it is called. They correspond to the parameters defined in the function's signature. In the video, the instructor explains that arguments replace the placeholders or parameters within the function, providing the necessary data for the function to work with. For example, when calling `calcAge(1991)`, the argument `1991` is passed and replaces the `birthYear` parameter within the `calcAge` function.

💡Function body

The function body is the block of code enclosed within curly braces `{}` that defines the actions and logic of a function. It contains the statements and operations that the function performs when called. The video refers to the function body as the place where the function's input data is processed and transformed before potentially returning an output value. Understanding the function body is essential for writing functional and reusable code.

💡Scope

Scope refers to the accessibility and visibility of variables and functions within a program. The video touches on scope when discussing parameters, which are variables with a local scope confined to the function they are defined in. Understanding scope is crucial for managing variable naming conflicts and ensuring proper data encapsulation and modularity in code. The instructor emphasizes that parameters with the same name in different functions are treated as separate variables due to their distinct scopes.

💡Reusability

Reusability is one of the core concepts of functions and is mentioned multiple times in the video. It refers to the ability to write a piece of code once and use it repeatedly in different parts of a program or across multiple programs. Functions promote reusability by encapsulating logic and behavior into modular units that can be called and executed as needed, reducing code duplication and improving maintainability.

💡Modularity

Modularity is the principle of breaking down a complex system into smaller, independent, and reusable components or modules. Functions are a key element of modular programming, as they allow code to be organized into separate, self-contained units that can be developed, tested, and maintained independently. The video emphasizes the importance of writing modular code and using functions to achieve this, making programs easier to understand, debug, and extend.

💡Code organization

Code organization refers to the structured and logical arrangement of code elements, such as functions, variables, and control structures, within a program. Good code organization is essential for readability, maintainability, and collaboration. Throughout the video, the instructor emphasizes the importance of organizing code into functions, separating concerns, and using clear naming conventions to improve code quality and comprehension.

Highlights

Functions are essential in programming and can receive input data, transform data, and output data.

There are three types of functions: function declarations, function expressions, and arrow functions.

Function declarations can be used before they are declared in the code.

Function expressions are function values stored in a variable.

Arrow functions are special function expressions, great for quick one-line functions without the explicit return keyword or curly braces.

All types of functions can receive input data, transform data, and output data, regardless of how they are written.

Functions typically have a name, parameters (placeholders for input values), a function body (code to process the input), and a return statement (to output a value).

Calling a function involves using parentheses after the function name, and providing arguments (actual values) for the parameters.

The return statement terminates the function's execution and outputs a value.

The console.log() function is used to print messages to the developer console for debugging purposes, and is separate from returning a value.

Understanding the structure and behavior of functions is crucial for effective programming.

The transcript provides a thorough review of functions, covering their types, structure, calling, and the role of return statements.

The transcript prepares the reader for an upcoming coding challenge involving writing their own function for the first time.

The explanation of functions is clear, concise, and designed to solidify the reader's understanding before moving on to more advanced topics.

The transcript demonstrates the importance of reviewing fundamental concepts and ensuring a strong grasp before progressing in programming.

Transcripts

play00:01

To finish this part about functions,

play00:03

let's review everything important that we learned so far.

play00:07

In order to make sure that you really understand functions

play00:11

before we move on to other topics.

play00:15

And let's start by bringing back and rewriting the function

play00:19

that we wrote before,

play00:20

which is the years until retirement function.

play00:25

So I think that was,

play00:27

yeah it was here in the lecture about arrow functions.

play00:31

So let's copy this one and paste it here.

play00:37

And the first thing that we're gonna do

play00:38

is to actually convert it

play00:40

to a more normal function expression.

play00:43

So how do we do that?

play00:45

Well, in this case,

play00:46

we simply get rid of the arrow here

play00:50

and then write the function keyword here.

play00:55

And so now this is just a regular function expression

play00:58

like we learned before.

play01:00

Next up we could export this functionality here

play01:04

into another function.

play01:05

So like a calcAge function that we've been using before.

play01:10

So let's do that

play01:11

because then we can do what we did in the last lecture,

play01:14

which was to call one function inside of the other function.

play01:19

So let's write another function expression here,

play01:22

calcAge equals

play01:27

a function and then the birth year again.

play01:33

And what we return from this one is simply 2037

play01:39

minus the birth year.

play01:42

So we already did that before. Right.

play01:45

Now you might find it confusing

play01:47

that we have two different functions here

play01:49

with the same parameter names.

play01:51

So this one has birth year and this one has too,

play01:55

but that's not a problem at all.

play01:57

So this birth year in this function is not at all related

play02:02

to this birth year in this function.

play02:04

They are two completely different parameters.

play02:06

So basically two different variables.

play02:09

We could even have a variable outside

play02:11

of any of the functions,

play02:13

which could also be called birth year.

play02:16

Okay.

play02:17

And we could do that now,

play02:18

but I don't want to confuse you even further. Okay.

play02:22

But what matters here is that this parameter is really

play02:25

like a local variable to each function.

play02:29

Anyway,

play02:30

let's now go ahead and delete this here and instead,

play02:34

calculate the age based on the function that we just wrote.

play02:38

And actually we just delete this part here.

play02:41

And so now the age will come from the function calcAge.

play02:46

And what we pass in here is the birth year.

play02:50

So again, it's confusing now with these

play02:53

same parameter names here,

play02:55

but let's quickly call this function

play02:58

just so I can quickly show you the data flow.

play03:02

So years until retirement with birth year 1991

play03:07

and first name of Jonas.

play03:11

So 1991 will be the birth year here in this function.

play03:16

Then as a first step,

play03:17

this years until retirement function called calcAge

play03:21

and it calls calcAge with the argument of 1991.

play03:26

So this one here,

play03:27

and so then birth year in this function also becomes 1991.

play03:32

And so then here, the operation will be 2037 minus 1991.

play03:37

And if you find it less confusing,

play03:39

we could change this year to something else.

play03:42

Let's just say year and it would work the exact same way.

play03:46

Okay. So again,

play03:47

these variable names in these two different functions,

play03:52

they do not have anything to do with one another.

play03:55

All right.

play03:56

But let's actually put it back here

play03:58

because it's a, it's good to keep this in mind.

play04:02

Then down here,

play04:03

let's actually go back to returning a number

play04:06

and not the string, which for now I will just comment out.

play04:12

So here we call this function and once more,

play04:15

I'm not gonna store it into a variable.

play04:18

So we will just log the result of this, to the console.

play04:24

So this should be just like before, 19.

play04:27

Okay.

play04:28

But now I want to show you something

play04:30

which is to call this function again,

play04:32

let's say now with a Mike

play04:36

and let's say Mike was born in 1970.

play04:41

And so,

play04:43

his years until retirement will be two.

play04:47

So a negative number, which means that he already retired.

play04:51

So let's quickly account for that.

play04:53

So what we will do is to basically return this number,

play04:57

if it is above zero,

play04:59

and if it is below zero,

play05:01

we are gonna return something else like a minus one

play05:05

or something or some special number.

play05:09

So instead of returning simply the retirement,

play05:12

let's take a decision here based on the retirement value.

play05:16

And so that's something that we learned in the last lecture.

play05:19

So let's use an if else statement and say,

play05:23

if the retirement is

play05:27

greater than zero.

play05:29

So if there are more than zero years left until retirement

play05:33

then return this retirement value.

play05:37

Okay.

play05:38

So remember that in the, if block,

play05:41

we can put any code that we want.

play05:43

And so that includes the return statement.

play05:47

And else, well, let's just return always minus one.

play05:53

So, minus one is kind of a standard number in programming.

play05:57

We could also like return,

play06:00

like this.

play06:01

So a number that shows us clearly that this has no meaning.

play06:06

Let's just keep it at number one, minus number one.

play06:09

Okay.

play06:10

And I'm returning actually numbers here

play06:12

and not a string as we had before,

play06:15

because that's usually what we do,

play06:17

especially when we actually receive a number as an input.

play06:21

So here in this function, we get birth year

play06:25

here as an input, and it's a number

play06:28

and therefore it's a good practice to

play06:30

then also return a number.

play06:34

Okay, let's try this again.

play06:36

Now, we'll even change it to something more drastic.

play06:39

So 1950 and let's see what we get now.

play06:46

Now,

play06:46

so it's minus one now.

play06:49

Great.

play06:50

Now, one thing that I didn't mention yet is

play06:53

that this return keyword here

play06:55

will actually immediately exit the function.

play06:58

So it will first return the value that we tell it to return.

play07:02

So in this case, the retirement value,

play07:05

and then after that, the function is done.

play07:08

So it exits immediately.

play07:10

And we also say that the function has returned.

play07:13

So let me actually demonstrate that to you.

play07:16

And what I will do is to take this string here.

play07:20

Now we can get rid of the rest

play07:23

and I will put that after the return.

play07:26

So we will log to the console,

play07:29

this string here that we just had.

play07:35

And then here let's log simply

play07:41

the first name has already retired,

play07:47

and then we can put another emoji here,

play07:51

like this party emoji that I like.

play07:55

And,

play07:58

yeah.

play07:59

What do you think will happen when we run this code now

play08:02

and keep in mind that we have the return

play08:04

before the console dot log, in both cases.

play08:07

So in the, if block here and also in the else block.

play08:12

So what do you think is gonna happen with these

play08:14

console dot logs?

play08:16

Well, let's see.

play08:18

And indeed they are simply ignored,

play08:21

so they will not get executed.

play08:23

Because as I said before,

play08:25

the return statement immediately exits

play08:28

or immediately returns the function.

play08:31

And so therefore there is no chance

play08:33

that this code here is even reached.

play08:36

So if we want this one here to execute,

play08:39

we need to put it before the return

play08:41

and in vs code, I can simply hit option or alt up.

play08:47

Okay. And that will then move the line up.

play08:50

So we can,

play08:50

we also have that here somewhere in this menu.

play08:56

So that's move line up and move line down.

play08:59

So just so you see which one is the shortcut.

play09:03

So I use that one all the time.

play09:04

I also use add cursor below all the time,

play09:08

and I also use add next occurrence.

play09:11

So that would be command or control D.

play09:14

So what this means is that we have, if we have

play09:18

this for example, here select it

play09:20

then we can already see all the other ones.

play09:22

But if we hit command D then it will actually select that.

play09:27

So you see. Now we have these four selected.

play09:29

And so we now could replace all of them at the same time,

play09:32

for example, like this. Okay.

play09:35

But anyway, let's go back to what we were doing here.

play09:38

So I just moved the console dot log before the return here.

play09:43

And so now there should be a chance that the console dot log

play09:46

is actually executed before the value is returned.

play09:50

And so let's do the same here.

play09:52

So again, I'm hitting option or alt up.

play09:55

Add to these two lines to changed position,

play09:58

and now, yeah, now it works.

play10:02

So we get the string and here we get,

play10:03

Mike has already retired.

play10:06

Okay.

play10:07

So this was to show you some more things about functions

play10:10

that we had already learned,

play10:12

and also show you something new,

play10:14

which is the fact that the return statement here

play10:18

immediately exits the function.

play10:20

So we reviewed already some things here,

play10:23

but now it's time to really review everything

play10:25

that we learned so far about functions

play10:27

in these first couple of lectures.

play10:30

And here we have the three type of functions

play10:32

that we talked about.

play10:34

So we have first, the function declaration,

play10:37

and one particularity about function declarations

play10:40

is that they can be used before

play10:42

they are declared in the code.

play10:44

Second, we have the function expressions,

play10:48

and they are essentially function values

play10:50

that are stored in a variable.

play10:52

And finally, we have arrow functions

play10:55

that are in fact also function expressions,

play10:58

but special ones.

play11:00

And these are great for quick one line functions

play11:03

where we don't need to explicitly use the return keyword

play11:06

and no curly braces either.

play11:09

I also said that this one has no this keyword,

play11:12

but more about that in one of the future lectures.

play11:16

Now what's important to note here is that

play11:18

these are three different ways of writing functions,

play11:21

but they all work in a similar way.

play11:24

So all of them can receive input data, they transform data,

play11:28

and then they can output data.

play11:31

It's all optional,

play11:32

but usually that's the things that functions do.

play11:35

And no matter which type of function we use,

play11:37

we can always do these three things.

play11:41

And now let's zoom in a little bit further

play11:43

and take a close look at the structure of a

play11:47

common function let's say.

play11:49

And this one here is a function statement,

play11:52

but it works the exact same way

play11:53

for all other types of functions again.

play11:57

So first, usually a function needs a function name.

play12:00

So calcAge in this example,

play12:03

then a function also has parameters.

play12:06

And these parameters are essentially placeholders,

play12:09

that receive input values.

play12:11

So, as I said before,

play12:12

these are a little bit like local variables of a function.

play12:16

So variables that are defined

play12:18

only inside of this very function.

play12:21

Now, as you also already know,

play12:23

we use functions to reuse pieces of code,

play12:27

and these pieces of code are inside the function body.

play12:31

So this is where the functions input data

play12:34

is usually processed and then returned.

play12:38

And speaking of the return, by the end of the function,

play12:40

we usually have a return statement,

play12:43

which we use to output a value from the function.

play12:46

And also, as I mentioned a little bit earlier,

play12:49

the return statement also immediately terminates

play12:52

the function's execution.

play12:55

We also say that the function returns, okay.

play12:58

And now about calling the function,

play13:01

we do that using parenthesis.

play13:03

So we write the name of the function

play13:04

like we did here with calcAge

play13:06

and then with a parenthesis we call the function.

play13:10

Because without the parenthesis,

play13:12

the function is really just a value.

play13:14

But then with the parenthesis,

play13:16

we actually called a function.

play13:18

And we can also say that we run the function

play13:20

or invoked a function or execute a function.

play13:24

And all of these terms kind of mean the same thing.

play13:28

Now, in this case,

play13:29

since the function actually has parameters,

play13:32

we then call the function with arguments and these arguments

play13:36

are the actual values of the function parameters.

play13:40

So we use these to input the actual data into the function.

play13:44

And we can also imagine this as replacing the placeholders

play13:48

that are the parameters.

play13:50

Then once the calcAge function has finally done its job,

play13:54

then all this expression will basically be replaced

play13:58

with the returned value.

play14:00

So in this case, the age that was replaced here.

play14:03

And that age value is what we then store

play14:06

into this age variable.

play14:09

So we use this variable to basically save the returned value

play14:12

that was outputed from the function.

play14:15

Okay.

play14:16

Now just one other thing that I want to make clear is

play14:19

that this console dot log that we have in the function.

play14:23

So in that first line there,

play14:25

has nothing to do with returning a value.

play14:28

This simply prints a message to the developer console,

play14:31

but it has nothing to do with returning.

play14:34

Actually the console dot log is actually just

play14:37

another function call inside the calcAge function

play14:40

because console dot log is itself a function.

play14:44

And so the argument that we pass into

play14:47

the console dot log function

play14:48

is what will get printed to the developer console.

play14:52

Okay. So just wanted to make sure

play14:55

that you really get this distinction

play14:57

between console dot log and return.

play14:59

The reason why we always use console dot log

play15:02

is because we want to see the results of our experiments

play15:05

in the developer console, in the browser.

play15:09

Anyway,

play15:10

I think this pretty much sums up all there is to know,

play15:13

at least for now about functions.

play15:16

So make sure that you get all of this down

play15:19

and then you can move on right to the next video

play15:22

where the first coding challenge

play15:24

of this section waits for you.

play15:26

And as you can probably guess,

play15:28

it's gonna be about writing your own function

play15:31

for the very first time.

play15:32

So I hope to see you there soon.