Function with Input and Assignable Output
To create more complex programs, we can have our functions be dependent on its inputs and give the ability to have the output of its functions be assigned to variables.
Example: 420 checker.
We are going to create a program that checks if our given number is 420.
The function will take a single parameter, we will call it: num
The function will output either true
if the given parameter is 420, false
otherwise
Our Program:
Outputs:
Function Declaration: The function
is_420
is declared with one parameternum
.Parameter
num
: This parameter will hold the value passed to the function when it is called. It is a placeholder variable to represent the potential values it can receiveAs you can see,
num
was69
in the firstconsole.log()
while being420
in the second output.
return is a keyword in JavaScript that has two important features:
return
allows us to assign a variable by creating a value from the functionreturn
also ALLOWS THE FUNCTION TO ENDS ITS CODE EARLY because the function will exit its code block when areturn
statement is executedIn the example above:
if
Statement: The function checks ifnum
is equal to420
.Condition
num == 420
: Ifnum
is420
, the function returnstrue
and it is assigned to either variableresult1
orresult2
when the function is calledelse
Statement: Ifnum
is not420
, the function returnsfalse
and it is assigned to either variableresult1
orresult2
when the function is called
The following output above is possible because:
result1
stores the result ofis_420()
with the given parameter of69
result2
stores the result ofis_420()
with the given parameter of420
Last updated