Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Introduction to JavaScript

2,483 views

Published on

Introduction to JavaScript course. The course was updated in 2014-15.

Will allow you to understand what is JavaScript, what's it history and how you can use it.

The set of slides "Introduction to jQuery" is a follow up - which would allow the reader to have a basic understanding across JavaScript and jQuery.

Published in: Education

Introduction to JavaScript

  1. 1. Introduction to JavaScript Dr. Andres Baravalle
  2. 2. Lecture plan • Starting to program • Introduction to JavaScript • Lexical structure • Variables and data types • Expressions • Operators • Objects and functions
  3. 3. STARTING TO PROGRAM
  4. 4. Starting to program • The following slides should appear familiar as you have done some programming before – If you are familiar with basic programming concepts such as variables, arrays, conditional statements and loops, you should be able to understand and use JavaScript quite rapidly.
  5. 5. INTRODUCTION TO JAVASCRIPT
  6. 6. WWW technologies • Since the advent of the World Wide Web (WWW) much of the focus in computing has been on technologies that work with, or on, the World Wide Web. This includes W3C technologies as HTML, CSS and XML (that work on the web) but also programming languages as Java, Python, Ruby - the allow to build applications that rely on - or use - the World Wide Web. • These technologies can be grouped (by function) into three main layers: – Languages for structuring content (such as HTML 5 or XML) – Languages to manage the presentation layer of information (such as CSS) – Languages to manage the interaction of the user with the structure and with the presentation (such as JavaScript or PHP).
  7. 7. WWW technologies and layers • At this point, it would be useful to summarise the more important WWW technologies, and in which layers they operate. • Please note that any technology can be used in different ways; we are now focusing on the more common uses of the technologies. • Some of the technologies focus on just one of the layers that we have identified: – XHTML and HTML5 are mark-up languages used to structure the content of web pages – XML (Extensible Mark-up Language) is a language that allows to structure arbitrary content. Historically, XML was defined only after HTML, trying to overcome some of its limitations – CSS is a style language used to add presentation information, of XML dialects and HTML.
  8. 8. WWW technologies and layers (2) • A number of languages implement features of all three layers: – Flash is a technology from Adobe to create animations, interactive movies and rich Web applications (Web applications that have features and functionalities similar to the ones of desktop applications). – Java is a technology from Oracle (formerly Sun) that is used in different fields of computing. It can be used for Web development, on both the client side and server side. Java programs embedded in web pages on the client side are called Java applets. – PHP is a server-side scripting language used for web development. – JavaScript (more later!)
  9. 9. JavaScript • JavaScript is a language that is largely used in the Word Wide Web to add client- side interactivity to web pages – JavaScript has been first included in Netscape 2, in 1995!
  10. 10. ECMAScript • ECMAScript is a scripting language standardised by ECMA in June 1997, based on the JavaScript specifications from Netscape but with a vendor-neutral name. • While the original ECMAScript was based on JavaScript, now it’s the other way around and JavaScript is based on ECMAScript: – The latest version of ECAMAScript is ECMAScript 6 – released in June 2015 – The current version of JavaScript is 1.8.5, compliant with ECMAScript 5 – Other ECAMAScript-based languages are ActionScript (used in Adobe Flash) & Jscript (the Microsoft implementation, used in Microsoft products)
  11. 11. Client side JavaScript • Client side JavaScript is simply JavaScript that runs on the client • In this module, you’ll be using client side JavaScript only (but there’s also server side JavaScript – although is not very used)
  12. 12. Client side JavaScript (2) • These are some client side JavaScript methods – to get you started: – document.write(), to write in a document – alert(), to open a pop-up window – prompt(), to capture user input – confirm(), to get a yes/no answer from the user
  13. 13. Inserting JavaScript • There are three common ways of inserting JavaScript code in a web page: – Inside an HTML tag script – In an external file – As a value of some HTML attributes
  14. 14. JavaScript in a tag script • Inside an HTML tag script: <script type="text/javascript"> alert("JavaScript is working in your browser"); </script>
  15. 15. JavaScript in an external file • Inside an external .js file, linked to the HTML page: <script type="text/javascript" src="path/to/file.js"> </script> • The external .js file will include just the JavaScript code, no HTML
  16. 16. JavaScript as a value of some HTML attributes • <a href="javascript:alert('JavaScript is working in your browser');">link</a>
  17. 17. Hello Word! • You are now ready to write your first Hello World file – and then we will go through JavaScript syntax
  18. 18. Hello Word! (2) <!doctype html> <html> <head> <meta charset="utf-8"> <title>Hello World</title> </head> <body> <script type="text/javascript"> document.write("<p>Hello World</p>"); </script> </body> </html>
  19. 19. Before you start • You’ll need a suitable editor – Aptana Studio, Adobe Dreamweaver, Notepad++ are all ok • You’ll need Firebug to debug your scripts – download an install it on Firefox • You’ll need a JavaScript reference; please download the “Open JavaScript Guide” from from sourceforge: http://sourceforge.net/projects/javascriptguide/
  20. 20. Activity #1 • You have seen three different approaches to include JavaScript code in a web page • Create 2 simple hello world pages – one like the one demonstrated a few slides before, one using an external file.
  21. 21. LEXICAL STRUCTURE
  22. 22. JavaScript: lexical structure • In the next slides we are going to understand the lexical structure of JavaScript (that is, the meaning of its terms) • Learning the lexical structure means understanding the elements that are used when creating scripts
  23. 23. JavaScript: semicolons • A JavaScript program is quite simply a sequence of instructions made up of symbols (such as keywords, characters with special meaning, numbers and text chunks) to which the language associates a special meaning • Simple statements in JavaScript are typically followed by a semicolon (;): var x = 1; var y = 2;
  24. 24. JavaScript: semicolons (2) • You may omit the semicolon if each of the statements is a placed on a separate line: var x = 1 var y = 2 – You should follow every statement by a semicolon and a new line – Readability of the code is improved by using semicolons after every statement, and it is a requirement in other development languages
  25. 25. Whitespace • Whitespace (spaces, tabs and newlines) can be used freely to format and indent the code • If you insert a new line and the chunk of code that is left in the line appears to be a complete, valid statement, JavaScript will insert an implicit semicolon, possibly altering the meaning of the code.
  26. 26. Whitespace (2) • Consider this code: return true; • which will be interpreted as: return; true; • The code will return the value undefined (which is the default value when return is called without a parameter), instead of the value true.
  27. 27. Case sensitivity • Computer languages can be case sensitive or case insensitive (or may be a combination of both) • JavaScript is case sensitive, which means that the name of keywords and other language identifiers must always be typed with the correct capitalisation
  28. 28. Comments • Comments are chunks of text which are not executed but are placed to ensure that the code can be read in an easier way • You should get into the habit of using comments in abundance, both to make sure that other developers can understand your code (unless you explicitly want to avoid that) and to refresh your own memory when returning to it
  29. 29. Comments (2) • JavaScript has two ways of inserting comments: // the rest of the line is a comment /* This block of text is a comment. In this way I can comment on multiple lines at the same time. */
  30. 30. Literals • Programming requires manipulation of data. In JavaScript, data that appear directly in a program are called literals. • For example: – "Hello world" – 15 – null – true – false
  31. 31. VARIABLES AND DATA TYPES
  32. 32. Data types • A program normally handles data in some form or other • For example, a program created to calculate and print a credit-card bill would deal with the: – Amounts that have been charged to the card – Names of the companies charging the card – Dates of charges to the card – Card owner’s name – Card owner’s address • All these items can be termed data
  33. 33. Data types (2) • JavaScript supports a number of different data types. The main ones are: – Number – String – Boolean • Other data types include: – Null & undefined
  34. 34. Declaring variables and storing values • This is done by using a statement – like these: • x = 0.01; // Just one Number type for integers and floats • This statement creates a variable x, of type Number – This is called typing, and statements that do that are called ‘type statements’.
  35. 35. Declaring variables and storing values (2) • x = 0.01; // Just one Number type for integers and floats • x = "hello world"; // Strings of text in quotation marks. • x = true; // Boolean values • x = null; // Null is a special value that means "no value”
  36. 36. Declaring variables and storing values (2) • The statement gives the variable a value using the operator ‘=’ – The first time you assign a value to a variable is typically called initialisation • Statements – as this one - that declare a variable’s name and type are also frequently called declarations
  37. 37. EXPRESSIONS
  38. 38. Expressions • Programming in any language requires manipulating data. In some cases, the data will be just literals (such as text strings) but quite often more complex expressions will be used. • Anything that can be evaluated by the JavaScript interpreter can be thought of as an expression, just as literals are any data that appear directly in a program.
  39. 39. Expressions (2) • Expressions can use a number of different operators, or no operators at all • For example: x * 2 • Individual expressions can be combined together with operators to create a compound expression, whose value is calculated at runtime: x + y/4 x - y + 2
  40. 40. OPERATORS
  41. 41. Operators • Operators are special functions that operate on one to three values (operands). • The most common operators require one operand (unary operators) or two operands (binary operators). – Unary operators require a single operand, which can be before or after the operator. – Binary operators require two operands, one before and one after the operator
  42. 42. Operators (2) • You have already seen a few operators that are a part of JavaScript – The assignment operator (‘=’) – The operators for the basic math operations (addition, subtraction, multiplication, division) • JavaScript includes a good number of operators, but we are going to focus on those that will be more useful for your forthcoming studies
  43. 43. Assignment operators • Used to assign the value of the right operand to the left operand: x = y; • The right operator can be any type of expression: x = x + y;
  44. 44. Assignment operators (2) • JavaScript includes a number of shorthand assignment operators: x+=y; • is equivalent to: x = x + y; • Shorthand assignment operators are available for the four main arithmetic operations: +=, -=, /=, *=, plus a number of others.
  45. 45. Arithmetic operators • The simplest arithmetic operators are: addition (+), subtraction (-), multiplication (*), and division (/) • Other useful arithmetic operators are the unary (with just one operand) increment (++) and decrement (--) operators • For example: x = 1; x++; // x is set to 2 y = x++; // y is set to 2 and x is set to 3 z = ++y; // y and z set to 3
  46. 46. Comparison operators Operator Symbol Equal == Strictly equal === Not equal != Strictly not equal !== Greater than > Greater than or equal >= Less than < Less than or equal <=
  47. 47. Comparison operators (2) • Comparison operators are used to compare the operands and return a Boolean value (True or False) • Remember that there is an operator for assignment (=) and an operator to compare if two variables are equal (==) • The strictly equal (===) and strictly not equal (!==) operators compare the type of the variable too – if the type does not match, the variables are not equal.
  48. 48. Logical operators • Logical operators are used to connect different expressions • The basic operators are and (&&), or (||), not (!) • Look at the examples: x == 1 && y ==2 // True if x equals 1 and y equals 2 x == 1 || y == 2 // True if x equals 1 or if y equals 2 x != 1 // True if x is not equal to 1
  49. 49. String operators • JavaScript has an operator (+) to concatenate strings • The + operator is also used to add two numbers – You can see how the + operator has two different meanings, one between numbers and another between strings
  50. 50. Activity #2 • Creare a script asking for the name and surname of a person when loading the page (use prompt(), and store name and surname in 2 different variables) • Wellcome the user with a message (alert()) "Wellcome name surname".
  51. 51. Activity #3: writing stylesheets! • Ask the user (prompt()) whether he would like a normal, big or low size for fonts in the screen • Use JavaScript to write an internal stylesheet reflecting the user’s preferences – Customise the tags h1, h2, body and p – Demonstrate how the user choice will change the style of content in the page
  52. 52. Precedence • There are situations in which different operators are used, one after the other • If an expression has more than one operator there are multiple ways in which the expression can be evaluated • The expression: 4 / 2 + 2 * 3 • could evaluate to 12 or to 8 depending on which operator is applied first.
  53. 53. Precedence (2) • To prevent this type of ambiguity, operators are each given a precedence and an associativity. • Precedence controls the order in which operators are evaluated; a higher precedence operator, a larger precedence value, is evaluated first • For example, multiplication and division have a higher precedence than addition and subtraction.
  54. 54. Associativity • Associativity describes how to process them (right-to-left or left-to-right). • Associativity for arithmetic operators is left-to-right, and for comparison operators is right-to-left.
  55. 55. Associativity (2) • Now, if we have a look at this code: var x = 1; var y = 2; var z = 3; y += x *= z; • The value of x, y and z after the last operation depends on whether x *= z or y += x is executed first. • As we have two assignment operators, and their associativity is right-to-left, we know what will be the order in which they will be analysed.
  56. 56. STATEMENTS
  57. 57. Statements • Statements are instructions that tell the interpreter to perform an action. • You have already seen some examples of statements in: x = 1; counter --;
  58. 58. Conditional statements: if • The if statement allows you to test an expression and then make a branch in the script’s flow of control • You can nest if statements, obtaining multi-way branches
  59. 59. Conditional statements: if (2) if (number == 1) { // first branch: // applicable if number is '1' } else { if (number == 2) { // second branch: // applicable if number is '2' } else { // optional 'catch all' branch // statements applicable if number is not '1' or '2’ } }
  60. 60. Activity #4: if… else… • Ask the user whether s/he would want to receive the mailing list of the website (confirm()). • If the users accepts, ask for the email address (prompt()) and inform (alert()) the user he has been registered • Otherwise, thanks the user anyway (alert())
  61. 61. Conditional statements: switch • If all the branches depend on the same expression it is more efficient and clearer to use a switch statement
  62. 62. Conditional statements: switch (2) switch(number) { case 1: // statements applicable if number is '1’ break; case 2: // statements applicable if number is '2’ break; default: // optional 'catch all' branch break; }
  63. 63. Activity #5: using switch • Refactor activity #4, implementing it again with switch
  64. 64. Loop statements: for • The for statement is used to perform a sequence of one or more instructions a number of times • The general form of the for loop is: for ( [initialisation]; [test]; [increment] ) { [statement] } • The loop typically initialises a counter which is then tested against a terminating condition.
  65. 65. Loop statements: while • The general form of the while loop is: while ( [test];) { [statement] }
  66. 66. Debugging JavaScript • JavaScript code can be complex, and so it is important that one of the skills you acquire during this course is to be able to identify bugs in the code (this is called debugging).
  67. 67. Activity #6: debugging JavaScript • Try to inspect the following code. <script type="text/javascript " > var hello_world = "Hello World; var text_to_alert = ""; for (var c=1; c<=5; c++) { text_to_alert += hello_word + ": " + c + " time.n"; } alert(text_to_alert); </script>
  68. 68. Activity #6: debugging JavaScript (2) • There are two errors in the code (and a bonus error!); can you see them? – If you can see the errors – well done! It means that you are getting familiar with JavaScript syntax. • If you can’t see the errors, don’t worry. Open Firefox and install Firebug, if you haven’t done it yet. – Use the Firebug console and tools to identify the errors.
  69. 69. OBJECTS AND FUNCTIONS
  70. 70. Objects • Objects are a collection of properties, each of which has a name and a value • A property of an object is simply an additional piece of information held in the object about the object.
  71. 71. Objects (2) • Objects are typically used when you need to structure information • To access the value of a property, you have to use a ‘dot’ notation, as we did in our Hello Word example: greeting.text = "Hello World";
  72. 72. Functions • A function is a discrete set of instructions that carry out some task • Functions are used to group tasks and to re-use code – A function used inside a class is called method – We will see later what a class is and how to use them
  73. 73. Functions (2) • This is a function stub in JavaScript: function nameOfTheFunction([parameter_1], [parameter_2], [parameter_3]) { // you can use parameter_1, parameter_2, parameter_3 in your statements // parameter_1, parameter_2, parameter_3 are local variables, valid // only inside the function [statements] }
  74. 74. Functions (3) • This is how to invoke (or ‘call’) the function in the previous slide: nameOfTheFunction([parameter_a], [parameter_b], [parameter_c]); • The value of parameter_a will be passed to parameter_1, the value of parameter_b will be passed to parameter_2 and the value of parameter_c will be passed to parameter_3.
  75. 75. Local and global variables • parameter_a, parameter_b, parameter_c are said to be global variables, while parameter_1, parameter_2, parameter_3 are called local variables, valid only inside the function.
  76. 76. Local and global variables (example) function addNumber (number1, number2) { var number3 = number1 + number2; // the next line returns the value of total back // to the global context // otherwise it would not be available any more return number3; } var number3 = addNumber(3,5);
  77. 77. Variable scope • The scope of a variable is the region of code where it is defined and may be used. – A ‘global’ variable has global scope: it can be accessed anywhere in a script. – Other variables such as those declared within a function are ‘local’ variables and may only be accessed within the function. – Local variable names take precedence over those with greater scope.

×