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

The Modern Web

Build modern and responsive webpages Try Front-end

The Modern Web will guide you through the most important tools of device-agnostic web development, including HTML5, CSS3, and JavaScript. The plain-english explanations and practical examples emphasize the techniques, principles, and practices that you'll need to easily transcend individual browser quirks and stay relevant as these technologies are updated.

$ Check price
34.9534.95Amazon 4.5 logo(30+ reviews)

More Front-end resources

Aching back from coding all day?

Foam Seat Cushion

Aching back from coding all day? Try Back Problems

This foam seat cushion relieves lowerback pain, numbness and pressure sores by promoting healthy weight distribution, posture and spine alignment. Furthermore, it reduces pressure on the tailbone and hip bones while sitting. Perfect for sitting on the computer desk for long periods of time.

$ Check price
99.9599.95Amazon 4.5 logo(9,445+ reviews)

More Back Problems resources