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;
  alert(randomNumber);
}

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

Responsive Typography

Build modern and responsive webpages Try Front-end

Responsive web design helps your site maintain its design integrity on a variety of screen sizes, but how does it affect your typography? With this practical book, graphic designers, web designers, and front-end developers alike will learn the nuts and bolts of how to get the best appearance from type without sacrificing performance on any device.

$ Check price
24.9924.99Amazon 4.5 logo(3+ reviews)

More Front-end resources

Aching back from coding all day?

Acupressure Mat & Pillow

Aching back from coding all day? Try Back Problems

Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.

$$ Check price
144.87144.87Amazon 4.5 logo(1,890+ reviews)

More Back Problems resources

Ad