Client-Side Web Technologies JavaScript Part I
JavaScript First appeared in 1996 in Netscape Navigator Main purpose was to handle input validation that was currently being done server-side Now a powerful programming language that has many uses for creating responsive and dynamic web applications Consists of: ECMAScript (ECMA-262) not tied to web browsers http://www.ecma-international.org/publications/standards/ecma-262.htm The Document Object Model (DOM) The Browser Object Model (BOM)
The script element Categories: Metadata content Flow content Phrasing content Content model: If no src attribute, then script content; otherwise empty Some additional attributes: src indicates the path to the external script file async indicates that an external script can begin downloading immediately (and executing immediately) type the content type; usually text/javascript See ScriptInsertion examples https://www.w3.org/tr/html51/semantics-scripting.html#the-script-element
Syntax is very C-like Case-sensitive language General Syntax Identifiers (variables, functions, etc.) must: Start with a letter, underscore ( _ ), or dollar sign ( $ ) Contain only letters, underscores, dollar signs, or numbers Statements are terminated by a semicolon ( ; ) Code blocks begin with a left curly brace ( { ) and end with a right curly brace ( } ) Like other programming languages, there are reserved words that cannot be used as identifiers: http://www.ecma-international.org/ecma-262/6.0/index.html#secreserved-words Comments: Single line: start with two forward slashes ( // ) Block comments begin with /* and end with */
Operators Operator Name Description + Unary Plus No effect on numeric values; will cause implicit conversion on non-numeric values - Unary Minus Negates a numeric value; will cause implicit conversion and then negation on non-numeric values ++ Increment Increments a numeric value by 1; can be prefix or postfix -- Decrement Decrements a numeric value by 1; can be prefix or postfix + Add When used on two number operands it performs addition on them; if one operands is a string then a new string is created by concatenating the two operands (implicitly converting the other operand to a string if necessary) - Subtract Performs subtraction using two number operands * Multiply Performs multiplication using two number operands / Divide Performs division using two number operands % Modulus Performs division using two number operands; the result is the remainder
Operators (continued) Operator Name Description! Logical NOT Negates a Boolean value; will cause implicit conversion and then negation on non-boolean values && Logical AND Returns true if and only if both Boolean operands evlauate to true, false otherwise; short-circuited; behavior differs for operands of non-boolean types Logical OR Returns false if and only if both Boolean operands evlauate to false, true otherwise; short-circuited; behavior differs for operands of non-boolean types == Equal Returns true if the two operands are equal; equality rules differ amongst data types; performs implicit type conversion when needed!= Not Equal Returns true if the two operands are not equal; equality rules differ amongst data types; performs implicit type conversion when needed === Strict Equal Same as Equal but does not do type conversion!== Strict Not Equal Same as Not Equal but does not do type conversion
Operators (continued) Operator Name Description < Less Than Returns true if the left operand is less than the right operand; the nature of the comparison differes amongst data types <= Less Than Or Equal Returns true if the left operand is less than or equal to the right operand; the nature of the comparison differes amongst data types > Greater Than Returns true if the left operand is greater than the right operand; the nature of the comparison differes amongst data types >= Greater Than Or Equal Returns true if the left operand is greater than or equal to the right operand; the nature of the comparison differes amongst data types = Assignment Assigns the value on the right side of the operator to the variable on the left side; compound assignments are allowed for many operators (E.g. +=, *=, etc.)
Operators (continued) Operator Name Description ~ Bitwise NOT Performs a bitwise NOT & Bitiwise AND Performs a bitwise AND Bitwise OR Performs a bitwise OR ^ Bitwise XOR Performs a bitwise XOR << Left Shift Shifts all bits to the left by the given number of positions (bits filled with 0's) >> Right Shift Shifts all bits to the right by the given number of positions (bits filled with 0's and maintains sign) >>> Unsigned Right Shift Shifts all bits to the right by the given number of positions (bits filled with 0's)
Flow Control Statements The if statement The while statement The do while statement The for statement The for-in statement The switch statement
The if Statement if ( condition ) { //some code } else if ( condition2 ) { //some code } else { //some code }
The while Statement while ( condition ) { } //some code
The do while Statement do { //some code } while ( condition );
The for Statement for ( initialization; condition; post loop expression ) { } //some code The for in Statement for ( property in expression ) { } //some code
The switch Statement switch ( expression ) { case value: statement break; case value: statement break; default: statement }
Data Types There are 7 fundamental data types: 6 primitive types Undefined Null Boolean Number String Symbol* 1 reference type Object * New in ECMAScript 6 (ECMAScript 2015)
Variables Variables are loosely typed Use the var operator to define variables var name; Variables can also be initialized when defined var name = Jeff ; Since variables are loosely typed we can do this (but don t!) var name = Jeff ; name = 23;
Variables Ways to declare variables var hoisted to top of function let block scope New in ECMAScript 6 (2015); good support across latest browsers const block scope and cannot be changed New in ECMAScript 6 (2015); good support across latest browsers When possible, use const Otherwise use let. Avoid var if possible.
typeof Operator To determine the data type of a given variable we can use the typeof operator var age = 35; console.log(typeof age); console.log(typeof(age)); // number // number Returns: undefined if the value is undefined (uninitialized or undeclared variable) boolean if the value is a boolean string if the value is a string number if the value is a number symbol if the value is a symbol object if the value is an object (other than a function) or null null is an empty object reference which is why typeof would return object function if the value is a function
The Undefined Type Has only one value, the special value undefined A declared variable that has not been initialized will be undefined var name; console.log(name === undefined) //true
The Null Type Has only one value, the special value null If you define a variable that you intend to later hold an object you should initialize the variable to null to allow null checking var myobject = null; if ( myobject!== null ) { } //do something
The Boolean Type Has two values, true and false All types have Boolean equivalents: Undefined: false Null: false Number: if the number is 0 or NaN, then false; true otherwise String: if an empty string then false; true otherwise Object: true Types are automatically converted as needed but you can explicitly convert to a Boolean type with the Boolean() function var mybool = Boolean( hello ); console.log(mybool); //true
The Number Type Supports integers and floating point numbers Number literal formats: Integers Decimal (base 10): 29 Hexadecimal(base 16): 0x1d Floating-point values Decimal point and at least one number after it: 3.14 E-notation: 1.785e2 or 3.8e-4 Like other languages, floating-point arithmetic can cause rounding errors (Google floating-point arithmetic ).1 +.2 = 0.30000000000000004???
The Number Type (continued) Number.MIN_VALUE = 5e-324 (most browsers) Number.MAX_VALUE = 1.7976931348623157e+308 If the result of a calculation is out of range then the result is the special value Infinity (or -Infinity) The isfinite() function can be used to determine if a result is finite NaN (Not a Number) is a special numeric value used to indicate than operation that was intended to return a number has failed Any operation involving NaN returns NaN so you cannot use it in an equality check The isnan() function is for this purpose
The Number Type (continued) Number conversion functions Number() Converts to a number using a large number of rules http://www.ecma-international.org/ecma-262/6.0/index.html#sec-tonumber var num = Number(false); //0 var num2 = Number( 34 ); //34 var num3 = Number( ); //0 parseint() Converts a string to an integer http://www.ecma-international.org/ecma-262/6.0/index.html#sec-tonumber var num = parseint( ); //NaN var num2 = parseint( 22.5 ); //22 parsefloat() Converts a string to a number http://www.ecma-international.org/ecma-262/6.0/index.html#sec-parsefloatstring var num = parsefloat( 22.5 ); //22.5
The String Type Represents a sequence of zero or more 16-bit Unicode characters You can use single or double quotes to delineate strings var name = Jeff ; var name = Jeff ; Strings are immutable To convert a value of another type into a string: tostring() method Results vary from type to type and amongst different kinds of objects String() function http://www.ecma-international.org/ecma-262/6.0/index.html#sec-string-constructorstring-value
The Object Type Objects are a collection of properties and methods Objects are instances of reference types There are no classes in ECMAScript * Created using the new operator followed by the name of the reference type (constructor function) var myobject = new Object(); We can test if a variable is an instance of a given reference type using the instanceof operator if ( myobject instanceof MyRefType ) { } //Do stuff... We will discuss objects in depth later See TypesAndOperators example *ECMAScript 6 (ECMAScript 2015) introduces classes but are essentially syntactic sugar
Functions Declared with function keyword Functions do not care about the number or type of arguments Functions do not specify whether a value must be returned on not Functions cannot be overloaded If two functions share the same name then the most recently declared function will own that name All arguments are passed by VALUE See Functions\Functions example
Execution Context For variables and functions it defines what data is accessible and how it should behave The global execution context is the outermost context This is the window object All global variables and functions are properties and methods on the window object Each function call gets its own execution context When code execution flows into a function its context is pushed onto a context stack
Scope Chain Used in identifier resolution Provides ordered access to all variables and functions an execution context has access to The beginning of the chain is the context of the currently executing code The end of the chain is the global execution context Identifiers are resolved by navigating the chain beginning to end Declaring a variable with var adds the variable to the most immediate context available
Closures Functions that have access to variables from another function s scope are called closures Inner functions still have access to outer function variables even if the outer function finishes executing See the ScopeAndClosures.html example
Memory Management JavaScript manages memory for you via garbage collection It automatically allocates and reclaims memory The garbage collector runs automatically Some browsers allow you to explicitly initiate collection but this is generally not recommended It is good practice to set global values to null (dereferencing) when no longer needed so their memory can be reclaimed (avoid globals though) Local variables are automatically dereferenced when they go out of context
Native Reference Types Object Function Array Date RegExp Primitive Wrappers Boolean Number String Math Global*
The Object Type Ways to create an instance of Object Use the new operator followed by the Object() constructor Object literal notation: Constructor function is not called Preferred way to pass large number of optional parameters to a function var myobject = { age: 18 };
The Object Type (continued) Each instance of an Object has the following properties and methods: constructor function used to create the instance hasownproperty(propertyname) indicates if a given property exists on the object instance (not on prototype) isprototypeof(object) determines if an object is a prototype of another propertyisenumerable(propertyname) can enumerate the property using the for-in loop tostring() returns a string representation of the object tolocalstring() returns a string representation of the object appropriate for locale of execution environment valueof() returns a string, number, or Boolean equivalent of the object See the ObjectType example
The Function Type All functions are instances of the Function reference type Therefore, all functions are objects Function names are really just variables that point to objects of the Function type Ways to create a function Function declarations (what we have seen thus far) Function expressions Use the new operator followed by the Function() constructor
The Function Type (continued) Inside function body there is a special object called this It points to the context object that the function is operating on Functions also have a length property that reflects the number of named parameters
The Function Type (continued) The apply() and call() methods on the Function type allow us to call functions supplying a specific object for the function to use as its this value apply() takes two arguments the object to use as the this pointer and an array or arguments to pass the function (can be the special arguments object as well) call() takes multiple arguments the first is the object to use as the this pointer and subsequent arguments are passed directly to the function The bind() function (new in ECMAScript 5) creates a new instance of the Function type whose this pointer will refer to the object passed in as a parameter to bind() See the Functions\Functions2 example
Ordered list of data The Array Type Can contain a mix of different types Dynamically sized as needed Get/set contents using square brackets ([]) myarray[2] = hello ; Indexes are zero-based numbers If setting an item with index past the end, the array length is automatically increased to index + 1 Arrays have a length property that can be read from and written to Can use Array.isArray() instead of instanceof Array
The Array Type (continued) Ways to create an Array instance: Use the new operator followed by the Array() constructor Array literal notation Constructor function is not called var myarray = [ hello, bye ];
Array Methods Method join() concat() slice() splice() push() pop() unshift() shift() Description Joins all items into a string, delimited by the separator, and returns the string Joins two or more arrays and returns the new array Returns a new array with the items in the supplied range Adds/removes items to/from an array and returns the removed items Adds new items to the end of the array and returns the new length Removes the last item in the array and returns that item Adds new items to the beginning of the array and returns the new length Removes the first item in the array and returns that item
Array Methods (continued) Method sort() reverse() indexof() lastindexof() every() some() foreach() Description Sorts the original array Reverses the order of items in the original array Searches the array (forward) for a specified item and returns its position Searches the array (backward) for a specified item and returns its position Runs the given function on every item in the array and returns true if the function returns true for every item Runs the given function on every item in the array and returns true if the function returns true for any one item Runs the given function on every item in the array
Array Methods (continued) Method filter() map() Description Runs the given function on every item in the array and returns an array of all items for which the function returns true Runs the given function on every item in the array and returns the result of each function call in an array See the ArrayType example
The Date Type Stores date and time as the number of milliseconds elapsed since midnight on January 1 st, 1970 Created using the new operator and the Date() constructor If no arguments, the new object represents the current date/time Can supply arguments to create an object for a given date/time Lots of methods http://www.w3schools.com/jsref/jsref_obj_date.asp See the DateType example
The RegExp Type Allows for matching patterns in text using regular expressions More info on regular expressions: http://www.regular-expressions.info/javascript.html http://www.w3schools.com/jsref/jsref_obj_regexp.asp https://regex101.com/ Ways to create a RegExp instance: The new operator followed by the RexExp() constructor Literal form See the RegExp example
The Boolean Type When a Boolean primitive type variable is read for property/method access, an object of the Boolean reference type is created to wrap the primitive value for the read operation The object is immediately destroyed afterwards You can explicitly create an instance using the new operator and the Boolean() constructor
The Number Type When a Number primitive type variable is read for property/method access, an object of the Number reference type is created to wrap the primitive value for the read operation The object is immediately destroyed afterwards You can explicitly create an instance using the new operator and the Number() constructor Defines some useful methods: http://www.w3schools.com/jsref/jsref_obj_number.asp
The String Type When a String primitive type variable is read for property/method access, an object of the String reference type is created to wrap the primitive value for the read operation The object is immediately destroyed afterwards You can explicitly create an instance using the new operator and the String() constructor Defines many useful methods: http://www.w3schools.com/jsref/jsref_obj_string.asp Defines a length property See the PrimitiveWrapperTypes example
The Math Object Provides methods and properties useful in mathematical computations http://www.w3schools.com/jsref/jsref_obj_math.asp Is a singleton Cannot create your own instance Instead do this: Math.sqrt(4) Math.pow(2, 8) Math.PI Math.random()
The Global Object Is a singleton All global variables and functions are actually properties and methods on the global object Web browsers implement the Global Object via the window object Defines a number of properties and methods We have already looked at many of them isfinite() isnan() parseint() Etc... http://www.w3schools.com/jsref/jsref_obj_global.asp
The Global Object (continued) The eval() method Extremely powerful Executes the string argument as a script Code executed by eval() is part of the same execution context as that from which the call to eval() was made There are performance and security concerns with eval()
Strict Mode New in ECMAScript 5 Can apply to entire scripts or functions Put the following before any code in the script or function use strict Backwards compatible Prevents certain actions from being taken Cannot assign variables that have not been defined (nonstrict puts these on the global object) Cannot use eval to introduce new variables into containing scope arguments.callee not supported Other things...
Exception Handling ECMAScript supports try-catch-finally statements Can also throw exceptions See Exceptions example