Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to JavaScript

Similar presentations


Presentation on theme: "Introduction to JavaScript"— Presentation transcript:

1 Introduction to JavaScript
Instructor: Sergey Goldman

2 JavaScript Role HTML CSS JavaScript (Scripting!) content and structure
headline, how many divisions are in your page, how many paragraphs… CSS Presentation Style, font, background . . . JavaScript (Scripting!) Behavior Events Validation

3 Web page (static) vs Web application (dynamic)
Application pages can update themselves on-the-fly: This requires: A programming language running in the browser API's in the language to provide access to the page's components (DOM manipulation)

4 Client-Side Scripting
JavaScript only works inside another application, for example, the web browser No compiling (scripting) No access to local file No direct access to db No access to hardware: HDMI, USB etc.

5 Popular Server-Side Programming Languages
Java C# VB.Net PHP Ruby on Rails Perl But! Because of its popularity JavaScript is used in other applications - Acrobat - Photoshop and even in server-side products - Node.js - Google Apps Script

6 Disabling JavaScript in WebBrowser
Chrome-> Settings-> Advanced -> Privacy-> Content settings FF->Settings Need to do our best to make it work w/o JavaScript (limited, but…)

7 History 1995 1996 1997 LiveScript (Netscape) JavaScript (Netscape 2)
IE3 Jscript by MS 1995 1996 1997 LiveScript (Netscape) JavaScript (Netscape 2) ECMAScript (standard) Sun had an agreement to rename LiveScript to JavaScript to jump on that Java hype The two languages have nothing to do with each other Both look like C After Jscript the ECMA created an independent and official ECMA standard officially called ECMAScript, 97

8 IDE and Tools Any text editor Use what you have: Visual Studio Eclipse
Netscape Aptana Intellij Vi SlickEdit Emacs . . . .Net Apps Need C# or VB.Net, Windows, Visual Studio iPhone Apps Need Objective-C, Mac OSX, Xcode JavaScript Need …just browser

9 Web Browsers 2015 http://stats. areppim
Web Browsers and wikipedia

10 Web Browser Percentage Market Share Worldwide October 2012
Percent (outdated) Chrome 34.77 IE 32.08 Firefox 22.32 Safari 7.81 Opera 1.63 Android 0.44 Maxthon 0.13 Sony PS3 Sogou Explorer Silk 0.08 Chromium 360 Safe Browser 0.07 RockMelt 0.06 BlackBerry 0.03 Pale Moon QQ Browser SeaMonkey 0.02 TheWorld Tencent Traveler AppleWebKit Iron 0.01 webOS Browser Mozilla Netscape Flock Camino Phantom Comodo Dragon

11 Javascript Basic First Look
object-oriented scripting language Simple object system based on prototypes NO Classes Basic syntax similar to C not Java Ex.: sum = 0; for (i = 1; i < 10; i++) { sum += i*i; } scripting language: Dynamic Interpreted

12 Hello World <!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <title>Welcome</title> </head> <body> <p>Welcome to HTML5!</p> <script> alert("Hello World!"); </script> </body> </html>

13 Another way (using document)

14 Errors

15 FireFox FireBug F12 – Console –> Enable it

16 FireBug Command Editor
Show command editor to be able to write multiple lines of JavaScript

17 Chrome F12

18 JavaScript language Interpreted language
Gives source/code to browser CASE SENSETIVE (but Var and var are the same ) case-insensitive languages: Visual Basic, Pascal … old HTML allows mix, <p> and </P>, not w/ JavaScript

19 What JavaScript can do…
Change colors of headline, background, foreground Change font Move, hide, show image, menu Calculate alert Validate . . . A lot more

20 One line –> one statement –> good practice
Sloppy html code – forget closing tag JavaScript can forgive ; But do not do it

21 White Space Executing line by line (all examples below are the same)
But these aware of spaces = = != . . .

22 Where does JavaScript go?
<!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <title>Welcome</title> <script> alert("Hello World!"); </script> </head> <body> <p>Welcome to HTML5!</p> EMPTY </body> </html>

23 JavaScript file If render page, create content->head
BTW css here always Otherwise in body Ex.: myHtml.html <!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <title>Welcome</title> </head> <body> <p>Welcome to HTML5!</p> <script src="myScript.js"></script> </body> </html> mySript.js alert("Hello World!");

24 type=“text/javascript”
Do not need! Formally required, but optional Default

25 Variables Untyped (JavaScript is loosely typed):
types associated with values, not with variables any variable can hold any value Scope is either local (within a function) or global (page) Default is global (careful!) use var to declare a local variable No block-level scoping within a function

26 Variables var var day; var newDay; var d; var day51; var 51day;
var day 51; No Spaces letters numbers underscores $

27 undefined undefined has a special meaning in JavaScript
When a variable is declared in JavaScript, but is not given a value, it has an undefined value. Attempting to use the value of such a variable is normally a logic error. When variables are declared, they are not assigned default values, unless specified otherwise by the programmer. To indicate that a variable does not contain a value, you can assign the value null to it.

28 null and undefined null
A value indicating that a variable contains no valid data. null is the result of: An explicit assignment of null to a variable. Any operation between expressions that contain null.

29 undefined and null (cont)
A special value given to variables after they are created and before a value has been assigned to them var x = null; document.write("x= " + x ); //null var y = undefined; document.write("y= " + y); //undefined var z; document.write("z= " + z); //undefined var u = window.doesnotexist; alert (u == null); //true, but u is undefined, //here undefined == null! var v = null; alert (v == null); //true

30 Variables are Case SensiTive
var x =100; x X = 200; X Automatic Creation!!! X = 200; 100 200

31 Data Types Primary Data Types string (variable-length); no char type
number (everything is floating-point, no integers) Boolean Object function Special Data Types (cannot contain values) null undefined Composite Data Types Array Date

32 Datatype ANY – Weak(ly) types var myVar; ?
Defining variables var year, month, day; var year =2013, month = 0, day = 24; Datatype ANY – Weak(ly) types var myVar; ? integer float string boolean array object

33 Weakly Type cont var myVar; myVar = 200; myVar = 1.5; myVar = “Hello”;
myVar = false; myVar = []; myVar = new Date();

34 Value Types is a piece of information that can be a string, number, boolean, null, object, or a function Type Description Example string     a series of characters inside quote marks   "JavaScript is cool" number any numeric value (not inside quotes) 4.55 boolean either true or false true null Empty, devoid of any value object properties and methods of an object function value returned by a function

35 typeof function <html> <head><script>
function MyFunctionForObject() { alert("Hello everyone"); } var myObject = new MyFunctionForObject(); var myArray = new Array(1); var myString = "Hello"; var myInteger = 9; var myFloat = 9.9; var myBoolean = true; var myDoc= document; var myWrite= document.write("Hmmm<br />"); document.write(typeof(myObject) + "<br/>"); //object document.write(typeof(myArray) + "<br/>"); //object document.write(typeof(myString) + "<br/>"); //string document.write(typeof(myInteger) + "<br/>"); //number document.write(typeof(myFloat) + "<br/>"); //number document.write(typeof(myBoolean) + "<br/>"); //boolean document.write(typeof(MyFunctionForObject) + "<br/>"); //function document.write(typeof(myDoc) + "<br/>"); //object document.write(typeof(myWrite) + "<br/>"); //underfined document.write(typeof(myVar)); //underfined </script> </head> <body></body> </html>

36 typeof cont Object Date Array There are 3 types of objects:
typeof "John"                 // Returns string  typeof 3.14                   // Returns number typeof NaN                    // Returns number typeof false                  // Returns boolean typeof [1,2,3,4]              // Returns object typeof {name:'John', age:34}  // Returns object typeof new Date()             // Returns object typeof function () {}         // Returns function typeof myCar                  // Returns undefined (if myCar is not declared) typeof null                   // Returns object There are 3 types of objects: Object Date Array

37 Conditions Terminology

38 Conditions cont.

39 Operators Operator === type comparison Not just equal but identical!

40 Debugging console.log (not for all browsers)
FF*

41 FF FireBag console.log

42 FF console.log, console.error, console.warn, console.info

43 Example FF

44 Chrome More Tools->Developer Tools <ctrl>+<shift>+<l> or F12 <Shift>+<Enter> continues on the next line Arrow up/down

45 Chrome

46 Other operators

47 Increment/Decrement (Unary operator)
Modulus (remainder) var x = 1003; var remainder = x % 4 //3 Increment/Decrement (Unary operator)

48 Ternary operator condition ? true : false;

49 Equality and Relational Operators

50 While Do …While

51 for

52 break

53 continue

54 Functions

55 Functions cont.

56 Function place head/beginning html
Put functions in order (but it does not matter, for readability) It's a better practice to rearrange function so that functions are defined and declared before you use it Invocation: myFunction(); Declaration: function myOtherFunction() { //code is here } function myFunction() { myOtherFunction();

57 Function parameters function factorial(x) { if (x <= 1) { return 1;
} return x*factorial(x-1);

58 return Using return

59 Parameters mismatch

60 Variable Scope global

61 An array is a single variable that holds multiple values
Arrays An array is a single variable that holds multiple values it doesn't matter what kind of datum is in at the different array slots Variable-length collections of values Indexed by integers

62 Creating Array

63 Creating Array Shorthand
Creating Array Longhand

64 JavaScript Arrays - Dynamic

65 Array Methods Modifies Original!
A lot of methods: push, pop, split, sort…

66 document and array

67 Numbers

68 Addition and Concatenation
var a = 5; var b = “5”; console.log(a+b); //55

69 NaN

70 Math object

71 Strings do not mix “ and ‘

72 String properties (can be treated as objects and arrays)
String methods

73 split Does not change original string
var phrase = "Yet another phrase"; var segment = phrase.slice(6,11); console.log("phrase= " + phrase); console.log("segment= " + segment); phrase= Yet another phrase segment= other Does not change original string

74 slice indexOf

75 comparison

76 https://developer.mozilla.org/en-US/docs/JavaScript/Reference

77 Dates Time to mills Month 0 based Internally ms since 1970

78 Dates methods > new Date('1970-01-01').getTime()
> new Date(' ').getTime() > new Date(' ').getTime()

79 getDay() Sunday 0…Wednesday 3…Saturday 6

80 Comparing (Dates are objects)
set Days Comparing (Dates are objects)

81 Objects (container)  collection of name-value pairs called properties.

82 Object creation Dot syntax
Object creation (shorthand)

83 Functions are objects increment = function(value) { return value + 1;
} increment(10) returns 11; There is no difference between a method and a function except the way they are invoked: method invocation provides a value for this. Use this to refer to instance variables. A property of an object can be a function; if so, it can be invoked using method notation: var o = new Object(); o.count = 0; o.increment = function(inc) { if (inc == undefined) { inc = 1; this.count += inc; //for this object o return this.count; o.increment(); returns 1 o.increment(3); returns 4 o.increment(5); returns 9

84 Constructor: a function named after the class.
function Rectangle(width, height) { this.width = width; this.height = height; } r = new Rectangle(26, 14);

85 Prototypes provide for inheritance of properties (typically methods). To create a method that applies to all objects of a particular class, define it like this: Rectangle.prototype.area = function() { return this.width*this.height; }

86 Prototypes (cont.) When Javascript looks up a property (e.g. a method), if it can't find it on the object itself, it looks for it in the prototype property of its class (constructor function). How object-oriented constructs are implemented in Javascript: Class: a constructor function; there is no other notion of class. Method: a function property on the prototype property of the constructor. Instance variable: a property on an object; must be created explicitly for each object (e.g., by constructor). Class variable: a property on the constructor function. Static variable: a property on the function. Static method: a function property on the constructor function. This object system is very simple, yet very flexible: Can add new properties and methods at any time.

87 this

88 Deitel book (using document )
document.write() OK for learning, but “harsh” on DOM

89 6.3 Modifying Your Script (Cont.)
The + operator (called the “concatenation operator” when used in this manner) joins two strings together

90 6.3 Dialog

91 6.3 Escape Sequences When a backslash is encountered in a string of characters, the next character is combined with the backslash to form an escape sequence. The escape sequence \n is the newline character. It causes the cursor in the HTML5 document to move to the beginning of the next line.

92 6.4 Obtaining User Input with prompt Dialogs Dynamic Welcome Page
Scripting Gives you the ability to generate part or all of a web page’s content at the time it is shown to the user Such web pages are said to be dynamic, as opposed to static, since their content has the ability to change

93

94 Comments A single-line comment begins with the characters // and terminates at the end of the line Comments do not cause the browser to perform any action when the script is interpreted; rather, comments are ignored by the JavaScript interpreter Multiline comments begin with delimiter /* and end with delimiter */ All text between the delimiters of the comment is ignored by the interpreter.

95 6.4.1 Prompt The window object’s prompt method displays a dialog into which the user can type a value. The first argument is a message (called a prompt) that directs the user to take a specific action. The optional second argument is the default string to display in the text field. Script can then use the value that the user inputs.

96 6.4.1 null again Function parseInt
null keyword Signifies that a variable has no value null is not a string literal, but rather a predefined term indicating the absence of value Writing a null value to the document, however, displays the word “null” Function parseInt converts its string argument to an integer JavaScript has a version of the + operator for string concatenation that enables a string and a value of another data type (including another string) to be concatenated

97 6.4.2 Adding Integers

98

99

100 6.6 Arithmetic The basic arithmetic operators (+, -, *, /, and %) are binary operators, because they each operate on two operands JavaScript provides the remainder operator, %, which yields the remainder after division Arithmetic expressions in JavaScript must be written in straight-line form to facilitate entering programs into the computer

101 6.6 Arithmetic (Cont.) Parentheses can be used to group expressions as in algebra. Operators in arithmetic expressions are applied in a precise sequence determined by the rules of operator precedence: Multiplication, division and remainder operations are applied first. If an expression contains several of these operations, operators are applied from left to right. Multiplication, division and remainder operations are said to have the same level of precedence. Addition and subtraction operations are applied next. Addition and subtraction operations have the same level of precedence. When we say that operators are applied from left to right, we are referring to the associativity of the operators. Some operators associate from right to left.

102 6.7 Decision Making (from deitel)

103

104

105 new To create an object, type the var keyword, followed by the name you want to use for the object, followed by the assignment operator, followed by the new operator, followed by the name of the class and its parentheses. In the parentheses of the class, you can provide a value for each argument. Do not need new for document and window objects – browser creates it

106 Escape/Unescape function
encodes the string that is contained in the string argument to make it portable. A string is considered portable if it can be transmitted across any network to any computer that supports ASCII characters.   To make a string portable, characters other than the following 69 ASCII characters must be encoded:   ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz   All other characters are converted either to their two digit (%xx) or four digit (%uxxxx) hexadecimal equivalent (referred to as the character's "hexadecimal escape sequence"). For example, a blank space will be represented by %20 and a semicolon by %3B.   var str = "Need education? Go to OIT school!"; var str_esc = escape(str); Need%20education%3F%20Go%20to%20OIT%20school%21

107 Escape/Unescape function
unescape function to decode an encoded sequence that was created using escape.   document.write(unescape(" Need%20education%3F%20Go%20to%20OIT%20school%21 ")) Need education? Go to OIT school!

108 eval eval: evaluates and/or executes a string of JavaScript code that is contained in the argument.   First, eval determines if the argument is a valid string and then parses the string looking for JavaScript code. If there are JavaScript statements in the code, they will be executed and eval will return the value of the last statement (if there is a value). If there is a JavaScript expression, it will be evaluated and its value will be returned.   Note that the argument is optional. However, if there is no argument, eval returned, "undefined".  eval(“thelma=1; luisa=2; document.write(thelma + luisa);"); 3

109 References and Reference Parameters
Two ways to pass parameters Pass-by-value Pass copy of original value Default for numbers and booleans Original variable is unchanged Pass-by-reference (copy). Actually by value How objects are passed, like arrays Pass location in memory of value Allows direct access to original value Improves performance

110 12.4.6 XHTML Markup Methods Anchor Blink Fixed Strike Subscript
<a name = “top”> Anchor </a> Blink <blink> blinking text </blink> Fixed <tt> monospaced text </tt> Strike <strike> strike out text </strike> Subscript <sub> subscript </sub> Superscript <sup> superscript </sup>

111 While loop

112

113

114

115 7.9 Formulating Algorithms: Sentinel-Controlled Repetition
Special value called a sentinel value (also called a signal value, a dummy value or a flag value) indicates the end of data entry Often is called indefinite repetition, because the number of repetitions is not known in advance Choose a sentinel value that cannot be confused with an acceptable input value

116

117

118

119

120 7.10 Formulating Algorithms: Nested Control Statements
Control structures may be nested inside of one another

121

122

123

124 Assignment operators

125 Increment/decriment

126

127

128


Download ppt "Introduction to JavaScript"

Similar presentations


Ads by Google