Javascript Basics Tutorial

34
Document Prepared By: Arun Krishnamoorthy JavaScript Basics Pre-Requisites: Knowledge in ABAP This document teaches you the basics of JavaScript in comparison with ABAP Language. Remember JavaScript and ABAP are not similar languages or substitute for one another. Since every program has the basic syntax, keywords, variables, functions and conditions we are just going to compare how to do the same in JavaScript of what we do in ABAP. 1. Introduction to JavaScript 2. Syntax overview 3. Variables 4. Operators 5. Control statements 6. Control break statements 7. Functions 8. Events 9. Dialog Box 10. Predefined functions

Transcript of Javascript Basics Tutorial

Page 1: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

JavaScript Basics

Pre-Requisites: Knowledge in ABAP

This document teaches you the basics of JavaScript in comparison with ABAP Language.

Remember JavaScript and ABAP are not similar languages or substitute for one another. Since

every program has the basic syntax, keywords, variables, functions and conditions we are just

going to compare how to do the same in JavaScript of what we do in ABAP.

1. Introduction to JavaScript

2. Syntax overview

3. Variables

4. Operators

5. Control statements

6. Control break statements

7. Functions

8. Events

9. Dialog Box

10. Predefined functions

Page 2: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Chapter 1: Introduction to Javascript

What is JavaScript?

Javascript is a scripting language and it supports client side scripting.

JavaScript is a lightweight, interpreted programming language with object-oriented capabilities

that allows you to build interactivity into otherwise static HTML pages.

JavaScript is:

JavaScript is a lightweight, interpreted programming language

Designed for creating network-centric applications

Complementary to and integrated with Java

Complementary to and integrated with HTML

Open and cross-platform

Client-side JavaScript:

Client-side JavaScript is the most common form of the language. The script should be included

in or referenced by an HTML document for the code to be interpreted by the browser.

It means that a web page need no longer be static HTML, but can include programs that interact

with the user, control the browser, and dynamically create HTML content.

The JavaScript client-side mechanism features many advantages over traditional CGI server-side

scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail

address in a form field.

The JavaScript code is executed when the user submits the form, and only if all the entries are

valid they would be submitted to the Web Server.

JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and

other actions that the user explicitly or implicitly initiates.

Page 3: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Advantages of JavaScript:

The merits of using JavaScript are:

Less server interaction: You can validate user input before sending the page off to the

server. This saves server traffic, which means fewer loads on your server.

Immediate feedback to the visitors: They don't have to wait for a page reload to see if

they have forgotten to enter something.

Increased interactivity: You can create interfaces that react when the user hovers over

them with a mouse or activates them via the keyboard.

Richer interfaces: You can use JavaScript to include such items as drag-and-drop

components and sliders to give a Rich Interface to your site visitors.

Limitations with JavaScript:

We cannot treat JavaScript as a full-fledged programming language. It lacks the following

important features:

Client-side JavaScript does not allow the reading or writing of files. This has been kept

for security reason.

JavaScript cannot be used for networking applications because there is no such support

available.

JavaScript doesn't have any multithreading or multi-process capabilities.

Once again, JavaScript is a lightweight, interpreted programming language that allows you to

build interactivity into otherwise static HTML pages.

JavaScript Development Tools:

One of JavaScript's strengths is that expensive development tools are not usually required. You

can start with a simple text editor such as Notepad.

Since it is an interpreted language inside the context of a web browser, you don't even need to

buy a compiler.

To make our life simpler, various vendors have come up with very nice JavaScript editing tools.

Few of them are listed here:

Microsoft FrontPage

Macromedia Dreamweaver MX

Macromedia Home site 5

Netbeans IDE

Page 4: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Chapter 2: Syntax Overview

Syntax Overview:

In a webpage, Javascript statements are inserted inside <script> </script> tags.

This script can be included to the webpage by including the script code in :

1. <head>…</head> tags.

2. <body>…</body> tags.

3. Create a separate .js file and link it to the webpage.

The script tags contain two attributes namely:

Language – “javascript”

Text – “text/javascript”

Both the attributes indicates the scripting language used. Usage of type attribute is

recommended.

A simple Script program:

Page 5: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Script program:

Document is an object that calls the function write and writes the value in the webpage. This is

similar to that of ABAP statement displayed below.

Syntax Explanation:

Start with a keyword or object reference.

Literals are passed in double quotes in Script where it is passed in single quotes in

ABAP. We can also pass literals in single quotes in scripts.

End of the statement is indicated by ‘.’ in ABAP and ‘;’ in javascript.

White spaces and line breaks are ignored. Hence we can give any no of line spaces

between two statements as in ABAP.

Unlike ABAP, Javascript statements are case sensitive.

Page 6: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Comments:

Comments in ABAP can be written in following ways.

Whereas comments in Scripts can be written in three possible ways

The comment in javascript can be written as below.

All the lines between /* ….*/ are commented. (Multi line comments)

Single line Comments:

Page 7: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Chapter 3: Variables

Variables:

One of the fundamental characteristics of any programming languages is the set of data types

that the programming languages support.

Javascript support all the primitive data types like

1. Numbers

2. Strings

3. Boolean (true or false)

Let’s see how to create variables and assign value to the variables.

Page 8: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

ABAP Code:

Var is the keyword used in javascript for declaring the variable. The value to the variable can be

assigned at the time of declaring the variable or at any point of time in the program. We need not

declare data type for the variables. The variables in javascript are flexible and adjust itself to the

type of data assigned to it.

A number of variables can also be declared with a var keyword separated by comma.

E.g: var name, age;

Variables in javascript are case sensitive. Variable name and Name are two different variables

whereas name and Name are the same variables in ABAP.

Name of the variables in javascript should not begin with numbers. Following name for variables

is reserved and may not be used.

Page 9: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Chapter 4: Operators

Operators:

Operators form the backbone of any programming language. Operators help us in several ways

like performing calculation, checking conditions and so on.

We have different types of operators supported in our programming languages. The most

categories of operators are:

1. Arithmetic operator

2. Comparison operator

3. Logical operator

4. Assignment operator

5. Conditional operators

Arithmetic operators:

Page 10: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Example:

Assume that variable A holds the value 10 and Variable B holds value 20:

Here while writing the output I have concatenated the variable to the text using + operator and

written the output.

e.g document.write(“Literals are passed within quotations ” + variable );

Note: We don’t have the increment or decrement operator in ABAP, we normally achieve it

through a = a + 1;

Page 11: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Assignment operators:

Example:

Note: We don’t have any of the assignment operators other than equals to ABAP. All other

forms are achieved as in example. e.g a += b; is written as a = a + b.

Page 12: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Comparison operator:

All these operators are similar in usage as with ABAP, except that we don’t use double equal to

check the equality between two variable and not equal to operator differs from the normal usage.

Equal to operator:

In javascript, if (a == b);

In ABAP, if a = b.

Not equal to operator:

In Javascript, if (a!= b);

In ABAP if a<>b.

Note: All other operators remain same in usage compared with ABAP

Page 13: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Logical Operators:

We don’t have any of these operators in usage in our ABAP program, Instead we have keyword

“AND” for “&&”, “OR” for “||” and “NOT” for “!”.

In javascript, instead of keywords we need to use the symbolic representation. Remaining usage

of these operators remains the same as with that of ABAP.

Bitwise Operators:

Bitwise operators are bit advance and will be discussed in later chapters. We don’t have this

operation in ABAP.

Page 14: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Conditional Operators:

The condition operator checks condition and assign value to the variables. If the condition is true

then value after question mark is assigned, if condition is false value after colon is assigned.

If the value of x is greater than 18 then old enough will be the value assigned to variable votable.

Note: This operator is similar to that of if…else.. condition in ABAP.

Page 15: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Chapter 5: Control Statements

Control statement:

Control statements are used to control flow logic or sequence of statement execution in other

words. Like in ABAP we have the control statement in Javascript.

They are as below:

1. If else condition

2. While

3. Do while

4. Switch case

5. For loop

6. For in

IF Conditions:

If condition is true then executes the statement within the if block.

Syntax:

If (condition) {

Statements to be executed;

};

Example:

Note: In ABAP we write within if…endif block and we don’t have brackets. In Javascript there

is no endif, an block is formed with curly brackets.

Page 16: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

IF...ELSE… Condition:

If the condition is true then statements within if block executes else the statement within the else

block executes. In simple words if not this, then do that.

Syntax:

If (condition) {

Statement to be executed;

}

Else {

Statement to be executed;

};

Example:

Page 17: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

IF…ELSEIF…condition:

This is similar to if else condition, the sequence executes till the condition matches and condition

can be checked for each block.

Syntax:

If (condition) {

Statements to be executed;

} else if (condition) {

Statements to be executed;

} else

…..

};

Example:

Page 18: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Switch Case:

Case statement in ABAP is Switch case in Javascript.

Syntax:

switch (expression)

{

case condition 1: statement(s)

break;

case condition 2: statement(s)

break;

...

case condition n: statement(s)

break;

default: statement(s)

}

Example:

Page 19: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Note: Break statements are important after every case condition, otherwise the output will be

like this.

While Condition:

When we want some statements to be executed again and again until the condition fails we use

the while statements.

Syntax:

while (expression) {

Statements to be executed;

};

Page 20: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Do while:

The do while also repeats the execution of statements repeatedly until the condition fails. The

difference between do while and while statement as below.

When condition fails in while statement no execution at all:

In do while even if the condition is not fulfilled the statement gets executed once.

Note: We do not have the do..while in ABAP, instead we have do..enddo statements.

Page 21: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

For Loops:

For loop is another form of looping. This is similar to that of loop statements in ABAP.

The For loops contains, three major parts:

1. Initialization

2. Condition

3. Iteration

Syntax:

for (initialization; test condition; iteration statement){

Statement(s) to be executed if test condition is true

}

Example:

For in:

There is one more looping keyword called for...in which is used to loop the JS objects. Since we

are not familiar with JS objects, skipping this part for now.

Page 22: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Chapter 6: Control breaks statements

Break:

Break statements exits the control out of the closing brackets.

Example:

The for loop breaks after the count becomes 3. Break keyword is similar to that of Exit keyword

in ABAP and it terminates the loop pass unconditionally. The remaining executions of the loop

are not continued further after triggering break keyword. In above example the loop pass us not

carried out the fourth and fifth time.

Page 23: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Continue:

Continue keyword is similar to that of continue keyword in ABAP and it terminates the loop pass

only for the satisfied condition. The remaining execution of loop continues further.

Page 24: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Using labels to control the flow:

We can specify labels in the program and control the sequence of execution. This concept is not

there in the ABAP.

We create a label by specifying the name before the loop pass starting and then control the

execution back to the point where the label is created. This is specifically used when there is a

loop inside a loop.

Example:

Page 25: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Chapter 7: Functions

Functions in javascript are similar to that of Function modules in ABAP. It is mainly used for

modularization and reusability of the Code.

The functions can be written anywhere in the html page or functions can be written in a separate

.js file and include it in the webpage.

Syntax:

function functionname(parameter-list)

{

Statements;

}

In the above example the function is called on the click of the button. The function to be called is

assigned to the button using on click attribute.

Let’s see an example of function with parameters:

Page 26: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Example:

Return statement in the function is the one that exports the value back. The variable in the

function perform add is not necessarily has to have the name as a and b respectively. It can be

any name, the functions take the arguments in the order it was passed. Say for example we have

variables num1 and num2 and call the method add (num1, num2) then num1 will be assigned to

a and num2 will be assigned to b.

The logic for the function can also be written at the time of calling the function.

e.g.

var result = new add (“x”, “y”, “return parseInt(x) + parseInt(y)” )

These types of functions are known as constructors and we will see a lot of those while creating

the UI element in UI5.

Page 27: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Chapter 8: Events

Events in Javascript are similar to that of events in ABAP object. Both indicate the occurrence of

something and that event is to be handled. Like in ABAP we have methods to handle the event

we have functions in javascript to handle the event.

To trigger the event handler method we don’t have to go through the event registration process as

in ABAP. We just have to specify the method to be called to the event attribute. Unlike ABAP

for an event we can have only one event handler method.

Take the previous example for function:

In the above example, on click attribute of the input tag is considered as event and is triggered by

the browser when the button is being clicked. The performadd() function is the event handler and

this function gets called when the user presses the button.

Likewise, each of the tags in html has a certain sets of events associated to it.

You can get to know about the events available for the tag, while working with code editing

software like macromedia. It list out the events with tag attributes, you can choose one and

assign functions to it.

Page 28: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Chapter 9: Dialog boxes

Dialog boxes in Javascript:

Javascript supports three important forms of dialog boxes. They are listed as below.

1. Alert dialog box

2. Confirmation dialog box

3. Prompt dialog box

Alert dialog box:

Alert dialog boxes are mostly used to create warning to the user or display some message to the

user in the form of pop up.

Alert is a standard function which creates the dialog box for the warning message. We just need

to pass the warning text to the standard function.

Page 29: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Confirmation dialog box:

Confirmation dialog box asks the user for action, whether yes or no to continue the process.

Executing the html file in browser and clicked on confirmation dialog:

Page 30: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

A pop up appears, clicking on Ok button.

While clicking on the ok button the browser returns the value of confirmation as true and when

we presses cancel button it return the value as false.

Page 31: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Prompt Dialog box:

Prompt dialog box is used to get the values from the user. The pop up opens with the text

provided to the prompt function asking for the value. The user entered value is returned and can

be captured in variable and proceed further.

Example:

Clicking on the prompt user name button calls the function my prompt which in turn calls the

function prompt(). Prompt() is a standard function that creates the dialog, this function has two

parameters one is text that appear on the popup and other is a default value to the input field.

Result after entering the name and clicking on ok.

Page 32: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Chapter 10: Predefined functions

Like we have predefined function modules in ABAP there are many predefined functions

available in Javascript.

Some of the standard functions which we saw in previous examples are:

Functions Description

alert() Alerts a warning message to the user

confirm() Ask for confirmation from the user

prompt() Prompt a value from the user

parseInt Converts the string into integers

write() Writes the value in the output page. Called by its object reference

document.write( )

getElementById() Get reference to HTML tag by using the ID. Called by its object reference

document.getElementById()

In this example I am going to use one such standard function that does a routine job like printing

the page.

Example:

You can also specify the function window.print() directly to the onclick event.

Page 33: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

Output:

Page 34: Javascript Basics Tutorial

Document Prepared By: Arun Krishnamoorthy

References:

http://www.tutorialspoint.com/javascript/index.htm

http://www.w3schools.com/js/default.asp