Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Learning Javascript

Basic course on Javascript, from notes I took.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Learning Javascript

Basic course on Javascript, from notes I took.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

What is 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.

We can use a simple code editor, even Notepad, to write it.

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.

Writing our first code


I’ll be using Notepad ++ to write code. We’ll create a file called example.html. First we
put in the usual template information:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8”>
<title>Document</title>
</head>
<body>

Leave a few lines

</body>
</html>

Now, in the body section, we add a script tag:

<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.

If it was moved to the body, it would show last.

Why put script in the body?


If the javascript doesn’t run in the head for some reason (like a blocker), the content in
the page won’t show. For that reason, it may be better to put it at the bottom of the html
body.

Also, if there is a lot of code in the head, it may take a lot longer for the page to load.

Two Basic Commands We’ll Be Using A Lot


alert
We’ve already used this, it creates a popup window with a message. If a popup blocker
is activated, it won’t show anything. Alerts will not execute code, so
alert(“<h1>test</h1”); will show a popup that actually shows exactly that, not a line in H1
format.

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.

“var” is a reserved keyword, and it’s used to create a variable. So:


var name;

creates a variable called “name”.

We assign a value to it by typing


name = 10; (for example).

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

The popup will show the value 100 instead of 10.

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.

Note about variable format - a mistake I kept making


I seem to keep forgetting this, but variables DO NOT use (). They use =. So if you want
to add two number (var number1 = 10, var number2 = 20) with a variable named
“result”, then it’s coded:

var result = number1 + number2;

NOT var result(number1 + number2);


As many other parts of the code DO use “()”, this is an important distinction.

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

You cannot put a zero in front of a variable.

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.

Working with example html2


This is an example file included with the course. We put in three variables, then call
them from a document.write statement. I saved it in the root directory of the course
folder, instead of the example folder. However, when I ran it, it didn’t look right - all of
the formatting for the sidebar (clickable boxes) was gone. I saw at the bottom there was
a reference to a .js file in the js directory of the example files, so I changed the path to
reflect that:
<script src="./exercise-files/Javascript/practical-app/js/myscript.js"></script>

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.

Control Structures, Functions, Math and Events


If statements
If statements let you test a condition, and if it passes, then an action gets executed. For
example:

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.

The format will be:

if(something meets this) {


this happens(and parameters go here);
}
Conditionals
We’ll be going over this more later, but in conditional statements there are these
conditional operators:
== equal
=== exactly equal
< less than
> greater than
!== not equal

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

To comment multiple lines, you use /* to open, and */ to close:


/* this is a comment about how I came up with this code
It was a bright sunny day, the dogs were singing,
the birds were howling, and the moon was shining bright */

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 “<=”.

The shorthand for counter = counter + 1 is: counter++;

So you DON’T write “counter = counter++;” you just write “counter++;”

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

This would work with multiplication, division, subtraction, etc.

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?

We can change the code like this:

function addNumbers(number1, number2) {


var calculation = number1 + number2;
document.write(calculation);
}

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:

Uncaught ReferenceError: number2 is not defined

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;

var result = addNumbers();


alert(result);

We can even go further and use “result” in a variable:

var result = addNumbers();


var cal = result + 1000;
alert(cal);

Now the variable “cal” is displayed, using the variable “result” plus 1000.

A Note About Programming In General


Programming usually has three processes - Input, Process, and Output. Also, values
are assigned from right to left: var result = addNumbers(); means the value on the right
(addNumbers) is being assigned to the variable “result”.

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.

But we’ll start off with just one, which is “onclick”.

Let’s create a button using the HTML “button”:


<button>Click Here</button>

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”>

Then, change the button tag to <button class=”btn btn-primary”>Click Here</button>

That will format the button nicely.

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>

Now we use a prebuilt function (case sensitive) called document.getElementById()


//Note that it’s document followed by a period, not a space.

So ours will read document.getElementById(‘button2’) \\Note the single quotes


Now we use a “dot notation”, which is just adding a period after the closing parenthesis
and then the command:
document.getElementById(‘button2’).onclick

Now we have to make onclick do something, so we have to assign it a function. So:

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 “;”

Now we name the function, let’s call it clickMeFunction()

So the whole thing looks like this:

document.getElementById(‘button2’).onclick = function() {
clickMeFunction()
};

So now we have to actually make the function, which we do below the }; section.

Let’s make it give an alert, so we create it as we did other functions:

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:

<button onmouseover="alert('Hello from Button 3')" class="btn btn-info">Hover Over


Me</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:

<!-- jQuery library -->


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></
script>

A Note About formatting document.write


You can add HTML formatting in a document.write statement, as follows:

var count = 0;

while (count < 5) {

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>");

So “red” can be set up to have a color, size, background, etc.

If using HTML commands like <li>, and you create a variable such as:

var message = “hello”;

the formatting will be:

document.write(“<li>” + message + “</li>”);

Printing Arrays On The Screen


Properly formatting the array
Let’s create the array:

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.

Options For Showing The Array On Screen

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.

Creating a list display


If we want it to show as a list, we have to do a few things. First, we want to enclose the
Javascript within “ul” tags for an unordered list. This means it won’t be numbered, and
you have a choice of whether it has a bullet (default, called a “disk”), a square, a circle,
or nothing. The command is <ul style=”list-style-type:disc”> (or whatever style).

To show them as a list, we need to create a loop. We start by creating variable for the
index: “var i = 0;”

Since there are six items, we create a “while”loop:

while(i < names.length) {


document.write(‘<li>’ + names[i] + ‘</li>’);
i++;
}

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

2. define the index with a starting count of 0

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.

var time = new Date();

Now we get the seconds, calling on our “time” variable:

var seconds = time.getSeconds();

We can then display it with:

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.

Here is an example of how this works:

let obj = {
cat: 'meow',
dog: 'woof'
};

let sound = obj.cat;

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'
};

let sound = obj[“cat”];

console.log(sound);
// meow

So the syntax is similar: objectName[“propertyName”];

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'
};

let dog = 'cat';


let sound = obj[dog];

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.

For bracket notation, property identifiers have to be a String or a variable that


references a String. It is okay to use variables, spaces, and Strings that start with
numbers.

Built In Math Functions


First of all, there is a global object actually called “Math”. It is NOT a constructor.
What’s a constructor? Rather than explain here, it’s explained as clearly as possible
(not very) at https://content.pivotal.io/blog/javascript-constructors-prototypes-and-the-
new-keyword. That webpage has also been saved. Note that constructors have the
first letter capitalized, as opposed to variables. Although it isn’t a constructor, Math is
also capitalized.

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.

var number = 10.4;


var roundNumber = Math.round(number);
alert(roundNumber);

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”.

var number2 = Math.pow(24, 8);


alert(number2);

The methods, with examples, can be found listed at https://developer.mozilla.org/en-


US/docs/Web/JavaScript/Reference/Global_Objects/Math

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

Adding And Removing From Arrays


We’ll start by defining the array using the index - brackets - for each element:

var cars = []; //that’s [ ], but it looks like a box here

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();

and the alert result would be BMW,Mercedes,,,,,

To add an element, we use the “push” command. It can have more than one value, so
we could write

cars.pop(“Ford”, “GM”)

and if we removed the pop command the alert result would be

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);

And the resulting alert is Mercedes, Honda, Datsun. It skipped BMW.

.unshift
To add to the beginning, we use “unshift”:

cars.unshift(“Hyundai”, “Ford”);

And the result is:

Hyundai, Ford, Mercedes, Honda, Datsun

.splice
By using “Splice”, we can add, remove, and specify where:

cars.splice(2, 0, “Dog”, “Cat”);

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.

cars.splice(2, 2, “Dog”, “Cat”);

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:

var fancyCars = cars.slice(2,4);

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:

var bestCities = ["New York","Los Angeles","San Francisco","Austin","New


Orleans","Memphis" ];

Now we use the prompt command to bring up a box for the user to type in:

var userInput = prompt("What is your city?");

But now what? How do we proceed to check the input against our array? And, when it
does, what then?

We’ll start by defining the index:

for(var i = 0; i <= bestCities.length; i++) {

if(userInput == bestCities[i]); {

alert(“That’s a great city!”);

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:

alert(“That’s a great city!”);


} else alert(“I don’t know that one…”);
}

Flags and Boolean Values


Working with the last program, we’re going to add a Boolean value under the prompt
(“What is your city?”);
var matchFound = false;

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:

} else alert(“I don’t know that one…”);


}

break;

Otherwise, the alert would keep coming up.

More Resources
The first place to go for more information is the developers themselves:

https://developer.mozilla.org/en-US/docs/Web/JavaScript

You might also like