Web Systems Development (CSC-215) Lecture 15: Introduction to JavaScript Monday 23rd April 2018
Javascript: dynamic functionality for websites
Offers functionality that is not otherwise possible because it runs in the browser and has direct access to all elements in a web page
JavaScript First appearance in Netscape Navigator in 1995 Not related to Java Grew more powerful when HTML started using the Document Object Model Like PHP, follows programming syntax of C Heart of Ajax (which along with HTML5 helps produce fluid front ends)
JavaScript & HTML Runs entirely within web browsers
Scripts in <head> When you want it to run when the page loads When it includes a function call that will be needed multiple times …
Including JavaScript Files The script files themselves (.js) should NOT contain any <script> tags
Debugging JavaScript Errors Use browser tools PHP errors were standard, JavaScript error handling will be browser implementation dependent For example Firefox -> Tools -> Web Developer -> Web Console
Syntax overview
Comments: C++ style // /* */
Semi colons: optional – unless there are multiple statements on a single line
Variable names: Like c++ except that $ is allowed Variable names: Like c++ except that $ is allowed. Not using it is good practice.
String Variables Double or single quotes
Escaping
String Assignment & Use
Numeric Variables
Arrays
Accessing Array Values
Arithmetic Operators
Logical Operators
String Concatenation
typeof
Functions
Globals Define outside of functions
Document object model
Document Object Model JavaScript built in the context of the DOM The DOM breaks down parts of an HTML document into discrete objects Each with its own properties and methods Each subject to JavaScript’s control
JavaScript Objects, Methods & Properties
DOM: Hierarchy of Parent & Child Elements
Short Form
Safe & Conventional Form Previous ones might not work in IE
Shortcut
Using the DOM The links value is an array
Using the DOM Retrieve length of array
Using the DOM Extract and display all links
Using the DOM Referencing history
Using the DOM Replace currently loaded URL
Expressions and Control Flow Syntax overview
Expressions Similar to C++, PHP in style
True/False All values evaluate to true except The string false -0 -0 Empty string Null Undefined NaN (not a number, e.g., after division by zero)
Literals & Variables
Simple Statements
Operator Precedence
OnError
Try Catch
If
Else
While
Do While
Explicit Casting
Class Activity Create a JavaScript program that inputs a number n from a user and then displays the sum to n For n = 5 output 1 + 2 + 3 + 4 + 5 = 15
Class Activity Using prompt/alert boxes for input/ouput
Lecture content adapted from chapter 14 & 15 of Learning PHP, MySQL, JavaScript, CSS & HTML5.