Professional Documents
Culture Documents
Chapter 7 JVS
Chapter 7 JVS
JavaScript
Ken Ratri. MT
KR-2012
Introduction
JavaScript is THE scripting language of the Web. JavaScript is used in billions of Web pages to add functionality, validate forms, communicate with the server, and much more. A scripting language is a lightweight programming language. JavaScript was designed to add interactivity to HTML pages. JavaScript is programming code that can be inserted into HTML pages to be executed by the web browser. Many HTML designers are not programmers, but JavaScript is a language with a very simple syntax. Almost anyone can put small "snippets" of JavaScript code into HTML pages.
KR-2012
Introduction
JavaScript can:
Write directly to the HTML output stream Change the content or style of HTML elements React to HTML events and test HTML form input Delete and create HTML elements
KR-2012
Introduction
ECMA-262 is the official name of the JavaScript standard. JavaScript was invented by Brendan Eich at Netscape, and appeared for the first time in Netscape Navigator (a no longer existing web browser) in 1995. The JavaScript standard was adopted by the industry standard association ECMA in 1997. The development of the standard (ECMAScript-262) is a work in progress.
KR-2012
Introduction
JavaScript and Java are two completely different languages, in both concept and design. Java (developed by Sun) is acomplex programming language in the category as C and C++.
KR-2012
JavaScript How To
Scripts in HTML must be inserted between <script> and </script> tags. Scripts can be put in the <body> and in the <head> section of an HTML page. Scripts can also be placed in external files. External files often contain code to be used by several different web pages. External JavaScript files have the file extension .js.
KR-2012
How To
Scripts in HTML must be inserted between <script> and </script> tags. Scripts can be put in the <body> and in the <head> section of an HTML page.
To insert a JavaScript into an HTML page, use the <script> tag. The <script> and </script> tells where the JavaScript starts and ends. The lines between the <script> and </script> contain the JavaScript:
<script> alert("My First JavaScript"); </script>
KR-2012
JavaScript in <body>
<!DOCTYPE html> <html> <body><h1>My Web Page</h1> <p id="demo">A Paragraph</p> <script> document.getElementById("demo").innerHTML="My First JavaScript"; </script> </body> </html>
The JavaScript is placed at the bottom of the page to make sure it is executed after the <p> element is created.
KR-2012
10
KR-2012
To use an external script, point to the .js file in the "src" attribute of the <script> tag:
<!DOCTYPE html> <html> <body> <script src="myScript.js"></script> </body> </html>
External scripts cannot contain <script> tags.
11
KR-2012
JavaScript Statements
JavaScript statements are "commands" to the browser. The purpose of the statements is to tell the browser what to do. This JavaScript statement tells the browser to write Test Id " inside an HTML element with id="demo":
document.getElementById("demo").innerHTML=Test Id";
Semicolon ; Semicolon separates JavaScript statements. Normally you add a semicolon at the end of each executable statement. Using semicolons also makes it possible to write many statements on one line.
12 KR-2012
JavaScript Code
is a sequence of JavaScript statements. Each statement is executed by the browser in the sequence they are written. This example will manipulate two HTML elements:
<body> <h1>My Web Page</h1> <p id="demo">A Paragraph.</p> <div id="myDIV">A DIV.</div> <script> document.getElementById("demo").innerHTML="Hello ; document.getElementById("myDIV").innerHTML="How are you?"; </script> </body>
13 KR-2012
JavaScript Statements
JavaScript Statements
JavaScript ignores extra spaces.You can add white space to your script to make it more readable. The following lines are equivalent:
var name="Hege"; var name = "Hege";
15
KR-2012
Comments
Single line comments, start // Multi line comments start /* and end with */
<script type="text/javascript"> // Write a heading document.write("<h1>This is a heading</h1>"); // Write two paragraphs: document.write("<p>This is a paragraph.</p>"); /* The code below will write one heading and two paragraphs */ document.write("<p>This is another paragraph.</p>"); </script>
16 KR-2012
</body> </html>
17
KR-2012
18
KR-2012
React to Events
<!DOCTYPE html> <html> <body> <h1>My First JavaScript</h1> <p id="demo"> JavaScript can react to events. Like the click of a button. </p> <script> function myFunction() { document.getElementById("demo").innerHTML="Hello JavaScript!"; } </script> <button type="button" onclick="myFunction()">Click Me!</button> </body> </html>
19 KR-2012
Test Input
<!DOCTYPE html> <html> <body> <h1>My First JavaScript</h1> <input id="demo" type="text"> <script> function myFunction() { if(isNaN(document.getElementById("demo").value)) { alert("Not Numeric"); } } </script> <button type="button" onclick="myFunction()">Click Me!</button> </body></html>
21 KR-2012
Variables &Operators
<script> var x=5; var y=6; var z=5+6; document.write(x + "<br>"); document.write(y + "<br>"); document.write(z + "<br>"); </script>
22
KR-2012
Variables &Operators
Variable can have short names (like x and y) or more descriptive names (age, sum, totalvolume). Variable names must begin with a letter
Variable names can also begin with $ and _ (but we will not use it)
Variable names are case sensitive (y and Y are different variables)
23
KR-2012
In the example below we create a variable called carname, assigns the value "Volvo" to it, and put the value inside the HTML paragraph with id="demo":
24
KR-2012
You can declare many variables in one statement. Just start the statement with var and separate the variables by comma:
var name="Doe", age=30, job="carpenter";
Your declaration can also span multiple lines: var name="Doe", age=30, job="carpenter";
25
KR-2012
Data Types
String, Number, Boolean, Array, Object, Null, Undefined. A string can be any text inside quotes.You can use simple or double quotes:
var carname="Volvo XC60"; var carname='Volvo XC60';
var answer="It's alright"; var answer="He is called 'Johnny'"; var answer='He is called "Johnny"';
26
KR-2012
JavaScript variables can also hold other types of data, like text values (name=Andrew Benjamin"). In JavaScript a text like " Andrew Benjamin " is called a string. When you assign a text value to a variable, put double or single quotes around the value. When you assign a numeric value to a variable, do not put quotes around the value. If you put quotes around a numeric value, it will be treated as text.
Data Types
Numbers JavaScript has only one type of numbers. Numbers can be written with, or without decimals:
var x1=34.00; var x2=34; //Written with decimals //Written without decimals
// 12300000 // 0.00123
28
KR-2012
Data Types
Booleans Booleans can only have two values: true or false. Booleans are often used in conditional testing.You will learn more about conditional testing in a later chapter of this tutorial.
var x=true var y=false
29
KR-2012
Data Types
Data Types
Objects
An object is delimited by curly braces. Inside the braces the object's properties are defined as name and value pairs (name : value). The properties are separated by commas:
var person={firstname:"John", lastname:"Doe", id:5566}; The object (person) in the example above has 3 properties: firstname, lastname, and id. Spaces and line breaks are not important. Your declaration can span multiple lines: var person={ firstname : "John", lastname : "Doe", id : 5566 };
31 KR-2012
Data Types
Declaring Variable Types When you declare a new variable, you can declare its type using the "new" keyword: var carname=new String; var x= new Number; var y= new Boolean; var cars= new Array; var person= new Object;
32 KR-2012
JavaScript Objects
"Everything" in JavaScript is an Object: a String, a Number, an Array, a Date.... An object is just a special kind of data, with properties and methods. Properties are the values associated with an object. Methods are the actions that can be performed on objects.
33
KR-2012
JavaScript Objects
Objects in Real Life: If a car is an object: The properties of the car include name, model, weight, color, etc. All cars have these properties, but the values of those properties differ from car to car. The methods of the car could be start(), drive(), brake(), etc. All cars have these methods, but they are performed at different times.
34 KR-2012
35
KR-2012
Properties: length=5
Hello
36
KR-2012
Creating Objects
JavaScript has several built-in objects, like String, Date, Array, and more. You can also create your own objects. This example creates an object, and adds four properties to it:
personObj=new Object(); personObj.firstname="John"; personObj.lastname="Doe"; personObj.age=50; personObj.eyecolor="blue";
37
KR-2012
38
KR-2012
39
KR-2012
Function
A function is a block of code that will be executed when "someone" calls it A function is written as a code block (inside curly { } braces), preceded by the function keyword:
40
KR-2012
When you call a function, you can pass along some values to it, these values are called arguments or parameters. These arguments can be used inside the function. You can send as many arguments as you like, separated by commas (,)
myFunction(argument1,argument2)
Declare the argument, as variables, when you declare the function: function myFunction(var1,var2) { some code }
41
KR-2012
Sometimes you want your function to return a value back to where the call was made. This is possible by using the return statement. When using the return statement, the function will stop executing, and return the specified value. Syntax
function myFunction() { var x=5; return x; }
42
KR-2012
43
KR-2012
Operators
As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +:
Operator + * / % ++ -44
Description Addition Subtraction Multiplication Division Modulus (division remainder) Increment Decrement
Assignment Operators
Assignment operators are used to assign values to JavaScript variables. Given that x=10 and y=5, the table below explains the assignment operators:
Operator = += -= *= /= %=
45
KR-2012
The + operator can also be used to add string variables or text values together. Ex.
46
KR-2012
Adding two numbers, will return the sum, but adding a number and a string will return a string:
47
KR-2012
Comparison Operators
digunakan dalam pernyataan-pernyataan logis untuk menentukan kesetaraan atau perbedaan antara variabel-variabel atau nilai x=5, tabel di bawah ini menjelaskan operator pembanding
Description is equal to is exactly equal to (value and type) is not equal is greater than is less than is greater than or equal to is less than or equal to
Example x==8 is false x===5 is true x==="5" is false x!=8 is true x>8 is false x<8 is true x>=8 is false x<=8 is true
KR-2012
Logical Operators
Logical operators are used to determine the logic between variables or values. Given that x=6 and y=3, the table below explains the logical operators:
Operator && || !
Example (x < 10 && y > 1) is true (x==5 || y==5) is false !(x==y) is true
49
KR-2012
Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. Syntax
variablename=(condition)?value1:value2
50
KR-2012
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: if statement - use this statement to execute some code only if a specified condition is true if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false if...else if....else statement - use this statement to select one of many blocks of code to be executed switch statement - use this statement to select one of many blocks of code to be executed
51 KR-2012
If Statement
if (condition) { code to be executed if condition is true }
if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true }
52 KR-2012
Switch Statement
Use the switch statement to select one of many blocks of code to be executed.
switch(n) { case 1: execute code block 1 break; case 2: execute code block 2 break; default: code to be executed if n is different from case 1 and 2 }
54 KR-2012
Loop
Loops are handy, if you want to run the same code over and over again, each time with a different value.
document.write(cars[0] + "<br>"); document.write(cars[1] + "<br>"); document.write(cars[2] + "<br>"); document.write(cars[3] + "<br>"); document.write(cars[4] + "<br>"); document.write(cars[5] + "<br>");
Loop
for - loops through a block of code a number of times for/in - loops through the properties of an object while - loops through a block of code while a specified condition is true do/while - also loops through a block of code while a specified condition is true
KR-2011
For...In Statement
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) { the 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.
KR-2011
for (var i=0; i<5; i++) { x=x + "The number is " + i + "<br />"; }
58
KR-2012
var person={fname:"John",lname:"Doe",age:25};
59
KR-2012
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 }
60
KR-2012
While Loop
while (i<5) { x=x + "The number is " + i + "<br />"; i++; }
61
KR-2012
The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
do { code block to be executed } while (condition);
62
KR-2012
63
KR-2012
he break statement "jumps out" of a loop. The continue statement "jumps over" one iteration in the loop. It was used to "jump out" of a switch() statement.
for (i=0;i<10;i++) { if (i==3) { break; } x=x + "The number is " + i + "<br />"; }
KR-2011
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop. This example skips the value of 3:
for (i=0;i<=10;i++) { if (i==3) continue; x=x + "The number is " + i + "<br />"; }
KR-2011