- Forward


ECMAScript/JavaScript
An Introduction for Programmers


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Characters and White Space
Back SMYC Forward
  • Character Set:
    • v3 uses 16-bit Unicode
    • Case-sensitive
  • White Space:
    • Extra spaces, tabs, carriage returns, and new lines are (mostly) ignored
    • However, line breaks between tokens can sometimes cause problems because semicolons are optional (in the language, NOT the course style guide)
Identifiers
Back SMYC Forward
  • First Character:
    • Must be a letter, underscore, or dollar sign
  • Subsequent Characters:
    • Can be a letter, digit, underscore, or dollar sign
  • A Restriction:
    • An identifier can not be the same as one of the pre-defined reserved words
Comments
Back SMYC Forward
  • Line Based:
    • Any text between a // and the end of the line is a comment
  • Block:
    • Any text between a /* and a */ is a comment
Primitive Types
Back SMYC Forward
  • boolean:
    • true or false
  • number:
    • 64-bit floating point defined by IEEE 754
    • Integer literals betwen -253 and 253 can be represented exactly
    • Special Values: Infinity, NaN, Number.MAX_VALUE, Number.MIN_VALUE, Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY
  • string:
    • A sequence of Unicode characters
    • String literals can be enclosed in either single quotes or double quotes
    • \ is the escape character and can be used to represent special characters (e.g., \n represents the newline character) and Unicode characters (e.g., \u00e9 is é)
Variables
Back SMYC Forward
  • Types:
    • Variables are untyped
  • Syntax of Declarations: Click here for information.
    • var identifier [= value] [,identifier [= value]]...;
  • Examples:
    • var cost; var cost=5; var cost=5, price=6.20;
  • Notes:
    • A variable that is declared but not initialized contains the value undefined
    • Variables that are used but not declared explicitly will be declared implicitly and have global scope
    • A variable can be declared more than once
Assignment Operator
Back SMYC Forward
  • Assignment:
    • Placing a value into the memory identified by a variable/constant
  • Syntax: Click here for information.
    • variable = literal|expression ;
  • Examples:
    • height = 14.0; name = "Bullwinkle";
Arithmetic Operators
Back SMYC Forward
  • Basics:
    • Addition (+)
    • Subtraction (-)
    • Multiplication (*)
    • Division (/)
  • Integer Operators:
    • Integer Division (/)
    • Modulo (%)
  • Others:
    • Increment (++) and Decrement (--)
    • Negation (-)
Relational Operators
Back SMYC Forward
  • Comparison:
    • Greater than: >
    • Less than: <
    • Greater than or equal to: >=
    • Less than or equal to: <=
  • Sameness:
    • Equal to: ==
    • Identical to: ===
    • Not equal to: !=
    • Not Identical to: !==
Relational Operators (cont.)
Back SMYC Forward
  • Identical for Numbers:
    • Must have the same value
    • Neither must be NaN (i.e., NaN === NaN always evaluates to false)
  • Identical for Strings:
    • Must contain exactly the same characters in exactly the same positions
Relational Operators (cont.)
Back SMYC Forward
  • Equality for Special Values:
    • null == undefined evaluates to true
  • Equality for Numbers and Strings/Booleans:
    • Convert the string/boolean to a number and then test (true becomes 1 and false becomes 0)
Logical Operators
Back SMYC Forward
  • Basics:
    • Logical AND: &&
    • Logical OR: ||
    • Logical NOT: !
  • What About XOR?
    • There is no XOR operator but you should be able to work without it
The if Statement
Back SMYC Forward
  • Syntax: Click here for information.
    • if (boolean_expression) statement [else statement]
  • Examples:
    • if (score < 60) grade = "F"; if (bmi >= 30.0) status = "Obese"; else if (bmi >= 25.0) status = "Overweight"; if (quantity > 100.00) { discount = 0.10; note = "Volume Dicount"; }
while Loops
Back SMYC Forward
  • Syntax: Click here for information.
    • while (boolean) statement
  • Examples:
    • keepGoing = true; while (keepGoing) { count += 1; if (count > 10) keepGoing = false; } while (width <= 10) { area = height * width; width += 1; }
do-while Loops
Back SMYC Forward
  • Syntax: Click here for information.
    • do statement while (boolean);
  • Example:
    • do { q = age * size; age += 1; } while (age < 65);
for Loops
Back SMYC Forward
  • Syntax: Click here for information.
    • for (initialization; boolean; update) statement
  • Example:
    • for (i=0; i<size; i++) { area = i * i; }
Objects
Back SMYC Forward
  • Defined:
    • An object is an unordered collection of properties (each of which consists of a name and a value)
  • Literals/Initializers:
    • {[(identifier|string) : (literal|expression)]...}
  • Examples:
    • var empty = {}; var origin = {x:0, y:0}; var course = {dept: "CS", "number": 139+20};
Creating Specialized Objects
Back SMYC Forward
  • An Observation:
    • Object literals do not specify the "kind" of object to create
  • The new Operator:
    • var identifier = new ClassName([parameters])
  • Example:
    • var today = new Date();
The Membership Operator
Back SMYC Forward
  • Purpose:
    • Access a particular property of an object
  • The Symbol:
    • .
  • Example:
    • horizontalPosition = origin.x;
The Membership Operator (cont.)
Back SMYC Forward
  • Assigning a Value to an Existing Property:
    • var position = {x:0, y:0}; position.x = 10;
  • Assigning a Value to an Undeclared Property:
    • var position = {}; position.x = 10;
Existence of Properties
Back SMYC Forward
  • Testing with the in Operator:
    • "property" in object
  • Deleting with the delete Operator:
    • delete object.property
for in Loops
Back SMYC Forward
  • Syntax: Click here for information.
    • for (identifier in object) statement
  • Example:
    • for (coord in position) coord++;
Arrays
Back SMYC Forward
  • Defined:
    • An array is an ordered (variable-sized) collection of (not necessarily homogeneous) values
  • Terminology:
    • The numerical position is called the index (and is 0-based)
    • The value is called the element
  • Literals/Initializers:
    • [ values ]
  • Examples:
    • var empty = []; var grades = [90, 85, 73, 88]; var bad_idea = ["CS", 139, 4, "B-"];
Operating on Arrays
Back SMYC Forward
  • Accessing Elements with the [] Operator:
    • identfier [ index ]
  • Adding Elements:
    • To add an element to an array one need only assign a value to it. For example:
    • var a = [2, 4, 6]; a[9] = 20;
  • The delete Operator:
    • Actually sets the value to undefined
The Length of an Array
Back SMYC Forward
  • An Observation:
    • Arrays can be sparse
  • The length Property:
    • Is always one larger than the largest index
for of Loops
Back SMYC Forward
  • Syntax: Click here for information.
    • for (identifier of iterable) statement
  • Example:
    • for (price of purchases) total += price;
  • Iterable Objects:
    • Include Array, Map and Set
Arrays of Arrays
Back SMYC Forward
  • An Observation:
    • Any element of an array can, itself, be an array
  • Accessing Elements:
    • Use the [] operator more than once
Relational Operators Revisited
Back SMYC Forward
  • Equality for Objects and Strings:
    • Convert the object to a string (using the toString() method) and then test
  • Identical for Objects/Arrays:
    • Must refer to the same object/array to be identical (i.e., they are not identical if the objects have identical properties or elements)
Values and References
Back SMYC Forward
Type Passed By Compared By
boolean Value Value
number Value Value
Object Reference Reference
string Immutable Value
Functions
Back SMYC Forward
  • Defined:
    • A block of code that is defined once but invoked/executed one or more times
  • Information Exchange:
    • A function may have one or more formal parameters that can be used to provide it with information
    • A function may have a return value that it evaluates to when invoked
Defining Named Functions
Back SMYC Forward
  • Syntax:
    • function identifier([parameters]){ [statement;]...}
  • Example:
    • function area(width, height) { var result; result = 0; if ((width > 0) && (height > 0)) result = width * height; return result; }
Defining Anonymous Functions
Back SMYC Forward
  • Syntax:
    • function([parameters]){ [statement;]...}
  • An Example (that assigns an anonymous function to a variable named f):
    • var f = function(width, height) { var result; result = 0; if ((width > 0) && (height > 0)) result = width * height; return result; };
  • Note:
    • The anonymous function on the right side of the assignment operator is called a function expression (to distinguish it from a function declaration/statement)
Invoking/Executing
Back SMYC Forward
  • Syntax:
    • identifier([parameters])
  • Example:
    • var size = area(10.2, 20.9);
  • Optional Arguments:
    • One can invoke a function with too few parameters (i.e., with fewer actual paramaters than formal parameters) in which case the the other parameters will be undefined
    • Hence, when writing functions, one should account for this possibility
Variable Scope
Back SMYC Forward
  • Types:
    • Variables declared outside of a function have global scope
    • Variables declared inside of a function have local scope
    • Variables can not have block scope
  • Resolving Ambiguities:
    • Local variables take precedence over global variables
A More Sophisticated Understanding of Scope
Back SMYC Forward
  • The Global Object:
    • The interpreter automatically creates a global object
    • Global variables are actually properties of the global object
  • The Call Object:
    • When a function is executed a call/activation object is created
    • Local variables (and the function's arguments) are actually properties of the call/activation object
Functions as Data
Back SMYC Forward
function area(width, height) { return width*height; } var f = area;

Note: This is very different from, for example, var size = area(3,5); which executes area. f is the same function as area and can be used the same way.

Immediately-Invoked Function Expressions (IIFEs)
Back SMYC Forward
  • The Idea:
    • Define a function and invoke it immediately afterward
  • Syntax:
    • (function[ identifier]([formal_parameters]){[statement;]...}(actual_parameters));
  • Note:
    • Since parentheses can't contain statements, the parser knows that the code after the opening parenthesis must be a function expression (not a function declaration/statement)
    • If the identifier is omitted the function is anonymous otherwise it is named
    • The trailing parenthesis invoke the function just as they would in the following:
    • f = function(width, height){return width * height;}; a = f(4,5);
Methods
Back SMYC Forward
  • The Concept:
    • One can think of a method as a function that belongs to an object
  • Making this Happen:
    • Assign a function to a property of an object
Methods (cont.)
Back SMYC Forward
// Assign an object literal to a variable var r = { width: 10; height: 5; area: function() { return this.width * this.height; } } // Use the object var a = r.area();
What is this?
Back SMYC Forward
  • Function Invocation:
    • When a function is invoked, this refers to the global object
  • Method Invocation:
    • When a method (i.e., a function that is a property of an object) is invoked, this refers to the "owning" object
Classes and Objects in some Object-Oriented Languages
Back SMYC Forward
  • A Class:
    • A definition of a set that is written in terms of the properties of the elements (i.e., an intensive definition of a set)
  • An Object:
    • An element of the set
  • Constructor:
    • A method that is called to initialize the properties of an object
Pseudoclasses in ECMAScript/JavaScript
Back SMYC Forward
  • The new Operator:
    • Creates an empty object, sets this to refer to the object, and then invokes a function
  • An Implication:
    • We can write a (constructor) function that allows someone to create objects with specific attributes and behaviors
  • Some Terminology:
    • We will use the word "pseudoclass" to describe the code that allows these sets of objects to be created
    • For convenience, we will often shorten "pseudoclass" to "class" but you should understand the difference
A Rectangle Pseudoclass
Back SMYC Forward
function Rectangle(width, height) { this.width = width; this.height = height; this.area = function() { return this.width * this.height; } }
Thinking About this Approach
Back SMYC Forward
  • width and height:
    • Every rectangle will have its own width and height
    • This makes perfect sense
  • area:
    • Every rectangle will have its own area function
    • This is inefficient since there is nothing about the function that is specific to an object
Prototypes
Back SMYC Forward
  • In ECMAScript/JavaScript:
    • Every object has a reference to an object known as its prototype
    • Properties of the prototype appear to be properties of the object
  • Using the Protoype in the Rectangle Pseudoclass:
    • We can assign the area function to the protoype
    • The function will then appear to be a property of the rectangle
An Improved Rectangle Pseudoclass
Back SMYC Forward
// The Constructor function Rectangle(width, height) { this.width = width; this.height = height; } // The area() Method Rectangle.prototype.area = function() { return this.width * this.height; }
Owned Properties
Back SMYC Forward
  • A Useful Method:
    • The hasOwnProperty() method can be used to determine if the property is owned by the object or its prototype
  • A Useful Operator:
    • The in operator can be used to determine if an object has or appears to have a property
  • An Example:
    • var r = new Rectangle(10, 5); r.hasOwnProperty("width"); // Evaluates to true r.hasOwnProperty("area"); // Evaluates to false "area" in r; // Evaluates to true
Wrappers
Back SMYC Forward
  • Defined:
    • An object that corresponds to (and contains) a primitive type
  • In ECMAScript/JavaScript:
    • There are wrappers for boolean, number and string values (named Boolean, Number and String).
    • Conversions are performed automatically as needed
  • Implications:
    • Given a variable s containing a string, you can use methods like s.charAt(index)
    • Given a variable n containing a number, you can use methods like n.toString(base)
There's Always More to Learn
Back -