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.
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.
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.
// Function that gets a random number from 1 to 100
function getRandomNumber() {
var randomNumber = Math.floor( Math.random() * 100 ) + 1;
alert(randomNumber);
}
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.
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 priceRelieve 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 priceAd