[Go to site: main page, start]

0% found this document useful (0 votes)
5 views78 pages

JavaScript Functions, Objects, and Arrays

Hwhevsgeyeygdfgehejajsjfbfkdkgluoulhjgiykiuoykhkbjgjfkhkhitinbnbmgnnvbvndkdithcbfbf. F fjrjfjvhrkeofbc be rjksjdjfhfydhdjfurr

Uploaded by

skhulilena4
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views78 pages

JavaScript Functions, Objects, and Arrays

Hwhevsgeyeygdfgehejajsjfbfkdkgluoulhjgiykiuoykhkbjgjfkhkhitinbnbmgnnvbvndkdithcbfbf. F fjrjfjvhrkeofbc be rjksjdjfhfydhdjfurr

Uploaded by

skhulilena4
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Schools of Computing & Mathematical Sciences

Multimedia fundamentals 242

JavaScript functions, objects


and arrays
Objective
At the end of this session, you should be able to:
• Display the ability to use functions in the JavaScript language.
• Demonstrate an understanding of OO concepts in the JavaScript
language.
• Demonstrate an understanding of the object oriented pattern in
JavaScript.
• Display the ability to use arrays in the JavaScript language.

2
JavaScript functions [1/3]
• In addition to having access to dozens of built-in functions (or
methods) such as write, which is used in [Link](), custom
functions can easily be created.
• Whenever there is a more complex piece of code that is likely to be
reused, that is a candidate for a function.
• The general syntax for a function is shown here:
function function_name([parameter [, ...]])
{
statements
}

3
JavaScript functions [2/3]
• The first line of the syntax indicates the following:
- A definition, which starts with the word function.
- A name follows that must start with a letter or underscore, followed by
any number of letters, digits, dollar symbols, or underscores.
- The parentheses are required.
- One or more parameters, separated by commas, are optional (indicated by the
square brackets, which are not part of the function syntax).
• Function names are case-sensitive, so all of the following strings refer
to different functions: getInput (), GETINPUT(), and getinput().

4
JavaScript functions [3/3]
• In JavaScript, the camel case (aka bumpy caps) naming convention is
used.
• This is a naming convention where the first letter of each word in a
name is capitalized except for the very first letter, which is lowercase.
• The function statements may include one or more return statements,
which force the function to cease execution and return to the calling
code.
• If a value is attached to the return statement, the calling code can
retrieve it.

5
The arguments array [1/3]
• The arguments array is a member of every function.
• The arguments array can be used to determine the number of variables
passed to a function and what they are.
• Consider the example displayItems() function given below:
<script>
displayItems("Dog", "Cat", "Pony")

function displayItems(v1, v2, v3)


{
[Link](v1 + "<br>")
[Link](v2 + "<br>")
[Link](v3 + "<br>")
}
</script>
6
The arguments array [2/3]
• When this script runs, it will display the following:
Dog
Cat
Pony

• Accessing function arguments this way is fine, but becomes inefficient


as the number of arguments increases.
• The arguments array provides the flexibility to handle a variable
number of arguments. The next slide shows how it can be used to
rewrite the previous example in a much more efficient manner.

7
The arguments array [3/3]
• Below is the displayItems() function modified to use the arguments
array.
• Note the use of the length property, and also how the array
[Link] is referenced using the variable j.
<script>
function displayItems()
{
for (j = 0 ; j < [Link] ; ++j)
[Link]([Link][j] + "<br>")
}
</script>

8
Returning a value [1/3]
• Functions are mostly used to perform calculations or data
manipulation and then return a result.
• The function fixNames () on the next slide uses the arguments array
(discussed in the previous section) to take a series of strings passed to
it and return them as a single string.
• The fixNames() function converts every character in the arguments to
lowercase except for the first character of each argument, which is set
to a capital letter

9
Returning a value [2/3]

<script>
[Link](fixNames("the", "DALLAS", "CowBoys"))
function fixNames()
{
var s = ""

for (j = 0 ; j < [Link] ; ++j)


s += [Link][j].charAt(0).toUpperCase() +
[Link][j].substr(1).toLowerCase() + " "
return [Link](0, [Link]-1)
}
</script>

10
Returning a value [3/3]
• When the fixNames () function is called with the parameters the,
DALLAS, and CowBoys, for example, the function returns the string
The Dallas Cowboys

How the fixNames () function works


• The function first initializes the temporary (and local) variable s to the
empty string.
• Then a for loop iterates through each of the passed parameters,
isolating the parameter’s first character using the charAt() method
and converting it to uppercase with the toUpperCase() method.

11
fixNames example explained [1/3]
• Then the substr() method is used to fetch the rest of each string,
which is converted to lowercase using the toLowerCase() method.
• A fuller version of the substr() method here would specify how many
characters are part of the substring as a second argument:
substr(1, (arguments[j].length) - 1 )
• The above line code tells the substr() method, “Start with the
character at position 1 (the second character) and return the rest of
the string (the length minus one).” If the second argument is omitted,
substr() takes the rest of the string.

12
fixNames example explained [2/3]
• After the whole argument is converted to the desired case, a space
character is added to the end and the result is appended to the
temporary variable s.
• Finally, the substr() method is used again to return the contents of the
variable s, except for the final space -which is unwanted. This is
removed by using substr() to return the string up to, but not
including, the final character.
• The various methods shown in this example are all built into
JavaScript and available by default.

13
fixNames example explained [3/3]
• This example is particularly interesting in that it illustrates the use of
multiple properties and methods in a single expression. For example:
[Link][j].substr(1).toLowerCase()
• The statement has to be interpreted by mentally dividing it into parts
at the periods. JavaScript evaluates these elements of the statement
from left to right as follows:
1. Start with the name of the function itself: fixNames.
2. Extract element j from the array arguments representing fixNames arguments.
3. Invoke substr() with a parameter of 1 to the extracted element. This passes all but the first
character to the next section of the expression.
4. Apply the method toLowerCase() to the string that has been passed this far.

14
Returning an array [1/3]
In the previous example, the function returned only one parameter. Arrays are used to
return multiple parameter as illustrated below:
<script>
words = fixNames("the", "DALLAS", "CowBoys")

for (j = 0 ; j < [Link] ; ++j)


[Link](words[j] + "<br>")

function fixNames()
{
var s = new Array()

for (j = 0 ; j < [Link] ; ++j)


s[j] = [Link][j].charAt(0).toUpperCase() +
[Link][j].substr(1).toLowerCase()
return s
}
</script>

15
Returning an array [2/3]
• In this example (previous slide), the variable words is automatically
defined as an array and populated with the returned result of a call to
the function fixNames().
• Then a for loop iterates through the array and displays each element.
• The fixNames() function on the previous slide is identical to the other
fixNames() example given earlier (slide #10), except that the variable
s is now an array, and after each word has been processed, it is stored
as an element of this array, which is returned by the return statement.

16
Returning an array [3/3]
• This function that returns an array enables the extraction of individual
parameters from its returned values, like the following:
words = fixNames("the", "DALLAS", "CowBoys")
[Link](words[0] + " " + words[2])

• The output from the above lines of code is simply:


The Cowboys

17
<intentionally left blank>

18
JavaScript objects
• Objects can be thought of as advanced variables.
• Variables can contain only one value at a time, whereas objects can
contain multiple values and even functions.
• An object groups data together with the functions needed to
manipulate it.

19
Declaring a class [1/5]
• To create a script to use objects, a composite of data and code called
a class needs to be designed.
• Each new object based on the class created is called an instance (or
occurrence) of that class.
• The data associated with an object is called its properties, while the
functions it uses are called methods.
• A JavaScript class is created by writing a function named after the
class. The next slide shows how to declare a class for an object called
User that will contain details about the current user.

20
Declaring a class [2/5]
<script>
function User(forename, username, password)
{
[Link] = forename
[Link] = username
[Link] = password
[Link] = function()
{
[Link]("Forename: " + [Link] + "<br>")
[Link]("Username: " + [Link] + "<br>")
[Link]("Password: " + [Link] + "<br>")
}
}
</script>

21
Declaring a class [3/5]
• This function can accept arguments and can create properties and
methods for objects in that class. The function is called a constructor.
• The example in the previous slide shows a constructor for the class
User with three properties: forename, username, and password. The
class also defines the method showUser().
• The function differs from other functions covered so far in two ways:
• It refers to an object named this. When the program creates an instance of
User by running this function, this refers to the instance being created.
• A new function named showUser() is created within the function. The
purpose of the syntax is to tie the showUser() function to the User class. Thus,
showUser() comes in as a method of the User class.

22
Declaring a class [4/5]
• The previous example follows the recommended way to write a class
constructor, which is to include methods in the constructor function.
• However, functions defined outside the constructor can also be
referred to as illustrated on the next slide.
• The script on the next slide shows an example of a class and method
defined separately.

23
Declaring a class [5/5]
<script>
function User(forename, username, password)
{
[Link] = forename
[Link] = username
[Link] = password
[Link] = showUser
}
function showUser()
{
[Link]("Forename: " + [Link] + "<br>")
[Link]("Username: " + [Link] + "<br>")
[Link]("Password: " + [Link] + "<br>")
}
</script>
24
Creating an object [1/2]
• An instance of the class User can be created as shown below:
details = new User("Wolfgang", "[Link]", "composer")

• Alternatively, an empty object can be created, like this:


details = new User()
and then populated later as shown below:
[Link] = "Wolfgang"
[Link] = "[Link]"
[Link] = "composer"

25
Creating an object [2/2]
• New properties can also be added to an object, like this:
[Link] = "Hello"
• To verify that the new properties work, the following statement can
be used:
[Link]([Link])

26
Accessing objects
• An object can be accessed by referencing its properties as illustrated below:
name = [Link]
if ([Link] == "Admin") loginAsAdmin()
• To access the showUser() method of an object of class User, the following syntax
would be used, in which the object details has already been created and
populated with data:
[Link]()
• This code would display the following (assuming the data supplied earlier):
Forename: Wolfgang
Username: [Link]
Password: composer

27
The prototype keyword [1/5]
• Considering the User class example, every instance will contain the
three properties and the method.
• Therefore, if there are 1,000 of these objects in memory, the method
showUser() will also be replicated 1,000 times.
• However, because the method is identical in every case, the prototype
keyword can be used to specify that new objects should refer to a
single instance of the method instead of creating a copy of it.
• Thus using the prototype keyword can save memory.

28
The prototype keyword [2/5]
• So, instead of using the following in a class constructor:
[Link] = function()
it could be replaced with this:
[Link] = function()
• The next slide shows an example of declaring a class using the
prototype keyword for a method.

29
The prototype keyword [3/5]
<script>
function User(forename, username, password)
{
[Link] = forename
[Link] = username
[Link] = password
[Link] = function()
{
[Link]("Forename: " + [Link] + "<br>")
[Link]("Username: " + [Link] + "<br>")
[Link]("Password: " + [Link] + "<br>")
}
}
</script>

30
The prototype keyword [4/5]
• The previous example works because all functions have a prototype
property, designed to hold properties and methods that are not replicated
in any objects created from a class. Instead, they are passed to its objects
by reference.
• A prototype property or method can be added at any time, and all objects
(even those already created) will inherit it, as the following statements
illustrate:
[Link] = "Hello"
[Link]([Link])
• The first statement adds the prototype property of greeting with a value of
Hello to the class User, while in the second line, the object details, which
has already been created, displays this new property.

31
The prototype keyword [5/5]
• Methods in a class can be added or modified as the statements below
illustrates:
[Link] = function()
{
[Link]("Name "+ [Link] +
" User "+ [Link] +
" Pass "+ [Link])
}
[Link]()
• These lines might be added to the script in a conditional statement (such as
an if statement), so they run if user activities require deciding on a different
showUser() method.
32
<intentionally left blank>

33
Static methods and properties
JavaScript also supports static properties and methods, which can
conveniently be stored and retrieved from the class’s prototype. Thus,
the following statements set and read a static string from User:
[Link] = "Hello"
[Link]([Link])

34
Extending JavaScript objects [1/5]
• The prototype keyword can be used to add functionality to a built-in
object.
• For example, to add the ability to replace all spaces in a string with
nonbreaking spaces in order to prevent it from wrapping around, can
be achieved by adding a prototype method to JavaScript’s default
String object definition, as illustrated below:
[Link] = function()
{
return [Link](/ /g, '&nbsp;')
}

35
Extending JavaScript objects [2/5]
• In this example (previous slide) the replace() method is used with a
regular expression to find and replace all single spaces with the string
&nbsp;.
• If the following command is then entered:
[Link]("The quick brown fox".nbsp())

it will output the string:


The&nbsp;quick&nbsp;brown&nbsp;fox

36
Extending JavaScript objects [3/5]
• Here is an example of a method that can be added that will trim leading
and trailing spaces from a string (once again using a regular expression):
[Link] = function()
{
return [Link](/^\s+|\s+$/g, '')
}
• If the following command is issued:
[Link](" Please trim me ".trim())

the output will be the string Please trim me (with the leading and trailing spaces
removed):
37
Extending JavaScript objects [4/5]
• If we break down the expression into its component parts, the two /
characters mark the start and end of the expression, and the final g
specifies a global search.
• Inside the expression, the ^\s+ part searches for one or more
whitespace characters appearing at the start of the search string,
while the \s+$ part searches for one or more whitespace characters
at the end of the search string.
• The | character in the middle acts to separate the alternatives.

38
Extending JavaScript objects [5/5]
• The result is that when either of these expressions matches, the
match is replaced with the empty string
• Thus returning a trimmed version of the string without any leading or
trailing whitespace.

39
<intentionally left blank>

40
JavaScript arrays
Array handling in JavaScript is very similar to PHP, although the syntax is
a little different. Nevertheless, given all you have already learned about
arrays, this section should be relatively straightforward for you.

41
Numeric arrays
• A new array can be created using the following syntax:
arrayname = new Array()

• Alternaively, the shorthand form can be used as illustrated below:


arrayname = []

42
Assigning element values [1/3]
• In PHP, a new element could be added to an array by simply assigning
it without specifying the element offset, like this:
$arrayname[] = "Element 1";
$arrayname[] = "Element 2";
• But in JavaScript, the push() method is used to achieve the same
thing, like this:
[Link]("Element 1")
[Link]("Element 2")
• This makes it possible to keep adding items to an array without having
to keep track of the number of items.
43
Assigning element values [2/3]
• To know how many elements are in an array, the length property can
be used, like this:
[Link]([Link])
• Alternatively, to keep track of the element locations and place them
in specific locations, can be done using syntax such as this:
arrayname[0] = "Element 1"
arrayname[1] = "Element 2"
• The next slide shows a simple script that creates an array, loads it
with some values, and then displays them.
44
Assigning element values [3/3]
<script>
numbers = []
[Link]("One")
[Link]("Two")
[Link]("Three")

for (j = 0 ; j < [Link] ; ++j)


[Link]("Element " + j + " = " + numbers[j] + "<br>")
</script>

45
Assigning element values [3/3]
The output from this script is as follows:
Element 0 = One
Element 1 = Two
Element 2 = Three

46
Assignment using the array keyword
• An array can be created together with some initial elements by using
the array keyword as illustrated below:
numbers = Array("One", "Two", "Three")
• More elements can still be added afterwards as well.

47
Associative arrays [1/4]
• An associative array is one in which its elements are referenced by
name rather than by numeric index.
• To create an associative array, define a block of elements within curly
braces. For each element, place the key on the left and the contents
on the right of a colon (:).
• The next slide illustrates how to create and display elements of an
associative array. The example shows how an associative array to hold
the contents of the “balls” section of an online sports equipment
retailer might be created.

48
Associative arrays [2/4]

<script>
balls = {"golf":"Golf balls, 6",
"tennis":"Tennis balls, 3",
"soccer":"Soccer ball, 1",
"ping":"Ping Pong balls, 1 doz"}

for (ball in balls)


[Link](ball + " = " + balls[ball] + "<br>")
</script>

49
Associative arrays [3/4]
• In this example (previous slide), to verify that the array has been
correctly created and populated, another kind of for loop using the in
keyword is used.
• This creates a new variable to use only within the array (ball, in this
example) and iterates through all elements of the array to the right of
the in keyword (balls, in this example).
• The loop acts on each element of balls, placing the key value into ball.

50
Associative arrays [4/4]
• This key value stored in ball, can be used to get the value of the
current element of balls.
• The result of calling up the example script in a browser is as follows:
golf = Golf balls, 6
tennis = Tennis balls, 3
soccer = Soccer ball, 1
ping = Ping Pong balls, 1 doz
• Getting a specific element of an associative array, can be done by
specifying a key explicitly, in the following manner (in this case,
outputting the value Soccer ball, 1):
[Link](balls['soccer'])

51
<intentionally left blank>

52
Multidimensional arrays [1/5]
• To create a multidimensional array in JavaScript, just place arrays
inside other arrays.
• For example, to create an array to hold the details of a two-
dimensional checkerboard (8×8 squares), could be done using the
code shown on the next slide.

53
Multidimensional arrays [2/5]
<script>
checkerboard= Array(
Array(' ','o', ' ','o',' ','o',' ','o'),
Array('o',' ', 'o',' ','o',' ','o',' '),
Array(' ','o', ' ','o',' ','o',' ','o'),
Array(' ',' ', ' ',' ',' ',' ',' ',' '),
Array(' ',' ', ' ',' ',' ',' ',' ',' '),
Array('O',' ', 'O',' ','O',' ','O',' '),
Array(' ','O', ' ','O',' ','O',' ','O'),
Array('O',' ', 'O',' ','O',' ','O',' '))

[Link]("<pre>")

for (j = 0 ; j < 8 ; ++j)


{
for (k = 0 ; k < 8 ; ++k)
[Link](checkerboard[j][k] + " ")
[Link]("<br>")
}
[Link]("</pre>")

</script>

54
Multidimensional arrays [3/5]
• In this example, the lowercase letter (o) and uppercase letter (O)
represent white and black pieces respectively. A pair of nested for
loops walks through the array and displays its contents.
• The outer loop contains two statements, so curly braces enclose
them.
• The inner loop then processes each square in a row, outputting the
character at location [j][k], followed by a space (to square up the
printout). This loop contains a single statement, so curly braces are
not required to enclose it.

55
Multidimensional arrays [4/5]
The <pre> and </pre> tags ensure that the output displays correctly,
like this:
o o o o
o o o o
o o o o

O O O O
O O O O
O O O O

56
Multidimensional arrays [5/5]
• Any element within this array can also be accessed directly by using
square brackets as illustrated below:
[Link](checkerboard[7][2])
• This statement outputs the uppercase letter O, which is the eighth
element down and the third along -remember that array indexes
start at 0, not 1.

57
<intentionally left blank>

58
Using array methods
• JavaScript has several built-in methods for manipulating arrays.
• The commonly used methods include:
-concat
-forEach
-join
-push and pop
-reverse
-sort

59
concat [1/2]
• The concat() method concatenates two arrays, or a series of values
within an array. For example, the following code :
fruit = ["Banana", "Grape"]
veg = ["Carrot", "Cabbage"]
[Link]([Link](veg))

outputs Banana,Grape,Carrot,Cabbage
• Multiple arrays can be specified as arguments, in which case
concat() adds all their elements in the order that the arrays are
specified.
60
concat [2/2]
• Here is another example of how to use concat():
pets = ["Cat", "Dog", "Fish"]
more_pets = [Link]("Rabbit", "Hamster")
[Link](more_pets)
• In this example, plain values are concatenated with the array pets,
which ouputs: Cat,Dog,Fish,Rabbit,Hamster

61
forEach [1/5]
• The forEach method in JavaScript is another way of achieving
functionality similar to the PHP foreach keyword, but only for
browsers other than Internet Explorer.
• To use it, simply pass it the name of a function, which will be called
for each element within the array.
• The next slide gives an example using the forEach method.

62
forEach [2/5]
<script>
pets = ["Cat", "Dog", "Rabbit", "Hamster"]
[Link](output)

function output(element, index, array)


{
[Link]("Element at index " + index + " has the value " + element + "<br>")
}
</script>

63
forEach [3/5]
• In this example, the function passed to forEach is called output(). It
takes three parameters: the element, its index, and the array.
• These parameter can be used as required by a given function. In this
example, just the element and index values are displayed using the
function [Link]().
• Once an array has been populated, the method is called like this:
[Link](output)

64
forEach [4/5]
This is the output:
Element at index 0 has the value Cat
Element at index 1 has the value Dog
Element at index 2 has the value Rabbit
Element at index 3 has the value Hamster

65
forEach [5/5]
• As already mentioned, at the time of writing these notes, forEach() is
not supported in Microsoft Internet Explorer.
• So the previous example will work only on non–Internet Explorer
browsers.
• To ensure cross-browser compatibility, instead of
[Link](output)
use a statement such as the following:
for (j = 0 ; j < [Link] ; ++j) output(pets[j], j)

66
join [1/2]
The join () method can be used to convert all values in an array to
strings and then join them together into one large string, placing an
optional separator between them. The sample code below shows three
ways of using the join() method

<script>
pets = ["Cat", "Dog", "Rabbit", "Hamster"]

[Link]([Link]()+ "<br>")
[Link]([Link](' ')+ "<br>")
[Link]([Link](' : ') + "<br>")
</script>

67
join [2/2]
• Without any parameter, join() uses a comma to separate the
elements; otherwise, the string passed to join is inserted between
each element.
• The output of the example in the previous slide looks like this:
Cat,Dog,Rabbit,Hamster
Cat Dog Rabbit Hamster
Cat : Dog : Rabbit : Hamster

68
push and pop [1/5]
The push() method is used to insert values into an array. The inverse method
of push is pop(): it deletes the most recently inserted element from an array.
The code below illustrates how to use the push() and pop() methods:
<script>
sports = ["Football", "Tennis", "Baseball"]
[Link]("Start = " + sports + "<br>")

[Link]("Hockey")
[Link]("After Push = " + sports +"<br>")
removed = [Link]()
[Link]("After Pop = "+ sports + "<br>")
[Link]("Removed = "+ removed + "<br>")
</script>

69
push and pop [2/5]
• The three main statements of this script (previous slide) are shown in
bold text.
• First, the script creates an array called sports with three elements and
then pushes a fourth element into the array.
• After that, it pops that element back off. In the process, the various
current values are displayed via [Link]().
• The script outputs the following:
Start = Football,Tennis,Baseball
After Push = Football,Tennis,Baseball,Hockey
After Pop = Football,Tennis,Baseball
Removed = Hockey

70
push and pop [3/5]
• The push() and pop() functions are useful in situations where it is
necessary to divert from some activity to do another, and then return.
• The script on the next slide illustrates push() and pop() usage inside
and outside of a loop.

71
push and pop [4/5]
<script>
numbers = []

for (j = 0 ; j < 3 ; ++j)


{
[Link](j);
[Link]("Pushed " + j + "<br>")
}
// Perform some other activity here
[Link]("<br>")
[Link]("Popped " + [Link]() + "<br>")
[Link]("Popped " + [Link]() + "<br>")
[Link]("Popped " + [Link]() + "<br>")
</script>

72
push and pop [5/5]
The output from this example is as follows:

Pushed 0
Pushed 1
Pushed 2

Popped 2
Popped 1
Popped 0

73
Using reverse
• The reverse() method simply reverses the order of all elements in an
array. The code below gives a reverse() usage example:
<script>
sports = ["Football", "Tennis", "Baseball", "Hockey"]
[Link]()
[Link](sports)
</script>
• The original array is modified, and the output from this script is as
follows:
Hockey,Baseball,Tennis,Football

74
sort [1/3]
• The sort() method is used to sort elements of an array in some order
such as alphabetical or some other order depending on the
parameters used.
• The example on the next slide shows four ways of using the sort()
method.

75
sort [2/3]
<script>
// Alphabetical sort
sports = ["Football", "Tennis", "Baseball", "Hockey"]
[Link]()
[Link](sports + "<br>")

// Reverse alphabetical sort


sports = ["Football", "Tennis", "Baseball", "Hockey"]
[Link]().reverse()
[Link](sports + "<br>")

// Ascending numeric sort


numbers = [7, 23, 6, 74]
[Link](function(a,b){return a - b})
[Link](numbers + "<br>")

// Descending numeric sort


numbers = [7, 23, 6, 74]
[Link](function(a,b){return b - a})
[Link](numbers + "<br>")
</script>

76
sort [3/3]
• The first of the four example sections is the default sort() method,
alphabetical sort, while the second uses the default sort and then applies
the reverse() method to get a reverse alphabetical sort.
• The third and fourth sections use a function to compare the relationships
between a and b. The function does not have a name, because it is used
only in the sort.
• Here, function creates an anonymous function meeting the needs of the
sort method. If the function returns a value greater than zero, the sort
assumes that b comes before a. If the function returns a value less than
zero, the sort assumes that a comes before b. By manipulating the value
returned (a - b in contrast to b - a), the sort () method chooses between an
ascending numerical sort and a descending numerical sort.

77
End

78

You might also like