Basic JavaScript Syntax

Functions

What are Functions?

In JavaScript, functions are objects because they can have properties and methods. What distinguishes them from other objects is that functions can be called. A JavaScript function is a block of code designed to perform a particular task perform a particular task and the function is executed when it is called. Functions can be built-in or user defined.

Example of a user defined function:

JavaScript example of user defined function.
Image source: N.Dobbin (for HyperionDev Course IFS L4T15: JavaScript Refresher, 2022)

Built-in functions

JavaScript has a number of standard, built-in objects with methods and properties. Some of these are described below:

  • charAt() - returns a character in a string at the given index
  • indexOf() - returns the index of a the first occurrence of a character in a string
  • charCodeAt() - returns the ascii number of the character at the given index in a string
  • fromCharCode() - returns the character of the given ASCII number
  • replace() - replaces a matched substring with a new substring
  • split() - splits a string into an array of substrings
  • toUpperCase() - returns the given string all in upper case
  • toLowerCase() - returns the given string in all lower case
  • join() - opposite of split(). Joins all array elements into a string
  • pow() - returns a base to the exponent power
  • min() - returns the smallest valued element
  • max() - returns the largest valued element
  • round() - returns a number rounded to the nearest integer

You can find more built in methods from the w3schools reference guide .





Practice what you've learned!

This example is a function called calculateTotal(). The function uses a for loop to prompt a user to input any number 5 times. Each time the user enters a number, it is stored in an array. The function then calculates the sum (total) of the inputted numbers by using a while loop and adds the output to the <p> tag with an id of functionExample in the HTML file.

HTML file: the onclick event defined in the "Try this function!" button element below, calling calculateTotal() function.

HTML code example of an onclick event that calls a JS function.
Image source: N.Dobbin (for HyperionDev Course IFS L4T15: JavaScript Refresher, 2022)

JS file: the calculateTotal() function is called when the event is triggered (i.e. the button is clicked).

JavaScript code example of a function to calculate the sum of an array.
Image source: N.Dobbin (for HyperionDev Course IFS L1T10: JavaScript Functions, 2022)
Try using this function by clicking the button below.
To see what's going on behind the scenes, right-click anywhere on the page and click inspect.