Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript Tutorial. What is JavaScript JavaScript is the programming language of HTML and the Web Programming makes computers do what you want them to.

Similar presentations


Presentation on theme: "JavaScript Tutorial. What is JavaScript JavaScript is the programming language of HTML and the Web Programming makes computers do what you want them to."— Presentation transcript:

1 JavaScript Tutorial

2 What is JavaScript JavaScript is the programming language of HTML and the Web Programming makes computers do what you want them to do

3 Why Study JavaScript JavaScript is one of the 3 languages all web developers must learn: 1.HTML to define the content of web pages 2.CSS to specify the layout of web pages 3.JavaScript is used to program the behavior of web pages

4 Where to put your JavaScript code JavaScript can be placed in either the and/or the sections of your HTML page

5 JavaScript Functions and Events A JavaScript function is a block of JavaScript code, that can be executed when "asked" for For example, a function can be executed when an event occurs, like when the user clicks a button

6 External JavaScript Scripts can also be placed in external files Example: Script.js function myFunction() { document.getElementById("demo").innerHTML = "Paragraph changed."; } External scripts are practical when the same code is used in many different web pages JavaScript files have the file extension.js

7 Using External JavaScript Files To use an external script, put the name of the script file in the src (source) attribute of a tag Example: You can place an external script reference in or as you like The script will behave as if it was located exactly where the tag is located

8 Advantages of using External JavaScript Files Placing JavaScripts in external files has some advantages: It separates HTML and code It makes HTML and JavaScript easier to read and maintain Cached JavaScript files can speed up page loads

9 Displaying information in JavaScript JavaScript can "display" data in different ways: Writing into an alert box, using window.alert() Writing into the HTML output using document.write() Writing into an HTML element, using innerHTML

10 Using window.alert() You can use an alert box to display information: window.alert(5 + 6);

11 Using window.alert()

12 Using document.write() For testing purposes, it is convenient to use document.write(): document.write(5 + 6); Document.write() simply writes the information in the web browser

13 Using innerHTML To access an HTML element, JavaScript can use the document.getElementById(id) method The id attribute defines the HTML element The innerHTML property defines the HTML content

14 Using innerHTML document.getElementById("demo").innerHTML = 5 + 6; The result is the same as: 11

15 Programming in JavaScript A computer program is a list of "instructions" to be "executed" by the computer In a programming language, these program instructions are called statements JavaScript is a programming language JavaScript statements are separated by semicolons

16 JavaScript Variables In a programming language, variables are used to store data values JavaScript uses the var keyword to declare variables An equal sign is used to assign values to variables In this example, x is defined as a variable. Then, x is assigned (or given) the value 6: var x; x = 6;

17 JavaScript Variables JavaScript variables are containers for storing data values. In programming, just like in algebra, we use variables to hold values. In programming, just like in algebra, we use variables in expressions (total = price1 + price2).

18 JavaScript Statements In HTML, JavaScript statements are "instructions" to be "executed" by the web browser This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo": document.getElementById("demo").innerHTML = "Hello Dolly.";

19 JavaScript Programs Most JavaScript programs contain many JavaScript statements The statements are executed, one by one, in the same order as they are written In this example x, y, and z are given values, and finally z is displayed: var x = 5; var y = 6; var z = x + y; document.getElementById("demo").innerHTML = z;

20 JavaScript Code Blocks JavaScript statements can be grouped together in code blocks, inside curly brackets {...}. The purpose of code blocks is to define statements to be executed together. One place you will find statements grouped together in blocks, are in JavaScript functions: function myFunction() { document.getElementById("demo").innerHTML = "Hello Dolly."; document.getElementById("myDIV").innerHTML = "How are you?"; }

21 JavaScript Identifiers All JavaScript variables must be identified with unique names. These unique names are called identifiers. Identifiers can be short names (like x and y), or more descriptive names (age, sum, totalVolume). The general rules for constructing names for variables (unique identifiers) are: Names can contain letters, digits, underscores, and dollar signs. Names must begin with a letter Names can also begin with $ and _ (but we will not use it in this tutorial) Names are case sensitive (y and Y are different variables) Reserved words (like JavaScript keywords) cannot be used as names

22 The Assignment Operator In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator. In JavaScript, x = x + 5 makes perfect sense: it assigns the value of x + 5 to x.

23 JavaScript Data Types JavaScript variables can hold numbers like 100, and text values like "John Doe". In programming, text values are called text strings. JavaScript can handle many types of data. Strings are written inside double or single quotes. Numbers are written without quotes. If you put quotes around a number, it will be treated as a text string.

24 Other JavaScript Data Types Booleans can only have two values: true or false. Booleans are often used in conditional testing. JavaScript arrays are written with square brackets. Array items are separated by commas. var cars = ["Saab", "Volvo", "BMW"]; An empty value has nothing to do with undefined. An empty string variable has both a value and a type. var car = "";

25 Declaring JavaScript Variables Creating a variable in JavaScript is called "declaring" a variable. You declare a JavaScript variable with the var keyword: var carName; After the declaration, the variable has no value. (Technically it has the value of undefined) To assign a value to the variable, use the equal sign: carName = "Volvo";

26 JavaScript Operators OperatorDescription +Addition -Subtraction *Multiplication /Division %Modulus ++Increment --Decrement

27 JavaScript String Operators The + operator can also be used to add (concatenate) strings. The += assignment operator can also be used to add (concatenate) strings: txt1 = "What a very "; txt1 += "nice day"; The result of txt1 will be: What a very nice day Adding two numbers will return the sum, but adding a number and a string will return a string: x = 5 + 5; y = "5" + 5; The result of x and y will be: 10 55

28 Working with Strings A JavaScript string simply stores a series of characters like "John Doe". A string can be any text inside quotes. You can use single or double quotes var carname = "Volvo XC60"; var carname = 'Volvo XC60'; The length of a string is found in the built in property length: var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var sln = txt.length;

29 Working with Numbers JavaScript has only one type of number. Numbers can be written with, or without, decimals. var x = 34.00; // A number with decimals var y = 34; // A number without decimals Extra large or extra small numbers can be written with scientific (exponent) notation: var x = 123e5; // 12300000 var y = 123e-5; // 0.00123

30 JavaScript Math Object The Math object allows you to perform mathematical tasks. The Math object includes several mathematical methods. Math.random() returns a random number between 0 (inclusive), and 1 (exclusive) Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments Math.round() rounds a number to the nearest integer And many more …

31 JavaScript Math Constants JavaScript provides 8 mathematical constants that can be accessed with the Math object: Math.E // returns Euler's number Math.PI // returns PI Math.SQRT2 // returns the square root of 2 Math.SQRT1_2 // returns the square root of 1/2 Math.LN2 // returns the natural logarithm of 2 Math.LN10 // returns the natural logarithm of 10 Math.LOG2E // returns base 2 logarithm of E Math.LOG10E // returns base 10 logarithm of E

32 JavaScript Dates The Date object lets you work with dates (years, months, days, hours, minutes, seconds, and milliseconds) A JavaScript date can be written as a string: Thu Apr 14 2016 13:49:53 GMT-0400 (Eastern Daylight Time) or as a number: 1460656193711 Dates written as numbers, specifies the number of milliseconds since January 1, 1970, 00:00:00.

33 Creating Date Objects The Date object lets us work with dates. A date consists of a year, a month, a day, an hour, a minute, a second, and milliseconds. Date objects are created with the new Date() constructor. There are 4 ways of initiating a date: new Date() new Date(milliseconds) new Date(dateString) new Date(year, month, day, hours, minutes, seconds, milliseconds) Using new Date(), creates a new date object with the current date and time

34 Creating Date Objects Using new Date(), creates a new date object with the current date and time Using new Date(number), creates a new date object as zero time plus the number. Zero time is 01 January 1970 00:00:00 UTC. The number is specified in milliseconds Using new Date(7 numbers), creates a new date object with the specified date and time: The 7 numbers specify the year, month, day, hour, minute, second, and millisecond, in that order

35 Displaying Dates When you display a date object in HTML, it is automatically converted to a string, with the toString() method document.getElementById("demo").innerHTML = d; is the same as document.getElementById("demo").innerHTML = d.toString(); The toDateString() method converts a date to a more readable format And more …

36 JavaScript Comparison and Logical Operators OperatorDescription ==equal to ===equal value and equal type !=not equal !==not equal value or not equal type >greater than <less than >=greater than or equal to <=less than or equal to ?ternary operator

37 JavaScript If...Else Statements Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. In JavaScript we have the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true Use else to specify a block of code to be executed, if the same condition is false Use else if to specify a new condition to test, if the first condition is false Use switch to specify many alternative blocks of code to be executed

38 The if Statement Use the if statement to specify a block of JavaScript code to be executed if a condition is true. if (condition) { block of code to be executed if the condition is true }

39 The else Statement Use the else statement to specify a block of code to be executed if the condition is false. if (condition) { block of code to be executed if the condition is true } else { block of code to be executed if the condition is false }

40 The else if Statement Use the else if statement to specify a new condition if the first condition is false. if (condition1) { block of code to be executed if condition1 is true } else if (condition2) { block of code to be executed if the condition1 is false and condition2 is true } else { block of code to be executed if the condition1 is false and condition2 is false }

41 The JavaScript Switch Statement Use the switch statement to select one of many blocks of code to be executed. This is how it works: The switch expression is evaluated once. The value of the expression is compared with the values of each case. If there is a match, the associated block of code is executed. Syntax switch(expression) { case n: code block break; case n: code block break; default: default code block }

42 JavaScript Loops Loops are handy, if you want to run the same code over and over again, each time with a different value. JavaScript supports different kinds of loops, mainly: for - loops through a block of code a number of times while - loops through a block of code while a specified condition is true

43 The For Loop The for loop is often the tool you will use when you want to create a loop. The for loop has the following syntax: for (statement 1; statement 2; statement 3) { code block to be executed } Statement 1 is executed before the loop (the code block) starts. Statement 2 defines the condition for running the loop (the code block). Statement 3 is executed each time after the loop (the code block) has been executed. Example for (i = 0; i "; }

44 The While Loop The while loop loops through a block of code as long as a specified condition is true. while (condition) { code block to be executed } Example while (i < 10) { text += "The number is " + i; i++; }

45 JavaScript Functions A JavaScript function is a block of code designed to perform a particular task. A JavaScript function is executed when "something" invokes it (calls it). A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). The parentheses may include parameter names separated by commas: (parameter1, parameter2,...) The code to be executed, by the function, is placed inside curly brackets: {}

46 JavaScript Functions (example) function name(parameter1, parameter2, parameter3) { code to be executed } Function parameters are the names listed in the function definition. Function arguments are the real values received by the function when it is invoked. Inside the function, the arguments behave as local variables.

47 Function Invocation/Return The code inside the function will execute when "something" invokes (calls) the function. When JavaScript reaches a return statement, the function will stop executing. Functions often compute a return value. The return value is "returned" back to the "caller“.

48 References www.w3schools.com


Download ppt "JavaScript Tutorial. What is JavaScript JavaScript is the programming language of HTML and the Web Programming makes computers do what you want them to."

Similar presentations


Ads by Google