Contact Information

KodeBlog

We're Available 24/ 7. Drop us an email.

JavaScript Functions

A JavaScript function is a piece of code that does a specific task. For example, you can have a function that gets the current system date and prints it to the terminal. Functions promote code reusability as you have to only write them in one place then reuse them as many times as you want.

Functions also simplify the process of maintaining applications. When you update the code underlying the function, the changes affect all the pieces of code the use the function. Functions can either accept parameters or they can be executed without functions.

By the time that you are done with this lesson, you will be able to work with built-in functions in JavaScript, define your own custom functions, learn how to pass arguments to functions and return values from functions when necessary.

Topics to be covered

We will cover the following topics in this lesson

Lesson Prerequisites

For you to successfully complete this lesson, you should have the following requirements

  • NodeJS - we will be executing JavaScript files directly using NodeJS from the command line. Alternatively you can execute the files in the web browser but that takes a a little more time and involves working with multiple programs.
  • Web Browser - a web browser can be used as an alternative to executing JavaScript files that we will be working with.
  • Visual Studio Code - we will be using it as the code editor. It comes with a built-in terminal that will allow us to easily execute JavaScript code from within the text editor. You can also use any code editor that you prefer.
  • JavaScript Basics - this is an added advantage and not mandatory. We will explain every piece of code covered in these lessons.

Lesson Practical Examples Project Setup

This is a practical based lesson. For you to successfully work out the examples given in this lesson, you will need to setup the following directories and files

Create a new directory called javascript-functions

Open the directory javascript-functions in Visual Studio Code or your favorite code editor

Create the following files inside your project folder.

  • bi-functions.js - this file will be used to for code dealing with built-in functions
  • custom-functions.js - this file will be used for code dealing with custom or user defined functions

The following visualizes our project setup

javascript-functions
-bi-functions.js
-custom-functions.js

Open the directory javascript-functions in Visual Studio Code or your favorite code editor

JavaScript Built-in Functions

JavaScript comes with built-in functions for common tasks that almost every program has to perform. For example, when performing arithmetic operations, the data type must be numeric. When you user the user for input, they provide it in string format. JavaScript has built-in functions that we can use to convert the strings to number. Let's now look at some of the built-in functions and how to use them.

JavaScript eval

This function accepts a string parameter that it interprets to a valid JavaScript program then executes it to return the result. Let's look at a practical example.

Open the file bi-functions.js

Add the following code then save the changes

let prog = "console.log('the eval function rocks')";

console.log(prog);

HERE,

  • let prog = "console.log('the eval function rocks')"; defines a variable prog that contains valid JavaScript code but it is assigned as a literal value.
  • console.log(prog); prints out the value of prog to the terminal

In Visual Studio Code, click on the terminal menu then select New Terminal. This will open a command line window within Visual Studio Code

Run the following node command to execute our JavaScript file

node bi-functions.js

You should be able to get the following results

console.log('the eval function rocks')

Let's now modify the above program and use the eval function to execute the value of the variable prog.

let prog = "console.log('the eval function rocks')";
let message = eval(prog);
console.log(message);

HERE,

  • let message = eval(prog); defines a variable message that is assigned the value of the eval function which is using the value of prog as the function argument.

Run the following command in the terminal to execute our modified code

node bi-functions.js

You should be able to get the following results

the eval function rocks

Notice how this time the string was treated as a JavaScript program, executed successfully and the results returned as we expected.

JavaScript parseInt

This built-in function accepts a string argument then converts it to an integer type. It is useful when you accept input from the user and you need to perform arithmetic operations on it. Let's now look at an example.

Open the file bi-functions.

js and add the following code to it.

let first_number = '4';
let second_number = '8';

let result = first_number + second_number;

console.log(result);

HERE,

  • let first_number = '4'; defines a variable that is assigned the value 4 but as a string and not a number
  • let second_number = '8'; assigns the string value 8 to the variable that we just defined
  • let result = first_number + second_number; adds the first and second numbers then assigns the result to the variable result
  • console.log(result); logs the value of result to the terminal.

Run the following node command to execute our file

node bi-functions.js

You should be able to get the following results

48

Notice how we wanted to perform an arithmetic operation but instead we just concatenated 4 and 8. This is where theparseInt function comes in.

Modify the code as follows

let first_number = '4';
let second_number = '8';

let result = parseInt(first_number) + parseInt(second_number);

console.log(result);

Open the terminal and then run the following command

node bi-functions.js

You should be able to get the following results

12

You should only use parseInt when the numeric values that you working with have no decimal points or you intentionally want to ignore the values after the decimal points. This is because parseInt drops the decimal values. Let's look at a practical example. Let's say you want to calculate the total cost for a meal.

let meal = '6.7';
let soda = '1.8';
let total = parseInt(meal) + parseInt(soda);

console.log('total is ' + total);

HERE,

  • let meal = '6.7'; let soda = '1.8'; defines two variables that are assigned string literal decimal values
  • let total = parseInt(meal) + parseInt(soda); performs an arithmetic operation and parses the strings using parseInt function
  • console.log('total is ' + total); prints the results in the console

Open the terminal and run the following command

node bi-functions.js

You should be able to get the following results

total is 7

Notice how our application added 6 and 1 and dropped 0.7 and 0.8. This is a net loss of 1.5. In the next section, we will fix this problem

JavaScript parseFloat

Float accepts decimal points. You should use it when you want to get the value after the decimal point too. parseFloat allows you to convert a string literal that contains a decimal place to a valid decimal number. Let's now rewrite the above program as follows

let meal = '6.7';
let soda = '1.8';
let total = parseFloat(meal) + parseFloat(soda);

console.log('total is ' + total);

HERE,

  • let total = parseFloat(meal) + parseFloat(soda); defines a variable total and assigns the value of the expression parseFloat(meal) + parseFloat(soda).
  • console.log('total is ' + total); prints the total in the console.

Open the terminal and run the following

node bi-functions.js

You should be able to get the following results

8.5

JavaScript encodeURI / escape

The encodeURI function is used to encode regular strings with special characters into URL friendly strings. It is the predecessor of the escape function. The escape function has been deprecated in favor of encodeURI. Both functions return the same values. The escape function has not been removed but you should be using encodeURI since its the recommended function.

Let's look at a practical example. We will create a regular string that contains

let title = 'JavaScript Built-in functions @ "KodeBlog"';

console.log(escape(title));
console.log(encodeURI(title));

HERE,

  • let title = 'JavaScript Built-in functions @ "KodeBlog"'; defines a variable title that is assigned a string value that contains spaces and special characters like" double quotes which are not URL friendly.
  • console.log(escape(title)); calls the escape function with the value of the title as the function argument then prints the result to the terminal.
  • console.log(encodeURI(title)); executes the encodeURI with the title variable as the argument.

Open the terminal and then run the script using the node command. You should be able to get the following results.

JavaScript%20Built-in%20functions%20@%20%22KodeBlog%22
JavaScript%20Built-in%20functions%20@%20%22KodeBlog%22

as you can see from the above results, both functions have returned the same result.

JavaScript decodeURI / unescape

The decodeURI function is used to decode data that was encoded using encodeURI function. It should be used in favor of unescape. The function unescape is similar to escape but does the opposite. We will now decode the results from the above section into the original values.

let encoded_title = 'JavaScript%20Built-in%20functions%20@%20%22KodeBlog%22';

console.log(unescape(title));
console.log(decodeURI(title));

HERE,

  • let encoded_title = 'JavaScript%20Built-in%20functions%20@%20%22KodeBlog%22'; defines a string value that has been encoded
  • console.log(unescape(title)); decodes our variable title into human readable format using the unescape function.
  • console.log(decodeURI(title)); decodes our variable title using the recommended decodeURI function.

Executing the above code produces the following results

JavaScript Built-in functions @ "KodeBlog"
JavaScript Built-in functions @ "KodeBlog"

JavaScript User Defined Functions

User defined function are functions that you create yourself to perform very specific tasks. For example, you can create a function that accepts two numbers then returns their sum. Before we look at a practical example, let's look at the syntax for defining functions in JavaScript.

Function declaration syntax

The syntax for defining functions is as follows

function functionName(){
	//function logic
}

HERE,

  • function functionName(){...} the keyword function is used to tell JavaScript that we are now defining a function. functionName is the name of the function that we want to create. The open and closing () should immediately follow the function name. The parenthesis can also be used to define function parameters. The code for the function is placed between the curly brackets {...}.

The following example shows how to define a function that accepts parameters

function functionName(first_parameter,second_parameter){
	//parameters are now available to the function as variables
	//function logic
}

HERE,

  • first_parameter,second_parameter defines two function parameters first_parameter and second_parameter.

JavaScript Function Example

Let's now create a simple function that accepts a number, squares it then prints the result to the terminal.

Open the file custom-functions.js then add the following code

function square(number){
    console.log(number * number);
}

square(1);
square(2);
square(3);

HERE,

  • The above function accepts a number then prints the square in the console
  • square(1); square(2); square(3); calls our function with 1,2,3 as parameters

Open the terminal then run the following command

node custom-functions.js

You should be able to get the following results

1
4
9

Let's now look at an example that does not accept a parameter. We will create a simple function that prints the system time to the console.

function printDate(){
    let date = new Date();

    console.log(date);
}

printDate();

HERE,

  • function printDate(){...} defines a function printDate.
  • let date = new Date(); defines a variable date that is initialized to an instance of the object Date.
  • console.log(date); prints the value of our variable to the terminal

Executing the above code should give you results similar to the following

2019-12-23T20:26:36.794Z

Function Return statement

The return statement is used to return a value after a function has finished executing. For example, you can create a function that displays the product of two numbers or a simple function that displays the application version. Let us look at a practical example.

function product(first_number,second_number){
    return first_number * second_number;
}

let result = product(5,9);

console.log(result);

HERE,

  • return first_number * second_number; multiplies the values of first_number and second_number then returns the result to the function caller.
  • let result = product(5,9); defines a variable result that is assigned the value of the function product which accepts 5 and 9 as function arguments.
  • console.log(result); prints the result in the terminal

Open the terminal then run the following command

node custom-functions.js

You should be able to get the following result

45

Summary

Functions are reusable pieces of code that perform specific tasks. For example, you can use a function to get the system date and display it. JavaScript supports both built-in and custom functions. Built-in functions come with JavaScript out of the box. Examples of built-in functions include parseInt,encodeURI etc. Custom functions are written by yourself and they are defined using the function keyword followed by the function name, parenthesis and the function code enclosed between the curly brackets. The return statement is used to return a value after executing the function code.

Author: Rodrick Kazembe

Rodrick is a developer who works on Desktop, Web and Mobile Applications. He is familiar with Python, Java, JavaScript, C++, C#, Kotlin, PHP, Python and the list goes on. Rodrick enjoys sharing knowledge especially when it comes to technology.

JavaScript JSON

JavaScript If Statement

Leave A Reply