JavaScript Coding Basics

Setting Up Document

To set up a section of document for JavaScript "<script>" tags must be placed around the JS code:

<Script>
[JavaScript Code Here]
</Script>


Outputting Messages On Screen

Displaying Messages on a web page can be done by using "document.write":

<Script>

document.write("Hello World");

</script>


If you want an alert pop up box to display above the browser window, "alert" can be used:

<Script>

alert("Hello World");

</Script>


Accepting Inputs

If you want to accept data that has not been hard coded, a form with "input id" can be used:

<script>

<form>
Enter data here
<input id="userInput", type="string", name="userString">
[a button that saves or outputs the data would be required here]
</form>

</script>


Variables

Variables can be set up and used using command "var" (followed by what you want the variable to be):

<script>

var i = "hello";

alert(i);

</script>


Arrays

Arrays can be stored in variables, similar to python:

<script>

var typesOfCar = ["Audi", "BMW", "VW", "Seat"]

</script>


For Loops

For loops can be used to repeat section of code without having to write the line over and over again, outputting the contents of a array is a good example. To output the array above, instead of having to write:

<script>

var typesOfCar = ["Audi", "BMW", "VW", "Seat"]

document.write(typesOfCar[0])
document.write(typesOfCar[1])
document.write(typesOfCar[2])
document.write(typesOfCar[3])

</script>

you could write:

<script>

for (i = 0; i < typesOfCar.length; i++) {
cars+= typescOfCar[i] + "<br>";
}

document.write(cars)

</script>

Comments

Popular posts from this blog

CPU Fetch-Decode-Execute Cycle

Scheduling

Utility Software