05JavaScript
05JavaScript
2022 Semester 1
Unit Coordinator: Tim French
JavaScript
JavaScript is a high-level, dynamic, untyped, and interpreted programming language. It
has been standardized in the ECMAScript language specification. Alongside HTML and
CSS, it is one of the three essential technologies of World Wide Web content
production. JavaScript is prototype-based with first-class functions, making it a multi-
paradigm language, supporting object-oriented, imperative, and functional
programming styles.
•Language specification: http://www.ecmascript.org/
•Tutorial: http://www.w3schools.com/js/
Components
•Core
– The heart of the language
•Client-side
– Library of objects supporting browser control and user interaction
•Server-side
– Library of objects that support use in web server
Uses of JavaScript
• Provide alternative to server-side programming
– Servers are often overloaded
– Client processing has quicker reaction time
• JavaScript can interact with the internal model of the web page
(“Document Object Model” - more on this soon...)
• Users actions, such as mouse clicks and key presses, are referred to as events
• Identifiers
– Start with $, _, letter
– Continue with $, _, letter or digit
– Case sensitive
– camelCase preferred
• Comments
– //
– /* … */
• Reserved words...
• Properties
• JavaScript is dynamically typed, that is, variables do not have declared types
– A variable can hold different types of values at different times during program
execution
• A variable is declared using the keywords var, let, const (or nothing)
var counter, index, pi = 3.14159265, rover = "Palmer",
stop_flag = true;
const x = 6, y = 7;
let z = x+y;
zz = z;
• If a variable remains uninitialized, then its type is undefined.
• An important difference from other languages like Java is that in Javascript, you
don’t get block-level scope, only functions have scope. So if a variable is defined
using var inside an if or for block, it will be visible to the entire function.
• let and const do have block level scope.
• In Javascript, there is no strong type-checking like Java. You can declare a
variable to hold an integer and then you can assign a string to that same
variable var value = 5; value = “Hello”; // No error
Assignments and Operators
• Plain assignment indicated by =
• Compound assignment with: += -= /= *= %= …
• a += 7 means the same as a = a + 7
• Like Java, you can use + to concatenate two different strings. You can also
use it to convert a string to a number
let value = + “123”;
• Numeric Operators
– Standard arithmetic
+ * - / %
– Increment and decrement
-- ++
• String Operators
– Concatenation
+
• Boolean Operators
– !, &&, ||
Implicit Type Conversion
• Comparisons in Javascript can be made using >, <, >=, <=, ==, ===, != and
!== operators. These works for both strings and numbers.
• The == operator performs type coercion if you give it two different types
“dog” == “dog” // true
1 == true // true!
‘abc’ == [‘abc’] // true!!
• The === operator performs returns true only if both operands are
equal, and of the same type.
“dog” === “dog” // true
1 === true // false
‘abc’ === [‘abc’] // false
Control Statements
• A compound statement in JavaScript is a sequence of 0 or more statements
enclosed in curly braces
• A control construct is a control statement including the statements or
compound statements that it contains
1
8
Control Structures
• Javascript has for, while, do-while loops just like
Java. It also has if-else, switch statements and
ternary operator. Switch statements can compare switch (expression) {
string values. You can also use an expression in the case value_1:
// statement(s)
case statement. case value_2:
• The && and || operators use short-circuit logic, which // statement(s)
means whether they will execute their second ...
operand depends on the first. This is useful for [default:
checking for null objects before accessing their // statement(s)]
attributes – }
// && will return Object if it’s null
var property = Object &&
Object.getProperty();
• Or for setting their default values –
var name = otherName || “default”;
l The if-then and if-then-else are similar to
that in other programming languages, especially
C/C++/Java
Object Orientation and JavaScript
• JavaScript is object-based
– JavaScript defines objects that encapsulate both data and processing
– However, JavaScript does not have the same inheritance nor subtyping (therefore
polymorphism) as normal OOP such as Java or C#.
• JavaScript provides prototype-based inheritance
– See, for example this Wikipedia article for a discussion:
http://en.wikipedia.org/wiki/Prototype-based_languages
• Eg
2
1
Array Object Creation
• Arrays can be created using the new Array method
– new Array with one parameter creates an empty array of the specified number of
elements
new Array(10);
– new Array with no parameter creates an empty array
var a = new Array();
a[0] = “dog”; a[1] = “cat”; a[2] = “hen”;
console.log(a.length); // outputs 3
– new Array with two or more parameters creates an array with the specified
parameters as elements
new Array(1, 2, “three”, “four”);
Associative Arrays index on Strings and are actually Objects. These oeprations
are not available to them:
var arr = [];
arr[“name”] = “Bob”;
• push: Add to the end
• pop: Remove from the end
• shift: Remove from the front
2
• unshift: add to the front 4
Function Fundamentals
• Function definition syntax
– A function definition consists of a header followed by a compound statement
– A function header:
• function function-name(optional-formal-parameters)
• Function call syntax
– Function name followed by parentheses and any actual parameters
– Function call may be used as an expression or part of an expression
• Functions must be defined before use in the page header (or linked in an
external file)
• return statements
– A return statement causes a function to cease execution and control to pass to
the caller
– A return statement may include a value which is sent back to the caller
– If the function doesn’t have any return statement, or uses an empty
return with no value, then undefined is returned.
2
5
Functions
• Along with the objects, functions are the core components in
understanding Javascript. We can also treat functions as objects.
The most basic function is as follows
function add(x, y){
var total = x+y;
return total;
}
• You can call the above function with no parameter as well. In
such case, they will be set to undefined.
Functions are Objects
• Functions are objects in JavaScript (or first class functions)
• Functions may, therefore, be assigned to variables and to object properties
– Object properties that have function name as values are methods of the object
Example
function fun() {
console.log("This surely is fun!");
}
ref_fun = fun; // Now, ref_fun refers to
// the fun object
fun(); // A call to fun
ref_fun(); // Also a call to fun
2
7
Local Variables
• “The scope of a variable is the range of statements over which it is visible”
• A variable not declared using var has global scope, visible throughout the page,
even if used inside a function definition
• A variable declared with var outside a function definition has global scope
• A variable declared with var inside a function definition has local scope, visible
only inside the function definition
– If a global variable has the same name, it is hidden inside the function definition
– A variable declared with let or const has block level scope.
2
8
Parameters
• Parameters named in a function header are called formal parameters
• Parameters used in a function call are called actual parameters
• Use arguments to access non-formal parameters
function fun1(my_list) {
var list2 = new Array(1, 3, 5);
my_list[3] = 14; //changes actual
parameter
3
0
The sort Method
• A parameter can be passed to the sort method to specify how to sort
elements in an array
– The parameter is a function that takes two parameters
– The function returns a negative value to indicate the first parameter
should come before the second
– The function returns a positive value to indicate the first parameter
should come after the second
– The function returns 0 to indicate the first parameter and the second
parameter are equivalent as far as the ordering is concerned
• Example:
3
1
Constructors
• Constructors are functions that create and initialize properties for new
objects
• A constructor uses the keyword this in the body to reference the object
being initialized
• Object methods are properties that refer to functions
– A function to be used as a method may use the keyword this to refer to the
object for which it is acting
3
2
Functions (Recursive)
• Like any other languages, you can write recursive
functions in Javascript. However, this creates a problem
if the function is anonymous. How would you call a
function without its name? The solution is using named
anonymous functions -
var ninja = {
yell: function cry(n) {
return n > 0 ? cry(n-1) + "a" : "hiy";
}
};
Javascript can also use prototypes to implement inheritance. A subclass can be defined
to have the prototype of a superclass, and then the implementation of the methods can
be overwritten in the subclass prototype..
Inner functions
• JavaScript function declarations are • Using inner functions we can
allowed inside other functions
function Example(){ use one of the most powerful
var a = 1;
abstractions Javascript has to
function oneMoreThanA(){
offer – closure. A quick quiz,
return a + 1;
what does this do –
function makeAdder(a) {
}
return function(b){
return oneMoreThanA(); return a + b;
} }
}
What does Example() return?
x = makeAdder(5);
• A closure is the local variables for a y = makeAdder(20);
function – kept alive after the
function has returned. console.log( x(6) );
// ?
console.log( y(7) );
// ?
Javascript closure
• Here, the outer function (makeAdder) has returned, and hence common
sense would seem to dictate that its local variable no longer exist. But they
do still exist, otherwise the adder function would be unable to work.
• In actuality, whenever Javascript executes a function, a scope object is
created to hold the local variables created within that function. It is initialized
with any variables passed in as function parameters.
• This is similar to the global object that all global variables and functions live
in, but with a couple of important differences: firstly, a brand new scope
object is created every time a function starts executing, and secondly, unlike
the global object these scope objects cannot be directly accessed from your
code.
• So when makeAdder is called, a scope object is created with one
property: a, which is the argument passed to the function. It then returns a
newly created function.
• Normally JavaScript's garbage collector would clean up the scope object
created for makeAdder at this point, but the returned function maintains a
reference back to that scope object. As a result, the scope object will not be
garbage collected until there are no more references to the function object
that makeAdder returned.
Javascript IO
• Standard output for JavaScript embedded in a browser is the window displaying the
page in which the JavaScript is embedded
• Writing to the document object is now considered bad practice. For simple
debugging use
console.log(“The result is: ”, result, “<br />”);
• To read, you can use alert or confirm. To get input you can use prompt.
• In NodeJS you can access stdin, stdout, and stderr through the process
object. Eg:
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout});
rl.question('What do you think of Node.js? ', (answer) => {
console.log('Thank you for your feedback:', answer);
rl.close();});
4
5
Errors in Scripts
• JavaScript errors are detected by the browser
• Different browsers report this differently
– Firefox uses a special console
• Can insert breakpoint in code with:
debugger;
• Support for debugging is provided
– IE, the debugger is part of the browser
– Firefox , plug-ins are available
• These include Venkman and Firebug
– Safari: Develop | Show Error Console
• First use: Choose Preferences | Advanced | Show Develop menu in menu bar
• Note: Reopen error console after reloading page (bug?)
– Chrome
• Use console from the Devloper Tools
4
6