Learning Javascript
Learning Javascript
3
Writing our first code........................................................................................................ 3
Running from an external script....................................................................................4
Why put script in the body?.......................................................................................4
Two Basic Commands We’ll Be Using A Lot................................................................4
alert........................................................................................................................... 4
document.write..........................................................................................................4
Coding..............................................................................................................................5
Variables.......................................................................................................................5
Note about variable format - a mistake I kept making...........................................5
Naming variables...................................................................................................... 6
The semicolon.......................................................................................................6
Arrays........................................................................................................................... 6
Working with example html2.....................................................................................6
Calculating................................................................................................................ 7
Control Structures, Functions, Math and Events..........................................................7
If statements............................................................................................................. 7
Conditionals...........................................................................................................8
Else........................................................................................................................... 8
Else If........................................................................................................................ 8
Comments.............................................................................................................9
Loops........................................................................................................................ 9
While Loop............................................................................................................ 9
Concatenate Alerts..............................................................................................10
Do While Loop.....................................................................................................10
For Loop.............................................................................................................. 10
Math........................................................................................................................ 10
Standard Math Order Of Operation.....................................................................11
Functions................................................................................................................ 11
Debugging...........................................................................................................12
Return..................................................................................................................... 12
A Note About Programming In General...............................................................13
Event Handlers....................................................................................................... 13
Other Events...........................................................................................................14
Bootstrapping..........................................................................................................14
What is bootstrapping..........................................................................................15
Advantages of Bootstrap:....................................................................................15
Header information..............................................................................................15
A Note About formatting document.write................................................................15
Printing Arrays On The Screen...................................................................................16
Properly formatting the array...................................................................................16
Options For Showing The Array On Screen............................................................16
Simple display..................................................................................................... 16
Creating a list display.......................................................................................... 16
Built-In Functions........................................................................................................17
Dot Notation And Brackets.........................................................................................18
Dot Notation............................................................................................................18
Brackets..................................................................................................................18
Built In Math Functions...............................................................................................19
Adding And Removing From Arrays...........................................................................20
.pop......................................................................................................................... 20
.shift........................................................................................................................ 21
.unshift.................................................................................................................... 21
.splice......................................................................................................................21
.slice........................................................................................................................21
Learning Javascript
What is Javascript?
It’s the most popular programming language in the world. It doesn’t need a compiler,
and works completely within the browser. It’s already installed on your Windows
machine. It’s also called a scripting language.
Javascript is NOT Java. It’s as powerful as Java, but they work totally differently.
When you type a search request into Google, and it offers suggestions - it’s getting
those suggestions from a database, and it’s calling that with Javascript. There are
many uses for Javascript, as it’s a very powerful language - you can do pretty much
anything with it.
</body>
</html>
<script>
</script>
Now we add the command “alert”, which brings up a popup box, in between the script
tags:
alert(‘hello from body’);
I can save and run this in Firefox directly from Notepad++, and it works!
We could have also added this script in the head, instead of the body. If we put it in
both places, it will run the head script first, then when you click “OK” on the popup, it will
show the body script popup. So it runs from the top to the bottom.
Running from an external script
We’ll create another document that just contains:
alert(“hello from the script”);
and save it as a javascript (.js) file called sample.js Now can add a call to it in the head
of the original example file, above the other one:
<script src=”sample.js”></script>
Note that, because the sample.js is in the same place as the html file, we don’t need to
include a full path. But if it wasn’t, say it was in a different directory or even someplace
in the cloud, we would need to type in the complete path:
<script src=”c:\mydirectory\myfiles\sample.js”></script>
Now, when we load the .html file into a browser, we get the external popup, the head
popup, and then the body popup.
Also, if there is a lot of code in the head, it may take a lot longer for the page to load.
document.write
This puts text directly into the html. So:
document.write(‘hello from documentwrite’);
will show up where ever it’s been placed in the html. This way, you can call an external
script with a bunch of text in it without cluttering the main document.
Coding
Variables
A variable is a container or holder of data. You give it a name and assign a value to
that name.
But this won’t do anything unless we find a way to use it. So, let’s use the alert
command:
alert(name);
and this will bring up a popup box with “10” as the message.
You can assign a different value to the variable without erasing the line with the original
variable:
name = 10
name = 100
Instead of putting the value on a separate line, it’s more common to combine:
var name = 10;
When assigning a value to a variable, you use either quotes or matched apostrophes
(‘adfaf’) for text, which is called a string. Numbers (called integers) do not need any
qualifier. This is how JS knows the value is a string or a number. “23” or ‘23’ is a string.
23 is an integer.
Naming variables
Often it’s suggested that, when naming variables, the first letter is lowercase. If there is
a second word, that has the first letter uppercase. This is called “Camelcase style”:
nameList myVariable anotherVar
The semicolon
The semicolon lets JS know you’re finished with that variable, so always include it at the
end of a line.
Arrays
An array is used to hold multiple values, so you don’t need to specify each with a
separate “var”.
We begin by using the var command and name the new array. We’ll call it arrayName.
Then we define that name as being an array:
var arrayName = new Array();
So every time we want to use that array, we refer to it by the name arrayName. Now
let’s add values to it by filling in the parenthesis, so the actual line would read:
var arrayName = new Array(10,20,30,40,4000,200);
The comma lets JS know it’s the end of the value, although we don’t need to put it at the
end of the last number.
Now we can use the alert command and call that array:
alert (arrayName);
In order to call a specific value from the array, we use an index. This starts numbering
the values listed at 0, and is used in a bracket within the parenthesis. So, in our
example, to use the value 10 (the first one), the command would be:
alert (arrayName[0]);
Note there is no space between the name and the open bracket.
But it still didn’t work. Looking at the header, I saw there was a reference to a css file,
which was in a css folder in the example directory. Once I changed that to reference it,
the formatting worked:
<link rel="stylesheet" href="./exercise-files/Javascript/practical-app/css/style.css">
Calculating
Hopefully this will be gone over later, but in the second example we gave created and
gave value to variables called var1 and var2. It used the following script:
function addNumbers(){
var calculation = var1 + var2;
document.getElementById('divContent').innerHTML = calculation;
}
</script>
<h1 id="divContent"></h1>
So we used a function called addNumbers (not sure if it’s built in), then used the
document.getElementByld command to assign a name called ‘divContent’, which called
innerHTML (not sure what that is yet) and said it was equal to calculation. Then, it put
that divContent into the page as a header 1 format.
var number1 = 5;
var number2 = 10;
if(number1 < number2) {
alert("something");
}
When this is run, the box will pop up saying “something”. But if number1 was 20
instead of 5, the alert would never get executed.
With the “==” conditional, if the values are the same but one is a string and one is an
integer, it will consider them equal anyway. With the “===” they both have to be exactly
the same, including the type. == will work with 20 and “20”, but === will not.
Else
We may want something to happen when the if statement is not true. Here we use the
“else” statement. This will come after the closing curly bracket of the “if” statement and
have a curly bracket of its own, like this:
}
else {
alert(nothing);
}
Else If
The else if statement can only be used after the if statement (which makes sense), and
before the else statement. It’s testing an alternate “if” condition before the “else” kicks
in. Again, it’s after the if closing curly bracket, and has its own brackets:
var number1 = 5;
var number2 = 10;
if(number1 == number2) {
alert("something");
}
else if(number1 < number2) {
alert("else if")
}
else {
alert("nothing");
}
So in this case, the popup “else if” would show.
If we add two new variables, number3 = 100 and number4 = 200, and make the else if
statement else if(number3<number4), then “else if” would also show. So the else if
statement doesn’t have to involve the same variables as the if statement. The code
runs from top to bottom, so it would check the if statement first, then the else if, then fall
back to else.
Comments
It’s a good idea to comment your work. “//” allows you to comment on that specific line.
It can be put in after a line of code:
alert(“some stuff”) // this is an alert comment
Or on it’s own:
// the following line will generate an alert box
If you forget to close the comment, EVERYTHING after /* will be considered a comment
- so your code won’t work.
Loops
While Loop
Loops repeat an action over and over until a condition is met. The syntax is similar to
an if statement:
while(this condition is true or false) {
repeat this action over and over again
}
We initialize this by using: var counter = 0; //usually you would use a zero
now we start that loop: while(counter < 5) { //notice there is no “;” between “)” and “{“”
alert(counter)
}
Now, note that the above program will never increment, so you’ll get a million alerts. So
we need to increment the counter, by adding (under alert) - counter = counter + 1.
Make sure it’s BEFORE the closing curly bracket. Now, it will loop and show a popup of
0, then 1, then 2, etc. until it reaches 5, at which point it will stop and the last thing it
shows will be 4. If you wanted it to print at 5, you would use “<=”.
Concatenate Alerts
If we wanted the alert to show text and the number, we need to concatenate. We do
this by adding a plus sign: alert(“While Loop: ” + counter);
Do While Loop
Unlike the While loop, which checks for the condition, the Do loop executes before it
checks for the condition:
var i = 0;
do {
alert("Do While Loop: " + i);
i++;
|}
while(i<5);
The condition is stated AFTER the closing curly bracket. In our example, it will execute
the While loop first, and then the Do While loop.
For Loop
The For Loop is probably the most commonly used, because you can put all the
arguments in one line:
for(var f = 0; f < 5; f++){
alert("For Loop: " + f);
}
If you are cutting and pasting or modifying previous commands, make sure that you
update ALL the variables. For example, in this one I changed the “i” to “f”, but forgot to
change the alert(“For Loop: “ + i); so it didn’t work.
Math
JS follows standard math order of operation rules. Also note that the alert function can
perform math functions: alert(10 + 10) will result in a popup box that says 20.
If we make variables number1 = 10 and number2 = 10, we can then make a variable
called calculation that would be:
var calculation = number1 + number2
Since it follows the math order of operation, multiplication is before addition, and
parenthesis is before multiplication. So:
var calculation = 10 + 10 * 5 would equal 60, but (10 + 10) * 5 would equal 100.
Standard Math Order Of Operation
Do what is possible within parentheses first, then exponents, then multiplication and
division (from left to right), and then addition and subtraction (from left to right). If
parentheses are enclosed within other parentheses, work from the inside out.
Functions
Functions allow us to organize what would otherwise be messy code. Function is a
reserved keyword. As with variables, the word function is followed by a name of your
choosing, followed by parenthesis (which could contain parameters, but could also be
empty), and then you open a set of curly brackets.
In other words, it’s formatted just like a variable. The commands the function uses go
between the curly brackets. To use it, you type the name of the function and
parenthesis followed by a semicolon.
function addNumbers() {
var number1 = 10;
var number2 = 20;
var calculation = number1 + number2;
document.write(calculation);
}
addNumbers();
We can put “addNumbers” anywhere in the document, as many times as we need to,
and as long as it’s between script tags it will run that function.
But what if we don’t want to have to go back and change number1 and/or number2
each time we need different numbers?
addNumbers(10, 20);
We took out the var declaration for number1 and number2 because it’s included in the
function declaration, and can be changed “on the fly”.
Debugging
Let’s say we wrote:
function addNumbers(number1, number1) {
by accident. It wouldn’t work, but we can find out what’s wrong by using a debugger. In
Chrome, you right click on the page and choose “Inspect”. At the bottom right, we can
see the Console, which will have the message:
at addNumbers (Functions.html:15)
at Functions.html:20
So it actually tells us that number2 isn’t defined, and it points to line 15 - where number2
is being called (var calculation = number1 + number2).
In Firefox, we again right click and choose Inspect Element, then click on the Console
tab. We get:
ReferenceError: number2 is not defined [Learn More]
On the rights side it tells us where the number2 error is, and it has a clickable link that
will tell more about the error.
Return
Expanding on the Functions, we can try substituting the reserved keyword “return” for
the static declaration “document.write”. The return statement stops the execution of a
function and returns a value from that function. We can use the function as a variable,
and then use that for whatever we want - for example, with “alert” instead of
“document.write”:
function addNumbers() {
var number1 = 10;
var number2 = 20;
var calculation = number1 + number2;
return calculation;
Now the variable “cal” is displayed, using the variable “result” plus 1000.
Event Handlers
Events are things like mouse clicks, or mouse drags, a web page has finished loading,
an input field was changed, a button was clicked, or other actions. By Googling
“javascript event handlers”, we can easily find hundreds of them. W3schools.com has
lots of information.
To format this, we’ll use bootstrapping (see below), which is covered in another course.
In the header we add:
<link rel=”stylesheet”
href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css”>
Now we add the event handler. This is going to call the JS alert box, even though we’re
not in between the script tags:
<button onclick="alert('Hello');" class=”btn btn-primary”>Click Here</button>
Note that the Hello text uses single quotes, not double, because the double quotes are
being used by “alert”.
Now, a better way would be to create an ID that we can use in the script portion. So we
create another button:
<button id=”button2” class=”btn btn-success”>Click Here2</button>
document.getElementById(‘button2’).onclick = function() {
};
Notice the “;” after the closing curly bracket? That’s because the whole thing, starting
with “document.getElementById” is a statement. Therefore, it has to be closed with “;”
document.getElementById(‘button2’).onclick = function() {
clickMeFunction()
};
So now we have to actually make the function, which we do below the }; section.
function clickMeFunction() {
alert(“Hello from click me!”);
}
The advantage of this is that you can call your functions from an external file, and not
have to declare them every time within the HTML - which will make it big and messy.
Imagine having 40 buttons and having to declare all of them with functions (example 1)
or creating the buttons and calling the function from an external script. The latter is
better, cleaner, and easier to read.
Other Events
Let’s use the same script as we did before, and now add another button:
So now, we’re using the “onmouseover” event. We can add dozens, even hundreds, of
events.
Bootstrapping
Bootstrap is a free front-end framework for faster and easier web development.
What is bootstrapping
Bootstrap includes HTML and CSS based design templates for typography,
forms, buttons, tables, navigation, modals, image carousels and many other, as
well as optional JavaScript plugins
Bootstrap also gives you the ability to easily create responsive designs
Advantages of Bootstrap:
Easy to use: Anybody with just basic knowledge of HTML and CSS can start
using Bootstrap
Responsive features: Bootstrap's responsive CSS adjusts to phones, tablets, and
desktops
Mobile-first approach: In Bootstrap 3, mobile-first styles are part of the core
framework
Browser compatibility: Bootstrap is compatible with all modern browsers
(Chrome, Firefox, Internet Explorer, Safari, and Opera)
More information, including tutorials, samples, full scripts, etc. are available here:
https://www.w3schools.com/bootstrap/default.asp
Header information
Their site says you have to include this in the head section:
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
But they also say you need this. Mine worked without it, but for reference:
var count = 0;
document.write(count + “<br>”);
count++;
}
You can also use .css formatting with the “class” statement:
document.write("<span class='red'>The score you entered is: " + score + ". Your letter
grade is: A!</span>");
If using HTML commands like <li>, and you create a variable such as:
var names = new Array ('Edwin', 'Russ', 'Joe', 'Mary', 'Dave', 'Lori');
Notice a few things: we start with “var”, the name of the new array (names), then it’s
“new Array”, not “newArray”. We can use either apostrophes or quotes for the text
names, and don’t forget the semi-colon at the end of the line. If we had numbers in the
array, they wouldn’t need quotes.
Simple display
If we then type “alert(names);”, it will show all of them. If we add the bracket and
choose a specific number, and the numbering starts at zero, it will show only that name.
So “alert(names[1]); will show Russ.
To show them as a list, we need to create a loop. We start by creating variable for the
index: “var i = 0;”
So we said “while i is less than the value of the length of names (new command here,
“variable name.length so you don’t have count up all the items in the array!),
document.write will list each item. We have to add “<li>” because that goes along with
the <ul> command, so to do that we have to put it with leading and trailing apostrophes
(it’s a text item) and concatenate it with the plus sign.
We use the “i++” to increment the value of the index by one each time the loop runs.
So to sum up:
1. define the array and the items in it using the variable command
3. create a while loop and make the value of what is “doing something” (i) to be “while
it’s less than the number of items in the array”
4. Define what’s going to happen during that “while” time, which is using document.write
to put something on the screen. In this case, it will be a bulleted item from the array, at
the position that “i” is set at
5. increment “i”
This loop runs until the value of “i” is greater than the number of items in the array.
Built-In Functions
JS has a number of built in functions. One site that has a good list is at:
https://www.tutorialspoint.com/javascript/javascript_builtin_functions.htm
The list calls them methods. Note that “methods” are the same as functions. We’ll use
the function to get the date and the seconds. Note how it has to be constructed,
beginning with a variable that uses the built in date function.
document.write(seconds);
Dot Notation And Brackets
Dot Notation
In the previous example, we used dot notation: var seconds = time.getSeconds. The
variable time had been defined as the built in function Date. So we created a variable
called seconds that used the property GetSeconds of the function (from the built in
function) Date.
let obj = {
cat: 'meow',
dog: 'woof'
};
console.log(sound);
// meow
Notice the fifth line where we’re using dot notation: let sound = obj.cat;. This is an
example of dot notation. You can access properties on an object by specifying the name
of the object, followed by a dot (period) followed by the property name. This is the
syntax: objectName.propertyName;.
When working with dot notation, property identifiers can only be alphanumeric (and _
and $). Properties can’t start with a number. They can’t contain a variable. This can be
an issue, which is why we also use brackets.
Brackets
Let’s use the same example, but with brackets:
let obj = {
cat: 'meow',
dog: 'woof'
};
console.log(sound);
// meow
We’ve used this in arrays, such as the “displaying list arrays” section above:
document.write(‘<li>’ + names[i] + ‘</li>’);
but it can also be used with objects. When working with bracket notation, property
identifiers only have to be a String. They can include any characters, including spaces.
Variables may also be used as long as the variable resolves to a String. Dotted
notation can’t do that, it has to follow certain formatting rules noted above.
Perhaps most importantly, we can now use variables to access properties in an object.
It’s important the variable you are using references a String.
let obj = {
cat: 'meow',
dog: 'woof'
};
console.log(sound);
// meow
Although we said let sound =obj[dog];, we made dog a variable that’s actually equal to
cat. So now there isn’t a property name that would equal dog: ‘woof’ anymore. With dot
notation, again, the property identifier can’t contain a variable.
All properties and methods of Math are static. You refer to the constant pi as Math.PI
and you call the sine function as Math.sin(x), where x is the method's argument.
Constants are defined with the full precision of real numbers in JavaScript.
There are a number of built in methods for Math. We’ll use round to get the rounded
value of a “floating number”, one that has a decimal place value. An integer doesn’t.
Notice we use dot notation between Math and the method, and the value can be a
variable (number) or we could have used an actual value (10.4).
Let’s use another one. To find the exponential value of a number, say 24 to the 8 th
power, we use the method “pow”.
There is also a list, along with a full website of Javascript (and other languages) tutorials
at https://www.tutorialspoint.com/javascript/javascript_math_object.htm
cars[0] = “BMW”;
cars[1] = “Mercedes”;
cars[6] = “Volkswagen”;
Notice that we didn’t have to put the index in order. If we add alert(cars); it will show:
BMW,Mercedes,,,,Volkswagen
.pop
To remove the last element in an array, we use the command “pop”. So it would be
cars.pop();
To add an element, we use the “push” command. It can have more than one value, so
we could write
cars.pop(“Ford”, “GM”)
BMW,Mercedes,,,,Volkswagen,Ford,GM
.shift
By using the command “shift”, we can skip the first item in an array:
var cars = [“BMW”, “Mercedes”, “Honda”, “Datsun”]; \\ Don’t forget, it’s brackets, not ()
cars.shift();
alert(cars);
.unshift
To add to the beginning, we use “unshift”:
cars.unshift(“Hyundai”, “Ford”);
.splice
By using “Splice”, we can add, remove, and specify where:
would put Dog and Cat between Mercedes and Honda. Remember an array counts
from 0, so BMW is 0, Mercedes is 1, so it puts it where Honda was - position 2.
would remove Honda and Datsun and put dog and cat there.
.slice
Slice allows us to take elements from another array to put in our array. First, we’ll
define the new array as fancyCars. Then, we’ll take from the cars array:
alert(fancyCars);
This takes the elements from array “cars” starting with 2 and up to 4, so in our case it
would be Honda and Datsun. If we added “Ford” to the cars array, it wouldn’t take it,
because that would be element #5. We’d have to change the command to:
cars.slice(2,5);
Using a for loop for user input
Let’s say we have an array that lists cities. We want the user to type in his city and we
want it to match one of the entries in our array.
We can start by defining the variable for the array and what it has in it:
Now we use the prompt command to bring up a box for the user to type in:
But now what? How do we proceed to check the input against our array? And, when it
does, what then?
if(userInput == bestCities[i]); {
So we used a random name for the index variable (“i”), set it to zero, then said as long
as it was less than or equal to the length of bestCities, it should increment to the next
value. We used “bestCities.length” because we might not know how long the array is.
It could be a dynamic array that increases in size. We happen to know it’s equal to 6,
so we could have said “i <= 6”, but this way is more realistic.
Then we check to see IF the user input is equal to one of the elements in bestCities,
starting with element zero. If not, it checks element 1, then 2, etc. When it matches, it
shows the alert message. If it doesn’t match, nothing happens on the user end unless
we add an “else” statement:
Notice the value doesn’t use quotes. A Boolean is either true or false.
Then we put “matchFound = true;” right above the alert(“That’s a great city!”);
So we have it set up. Now we do an “else” statement, but to prevent a loop, we add a
break statement:
break;
More Resources
The first place to go for more information is the developers themselves:
https://developer.mozilla.org/en-US/docs/Web/JavaScript