js_sem2_lec4
js_sem2_lec4
@newtonschool
Table of Contents
● Function Declaration and Syntax
● Parameters vs Arguments
● Spread and Rest Operator
● Function Return Values
● Higher Order Functions and Callback Functions
Function Declaration and
Syntax
What is a Function?
Function is a block of code made out of set of steps which result in a single
specific action.
PRIMITIVES
Similarly we use functions in our programs
Let us define a tie shoes function and reuse it multiple times:-
PRIMITIVES
Naming a function
A programmer can give function a name and be used again and again.
PRIMITIVES
Challenge:
PRIMITIVES
Think of a more complex task/function
Your dad wants you to calculate your daily expenses but you find it
difficult to do manually, you are crying for help!!
Your Rescue: Write an add function
Don’t worry functions are here for rescue.
Function Parameters
Here “num1” and
“num2” are
function
parameters.
Function: using parameters to add
Let’s use parameters to calculate the sum. And print it:-
Using parameters to
perform addition
Function: calling using arguments
Let’s just call the function by passing values inside it:-
Feeling awesome,
right??
Higher Order Functions and
Callbacks
Values we can pass/return in a function
You can pass variety of values in a function. Let’s have a look:-
Primitive Data
Objects Functions Others
Types
Higher-Order Functions
A higher-order function is a function either accepts a function as an argument or
returns a function.
But why do we
need function to
receive and accept
values??
Advantage of Higher-Order Functions
We receive or return functions as values to make our code flexible and reusable, allowing
us to define behavior dynamically and build more modular, maintainable programs.
Callback function
Rest and Spread Operator
Rest operator: team player of javascript
You are tasked to form a cricket team. First, pick your favourite duo to open the
batting, then select the captain. The rest make up the team.
Rest operator: team player of javascript
Let’s write a code for it:-
rest operator
grouping rest of
the values in
variable team
Output:
41
Thanks
for
watching!
42