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.

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

Build modern and responsive webpages

High Performance Web Sites

Build modern and responsive webpages Try Front-end

Want your web site to display more quickly? This book presents 14 specific rules that will cut 25% to 50% off response time when users request a page. Author Steve Souders, in his job as Chief Performance Yahoo!, collected these best practices while optimizing some of the most-visited pages on the Web.

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

More Front-end resources

Ad