Core Objects


Chapter: 37

Arrays 


JavaScript Arrays


Arrays store multiple values in a single variable.

To store three course names, you need three variables.
var course1 ="HTML";
var course2 ="CSS";
var course3 ="JS";
JS
But what if you had 500 courses? The solution is an array
var courses = new Array("HTML", "CSS", "JS");
JS
This syntax declares an array named courses, which stores three values, or elements.



Accessing an Array


You refer to an array element by referring to the index number written in square brackets.
This statement accesses the value of the first element in courses and changes the value of the second element.
var courses = new Array("HTML", "CSS", "JS");
var course = courses[0]; // HTML
courses[1] = "C++"; //Changes the second element
JS
[0] is the first element in an array. [1] is the second. Array indexes start with 0.

Accessing an Array

What is the output of this code? var arr = new Array(3, 6, 8); document.write(arr[1]);


Accessing an Array


Attempting to access an index outside of the array, returns the value undefined
var courses = new Array("HTML", "CSS", "JS");
document.write(courses[10]);
JS
Our courses array has just 3 elements, so the 10th index, which is the 11th element, does not exist (is undefined).

Accessing an Array

What is the result of trying to reference an array member which does not exist?

undefined
false
0
null

Chapter: 38

Other Ways to Create Arrays


Creating Arrays


You can also declare an array, tell it the number of elements it will store, and add the elements later.
var courses = new Array(3);
courses[0] = "HTML";
courses[1] = "CSS";
courses[2] = "JS";
JS
An array is a special type of object.
An array uses numbers to access its elements, and an object uses names to access its members.

Creating Arrays

Please insert the missing characters to output the third member of the array:

document.write(example
);

Creating Arrays



JavaScript arrays are dynamic, so you can declare an array and not pass any arguments with the Array() constructor. You can then add the elements dynamically.
var courses = new Array();
courses[0] = "HTML";
courses[1] = "CSS";
courses[2] = "JS";
courses[3] = "C++";
JS
You can add as many elements as you need to.

Array Literal


For greater simplicity, readability, and execution speed, you can also declare arrays using the array literal syntax.
var courses = ["HTML", "CSS", "JS"];
JS
This results in the same array as the one created with the new Array() syntax.
You can access and modify the elements of the array using the index number, as you did before.
The array literal syntax is the recommended way to declare arrays.

Creating Arrays

By entering var example = new Array(); we create an empty array which can be filled...

anytime later
just after it
nevermore

Chapter: 39

Array Properties & Methods


The length Property


JavaScript arrays have useful built-in properties and methods.

An array's length property returns the number of it's elements.
var courses = ["HTML", "CSS", "JS"];
document.write(courses.length);
JS
The length property is always one more than the highest array index.
If the array is empty, the length property returns 0

The length Property

Array has the "length" property, because it is:

a variable
a function
an object

Combining Arrays


JavaScript's concat() method allows you to join arrays and create an entirely new array.

Example:
var c1 = ["HTML", "CSS"];
var c2 = ["JS", "C++"];
var courses = c1.concat(c2);
JS
The courses array that results contains 4 elements (HTML, CSS, JS, C++).
The concat operation does not affect the c1 and c2 arrays - it returns the resulting concatenation as a new array.

Combining Arrays

The "concat" method takes two arrays and:

compares their members
combines them in one new array
outputs them to the screen

Chapter: 40

Associative Arrays


Associative Arrays


While many programming languages support arrays with named indexes (text instead of numbers), called associative arrays JavaScript does not.
However, you still can use the named array syntax, which will produce an object.
For example:
var person = []; //empty array
person["name"] = "John";
person["age"] = 46;
document.write(person["age"]);
JS
Now, person is treated as an object, instead of being an array.
The named indexes "name" and "age" become properties of the person object.
As the person array is treated as an object, the standard array methods and properties will produce incorrect results. For example, person.length will return 0.

Associative Arrays

In associative arrays, index numbers are replaced with:

variable names
functions
constants
strings

Associative Arrays


Remember that JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.
It is better to use an object when you want the index to be a string (text).
Use an array when you want the index to be a number.
If you use a named index, JavaScript will redefine the array to a standard object.

Associative Arrays

In order to use associative arrays, the "associated" name is put in:

parentheses ( )
curly braces { }
brackets [ ]

Chapter: 41

The Math Object


The Math Object


The Math object allows you to perform mathematical tasks, and includes several properties.contentImageFor example:
document.write(Math.PI);
JS
Math has no constructor. There's no need to create a Math object first.

The Math Object

In the Math Object, which of the following constants does NOT exist?

Math.ABC
Math.PI
Math.E

Math Object Methods


The Math object contains a number of methods that are used for calculations:contentImageFor example, the following will calculate the square root of a number.
var number = Math.sqrt(4);
document.write(number);
JS
To get a random number between 1-10, use Math.random(), which gives you a number between 0-1. Then multiply the number by 10, and then take Math.ceil() from it: Math.ceil(Math.random() * 10).

Math Object Methods

In the Math Object, which of the following methods is used to calculate the square root?

round
sqrt
ceil
root

The Math Object


Let's create a program that will ask the user to input a number and alert its square root.
var n = prompt("Enter a number", "");
var answer = Math.sqrt(n);
alert("The square root of " + n + " is " + answer);
JS
Result:contentImageEnter a number, such as 64.contentImage
Math is a handy object. You can save a lot of time using Math, instead of writing your own functions every time.

The Math Object

What is the result of the following expression: Math.sqrt(81);


Chapter: 42

The Date Object


setInterval


The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).
It will continue calling the function until clearInterval() is called or the window is closed.

For example:
function myAlert() {
alert("Hi");
}
setInterval(myAlert, 3000);
JS
This will call the myAlert function every 3 seconds (1000 ms = 1 second).
Write the name of the function without parentheses when passing it into the setInterval method.

setInterval

Fill in the blanks to call the function "calc()" every 2 seconds:

setInterval(
,
);

The Date Object


The Date object enables us to work with dates.
A date consists of a year, a month, a day, an hour, a minute, a second, and milliseconds.

Using new Date(), create a new date object with the current date and time
var d = new Date();
//d stores the current date and time
JS
The other ways to initialize dates allow for the creation of new date objects from the specified date and time
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
JS
JavaScript dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC). One day contains 86,400,000 millisecond.
For example:
//Fri Jan 02 1970 00:00:00
var d1 = new Date(86400000);

//Fri Jan 02 2015 10:42:00
var d2 = new Date("January 2, 2015 10:42:00");

//Sat Jun 11 1988 11:42:00
var d3 = new Date(88,5,11,11,42,0,0);
JS
JavaScript counts months from 0 to 11. January is 0, and December is 11.
Date objects are static, rather than dynamic. The computer time is ticking, but date objects don't change, once created.

The Date Object

What information results from creating a Date Object?

The date when the web page was hosted
The current date and time
An empty string


Date Methods


When a Date object is created, a number of methods make it possible to perform operations on it.contentImageFor example:
var d = new Date();
var hours = d.getHours();
//hours is equal to the current hour
JS
Let's create a program that prints the current time to the browser once every second.
function printTime() {
var d = new Date();
var hours = d.getHours();
var mins = d.getMinutes();
var secs = d.getSeconds();
document.body.innerHTML = hours+":"+mins+":"+secs;
}
setInterval(printTime, 1000);
JS
We declared a function printTime(), which gets the current time from the date object, and prints it to the screen.
We then called the function once every second, using the setInterval method.
The innerHTML property sets or returns the HTML content of an element.
In our case, we are changing the HTML content of our document's body. This overwrites the content every second, instead of printing it repeatedly to the screen.

Date Methods

Fill in the blanks to initialize a date object representing the current date and time:

date =
Date();

Chapter: 43

Module 6 Quiz


Given the array below, please complete the expression to be alerted with "apple".

var fruits = new Array("pear", "orange",

"apple", "grapefruit");


alert(fruits
);

What is the result of the following expression? alert(Math.sqrt(36));

0
6
12
36

Please fill in the blanks to output the current minutes:

var date = new Date();

alert(
.
Minutes());

What is the output of this code? var arr = new Array("a", "b", "c"); alert(arr[1]);


Drag and drop from the options below to get alerted with the value of the PI constant.

alert

(

Math

.

PI

);


Code Project:

Store Manager


Store Manager


You are working on a Store Manager program, which stores the prices in an array.
You need to add functionality to increase the prices by the given amount.
The increase variable is taken from user input. You need to increase all the prices in the given array by that amount and output to the console the resulting array.

Note: Comment down your answer for this.
Use a loop to iterate through the array and increase all items.


Comments