Functions in JavaScript

What makes a function a function? It
contains a block of code
can take some input(s)
convert those input(s) into an output
must work the same way every time (deterministic)
all in all, it turns the block of code reusable
To sum up, functions turn a block of code reusable by enabling in-take of input, which is then converted into an output that must be deterministic, meaning, it has to work the same way every time.
Ok, enough concept. It's time for a code2learn session using vscode, JavaScript, and the Quokka.js extension to allow immediate display of output.
Type code demo.js from any command line/terminal. That will open demo.js in vscode.
Try out the following code
var num = Number("123");
Number() is a JavaScript built-in function that take any numerical string input and convert it to a number. The function also returns the output, which can be assigned to a variable, num in this case.
Try out the next code to print the output to the console.
console.log(num); // 123
console.log() is a built-in function in JavaScript to print any input to the console. When num is passed as argument, it prints out 123.
Try out the next code to create a printHello() function
function printHello() {
console.log("Hello");
}
Next, try out the following code to call the function
printHello(); // Hello
What is the take away in the above code? The take away is that there are four parts to create a function:
the
functionkeywordthe function name,
printHellothe parenthesis with no space
()the curly brackets
{}
Every function definition requires these four parts.
To add an input to a function, a placeholder for that input is declared inside the parenthesis at the time of function definition . That placeholder is known as parameter. If there're more than one input, then additional parameter is added separated by commas.
function add(param1, param2, param3) {
return param1 + param2 + param3;
}
Try out the code below, a simple function with a single parameter.
function printHello2(firstName) {
console.log("Hello " + firstName);
}
Each time the function is called, the required input must also be passed. Passing such input is referred to as passing an argument. For example, the call to printHello2("Sam") requires passing the literal string "Sam" as an argument. "Hello Sam" is the output printed out to the console.
printHello2("Sam"); // Hello Sam
Next, try out the code below, a function that returns an output. It uses the special keyword return to return an output.
function printHello3(firstName) {
return "Hello " + firstName;
}
Next, try out the code below, a function which return an output.
var helloPete = printHello3("Pete");
console.log(helloPete); // Hello Pete
The first line of code above have two parts:
First, the function returns an output
Second, the output is assigned to a variable,
helloPete
The second line takes the variable as argument and prints it out to console.
