javascript javascript is a scripting language that is most commonly used to add client- side...

21
JavaScript JavaScript JavaScript is a scripting language that is most commonly used to add client-side programming to a web page. Some of the things it is used for in web development: Manipulate the HTML elements and CSS Interact with the user Send data back to a server asynchronously (AJAX) Input validation (ex: make a textbox red if it has too many/few characters in it)

Upload: rafe-patterson

Post on 26-Dec-2015

223 views

Category:

Documents


1 download

TRANSCRIPT

JavaScriptJavaScriptJavaScript is a scripting language that is most commonly used to add client-side programming to a web page.

Some of the things it is used for in web development:

Manipulate the HTML elements and CSS Interact with the user Send data back to a server asynchronously (AJAX) Input validation (ex: make a textbox red if it has too many/few characters

in it)

Java vs. JavaScriptJava vs. JavaScriptJavaScript has next to nothing to do with Java

JavaScript was developed at Netscape in the 90's and was originally called LiveScript. It is believed that the name change to JavaScript was a marketing ploy to take advantage of the popularity of Java.

JavaScript syntax is much like C, and therefore much like Java.

JavaScript DetailsJavaScript DetailsJavaScript is managed by the Mozilla Foundation

Client-side: the browser (the client) is able to read & execute the code.

*JavaScript can be used server-side for other purposes

Interpreted or may be compiled using just-in-time compilation in modern browsers.

ECMAScript: The version of JavaScript that was standardized by Ecma International

Imperative: Code is written as a sequence of steps to perform

Structural: Makes use of decisions (if / else if / else), iteration (for, while), and subroutines and functions

JavaScript Type SystemJavaScript Type SystemLoosely Typed: Variables are not given a type, just “var”

Dynamically Typed: The type of the variable is determined at runtime based on its value.

The good: You don't have to cast anything, you can switch between types if it suits your code. Example: User types in “10”, you can leave it as is and still compare it to the integer 10.

The bad: Type errors will not be detected until runtime, and depending on your exact code they may be easy to miss.

Coercion: Implicit type conversion: “2” * “10” --> 20

Conversion: JavaScript provides functions to convert values to other types when necessary

JavaScript Variables & Simple JavaScript Variables & Simple TypesTypes

Variablesvar x = 123;var y; //to be used later

JavaScript does have types, they are just determined dynamically.

Number / Float - Generic number1.0 is the same as 1100 is the same as 1e2Negative numbers have a – symbol

Infinity is a keyword that represents very large numbers

Strings can be enclosed in single or double quotes'Hello' is the same as “Hello”\ is the escape character

Boolean – true or false

JavaScript Null, NaN, UndefinedJavaScript Null, NaN, UndefinedNaN (Not a Number) results when an arithmetic operation is invalid. Use the isNaN() function to detect it (==, === won't work because NaN is never equal to itself).

A variable is undefined if it was never given a value. Use === for comparisons.

null is what you would expect – a null value. You can assign a variable the value of null and compare null to values. Use === for comparisons.

JavaScript Decision StatementsJavaScript Decision StatementsIf Statementsif (condition) {

} else if (condition) {

} else {

}

Ternary var answer = x == “Y” ? “Yes” : “No”;

Switch Statementsswitch (expression) {

case expression:... break;

case expression:...break;

default:...

}

JavaScript LoopsJavaScript Loops

Whilewhile (condition) { ... }

Do While (Will always be executed at least once because the condition is evaluated last)do { ... } while (condition)

Forfor (var i = 0; i < 10; i++) { ... }

for (someProp in someObj) { ... }

JavaScript Try & ThrowJavaScript Try & Throw

Try / Catchtry { } catch (err) {

}

Throw (Throw a string, number, boolean, object)throw “Some message”;

JavaScript OperatorsJavaScript Operators&& boolean AND|| boolean OR* multiply/ divide% modulo+ addition or string concatenation- subtraction>=, > greater than or equal, greater than<=, < less than or equal, less than

JavaScript EqualityJavaScript Equality= is for assignmentvar x = 10;

== is for equality(x == 10) //true(x == “10”) //true(x != 9) //true

=== is for equality including data type(x === 10) // true(x === “10”) // false(x !== “10”) // true

JavaScript ArraysJavaScript ArraysSyntax:var x = [10, 15, “apple”];var first = x[0];

JavaScript ObjectsJavaScript ObjectsObjects: Heavily used; Objects are associative arrays where the property name is the key. Both dot notation and array notation are supported

fruit.color = “red”;fruit[“color”] = “red”;

Prototypes: You don't create classes like you do in OOP languages. Instead you create a prototype.

Inheritance can be done using a prototype. Feel free to read up on JavaScript prototypes and prototypal inheritance

Object LiteralSimple notation for creating objects

var fruit = {“color”: “red”, “type”: “apple”, “weight”: 0.5};

JavaScript ObjectsJavaScript ObjectsObjects can contain simple values, other objects, arrays, functions

var student = {“firstName”: “John”, “lastName”: “Smith”, “uid”: “123456”,“schedule”: [

{“class”: “CS108”,“days”: “MW”,“startTime”:”10:00”

},{

“class”: “CS108”,“days”: “MW”,“startTime”:”10:00”

}]

};

var firstCourseNum = student.schedule[0].class;

JavaScript FunctionsJavaScript FunctionsJavaScript is a functional language: Functions are first-class. Functions are objects themselves. They can be passed as arguments to other functions, they can be returned from other functions, and a function can be assigned to a variable.

Variadic Functions: Functions take a variable number of arguments

function someFunc(x, y, z) { document.write(x); document.write(y); document.write(z); document.write(arguments[3]);}

someFunc(1, “a”); //z will be undefined

someFunc(1, “a”, 2, “b”); //”b” will only be accessible through the special arguments array

ClosuresClosures

* Examples from Wikipedia

A closure is a data structure that stores a function along with an environment.

In the example below, the variable in red will be available to the returned function (green) even though it would normally be out of scope.

Anonymous Functions (Lambda)Anonymous Functions (Lambda)

* Examples from Wikipedia

Anonymous functions are unnamed functions, often returned or passed into another function. You do not ever have to use an anonymous function, but sometimes they are convenient.

DOM (Document Object Model)DOM (Document Object Model)The Document Object Model is a programming interface. The objects in HTML (or XML or XHTML) are represented as nodes in a tree structure, called the DOM tree. These nodes can have event handlers attached to them. The event handlers can call code or functions in languages like JavaScript.

Example: Buttons have an onclick event. When a button is clicked, you might want to pop up something asking the user if they are sure they want to perform an action, you might make something on the page change, etc.

It is common to hear that you are traversing the DOM looking for an element with JavaScript, or that you are manipulating the DOM with JavaScript.

The DOM is standardized. Browsers are supposed to adhere to this standardization.

DOM (Document Object Model)DOM (Document Object Model)Please read: https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction

Cross-Site Scripting (XSS)Cross-Site Scripting (XSS)It is common to ask a user for text input and then display that input back to the screen. Think: product review, comment on an article, etc.

If a user were to input JavaScript code, and that were to be displayed on the screen, what would happen? That JavaScript code would execute.

What to do about it?Sanitize user input! Strip out any script tags or anything else that may be malicious.

Client Side SecurityYou can strip out the script tags using JavaScript, but you cannot rely on that as a full solution. You must also sanitize data at the server side because anyone can modify client-side data (using the same browser tools you use for debugging).

Regular ExpressionsRegular ExpressionsRegular expressions are patterns used to match characters in a string. The simplest example of using regular expressions is when you want to restrict a user to typing in only numbers, or to following a particular pattern like an email address or phone number.

Regular expressions are heavily used in programming and learning how to use them is well worth your time if you want to be a developer.

There are plenty of resources online. This page from Mozilla explains how to use them with JavaScript:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions