Loops execute a block of code statements between two braces { } repeatedly as long as a condition is true. When the condition for looping becomes false, the loop ends and the program continues past the loop block. There are two main forms of loops: while and for. Generally, it's possible to write the same loop in either form to receive the same logical behavior:
// Computes the sum of consecutive numbers between min and max inclusively
function whileLoop(minVal, maxVal) {
let sum = 0;
let i = minVal;
while (i <= maxVal) {
console.log(`Adding ${i} to ${sum}...`);
sum += i;
i += 1;
}
alert("The sum of consecutive numbers between " + minVal + " and " + maxVal + " is " + sum);
}
// Computes the sum of consecutive numbers between min and max inclusively
function forLoop(minVal, maxVal) {
let sum = 0;
for(let i = minVal; i <= maxVal; i += 1) {
console.log(`Adding ${i} to ${sum}...`);
sum += i;
}
alert("The sum of consecutive numbers between " + minVal + " and " + maxVal + " is " + sum);
}
var candies = ["SweeTarts", "Milk chocolate peanut butter cups", "Twix"];
function printCandies() {
for(let i = 0; i < candies.length; i++) {
console.log("I love eating " + candies[i]);
}
}
Arrays in JavaScript have several built-in methods and properties, such as:
Arrays are also the return value for certain functions, such as the string's split() method. See the date/time parser demo.
You can use loops and arrays to programmatically generate HTML that would take a long time to write by hand. See the cards demo
Demo: Building a form
Input elements are a standardized way to
receive values from the user of an expected type, such as a number for an item quantity in a shopping
cart or a date/time for an appointment. They aid in web design by providing a level of validation. For
example, you can only enter numbers into an input element with type="number"
as one
of its attributes. Generally, the .value property of an input element in JavaScript is presented as a
string, so you still have to convert it to a number before using it with arithmetic expressions.
Otherwise, the content in an input element's value is ready to use as a string. Try entering an email
address in the box and clicking the submit button.
HTML Forms are container elements that
organize a number of input elements into a single context. A form can be "submitted" by pressing
enter in one of its input fields or by using an <input> element with an attribute
type="submit"
. When a form is submitted, the browser collects the ids and values of
the form's input elements and submits them to the server for processing. It's possible to use
PHP on the server side and access the form's data using input ids. The default behavior for a form
submission means that the page will appear to be refreshed, which in turn erases the form content.
It's possible to override this behavior by defining a function to be called when the form is
submitted: This function should have an argument to represent the submit event. Then, inside the
function that handles the form submission, you can prevent the default behavior from occurring:
<form onsubmit="return handleFormSubmission();">
<input type="text" id="name">
<input type="submit" value="Submit form">
</form>
function handleFormSubmission() {
//e.preventDefault(); // keeps the page from refreshing, also prevents submitting form data to server
let name = document.getElementById("name").value;
alert(`Your name is ${name}`);
return false;
}
Try it:
We're using multiple JS functions to handle input validation - one for each input field in the form, including the date and time. If something is wrong with the input, we make an error message visible with the specific problem. When the input passes validation, the error message goes away and the form submits.
You can set just about any HTML element to be editable by adding the attribute contenteditable="true"
- this even works on the <body> tag!
. Here's an example of a div next to a textarea. By default, a div is not editable, while a textarea is expected to be used for writing text. There are a few primitive buttons for text formatting, and some JavaScript functions that try to keep the two elements in sync. Try them out!
Demo: Text editor with a div
Demo: Live html editor
Walkthrough of demo: Live html editor