Lesson 8 — Practical Exercise

A simple intro to JavaScript

Previous :: Next

Getting Functional

Open up Brackets and create a new file in the JavaScript folder by creating a new file. ( ⌘ + N / Cmd + N) Then rename the file to math.html.

Type in this code into the file and then save the file:

<script>
/* This program will use functions to do math!
*/
var word1 = prompt("Enter a word", "Hello"); //Has the user enter a word, otherwise sets Hello
var word2 = prompt("Enter another word", "World"); //Has the user enter a word, otherwise sets world

alert("2 + 3 = " + additon(2,3)); //This will show: 2 + 3 = 5
alert("2 - 3 = " + subtraction(2,3)); //This will show: 2 - 3 = -1
alert(word1 + " + " + word2 + " = " + additon(word1,word2)); //This will combine your two wrds together
var answer = confirm("Are you hyped?"); //Checks if the user is hyped

if (answer){ // Responds to the answer
alert("Come aboord the hype train!!");
}else{
alert("Well I didn't want you anyway"); //if I used ' for the string here, it wouldn't work because there is a contraction
}

function additon(a,b){
var c;

if(typeof a === "number"){ // Checks if a is a number
c = a + b;
} else {
c = String(a) + String(b); //C hanges a and b to a string before adding them together
}

return c // returns c so that it can be printed out
}

function subtraction(a,b){
var c = a - b; // subtractio
return c; // returns c so that it can be printed out
}
</script>

As you can see, the comments in my code explain the process through which it runs, so that I don’t have to go line by line to explain it, rather it is self-explanatory.

Previous :: Next