01. Functions

What is a function?

Functions are block of javascript code that can be executed when called. The block contains a series of statements that perform a specific task.

Functions can take in valid input values known as arguments, and can return the resulting variable as a return statement.

Why use a function?

Functions are useful for abiding to the DRY (don't repeat yourself) principle. You can create a function in one place, and call it from several locations. In programming, this is good practice, as it avoids writing the same chunks of code multiple times. Furthermore, this allows you to better manage your application and prevent bugs, as you won't need to update your logic in multiple places.

Declaring a function

A function is declared with the function keyword, followed by its name and a set of paranthesis.

Just like with other variable names, function names must obey a set of rules.

  1. Functions must be made up of letters, numbers, _ and $.
  2. Functions cannot start with a number.
  3. Functions can't include any spaces or punctuations.
// Function that gets a random number from 1 to 100
function getRandomNumber() {
  var randomNumber = Math.floor( Math.random() * 100 ) + 1;

Function hoisting

Previously we mentioned that JavaScript is a procedural language, meaning it executes code line-by-line. An exception to this methodology is with functions, which incorporate hoisting. In hoisting, the functions are moved to the top of the current scope. This allows functions to be called before they are declared.

Build modern and responsive webpages


Build modern and responsive webpages Try Front-end

This book teaches HTML as if it's for anyone - hobbyists, students, and professionals - and it's full-color throughout. It utilizes information graphics and lifestyle photography to explain the topics in a simple way that is engaging. You can progress through the chapters from beginning to end or just dip into topics of particular interest at your leisure.

$ Check price
29.9929.99Amazon 4.5 logo(926+ reviews)

More Front-end resources

Aching back from coding all day?

Prism Glasses

Aching back from coding all day? Try Back Problems

Ever feel achy from sitting crunched up on your computer table? Try lying down with these optical glasses that allow you to work on your laptop while lying flat on your back. This is the perfect solution with those with limited mobility or those who wish to prevent neck cramps and back strains.

$ Check price
4.454.45Amazon 4 logo(128+ reviews)

More Back Problems resources