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:
// Function Definitions
function is_420(num) {
if (num == 420) {
return true;
} else {
return false;
}
}
// End of Function Definitions
// Our Main Section
let result1 = is_420(69);
let result2 = is_420(420);
console.log(`Checking 69: ${result1}`);
console.log(`Checking 420: ${result2}`};Outputs:
Checking 69: false
Checking 420: trueFunction Declaration: The function
is_420is 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,
numwas69in the firstconsole.log()while being420in the second output.
return is a keyword in JavaScript that has two important features:
returnallows us to assign a variable by creating a value from the functionreturnalso ALLOWS THE FUNCTION TO ENDS ITS CODE EARLY because the function will exit its code block when areturnstatement is executedIn the example above:
ifStatement: The function checks ifnumis equal to420.Condition
num == 420: Ifnumis420, the function returnstrueand it is assigned to either variableresult1orresult2when the function is calledelseStatement: Ifnumis not420, the function returnsfalseand it is assigned to either variableresult1orresult2when the function is called
Checking 69: false
Checking 420: trueThe following output above is possible because:
result1stores the result ofis_420()with the given parameter of69result2stores the result ofis_420()with the given parameter of420
Last updated