0% found this document useful (0 votes)
2 views53 pages

2.JS Part1

This document serves as an introduction to JavaScript, covering its definition as a lightweight, interpreted scripting language used within HTML, its history, and syntax. It explains how to insert JavaScript into HTML files, the use of various JavaScript operators, variables, and data types, as well as the functionality of popup boxes like alert, confirm, and prompt. Additionally, it discusses best practices for writing JavaScript code and embedding external JavaScript files.

Uploaded by

musaissakah67
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views53 pages

2.JS Part1

This document serves as an introduction to JavaScript, covering its definition as a lightweight, interpreted scripting language used within HTML, its history, and syntax. It explains how to insert JavaScript into HTML files, the use of various JavaScript operators, variables, and data types, as well as the functionality of popup boxes like alert, confirm, and prompt. Additionally, it discusses best practices for writing JavaScript code and embedding external JavaScript files.

Uploaded by

musaissakah67
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 53

INTRODUCTION TO

JAVASCRIPT
Objectives
by the end of lecture, students should be able to:

◦ Define what type of programming language


JavaScript is.
◦ Describe the syntax of JavaScript.
◦ Insert a JavaScript program into HTML file.
◦ Control Structures
JavaScript History and
Versions
JavaScript was introduced as part of the Netscape 2.0
browser
Microsoft soon released its own version called JScript
ECMA developed a standard language known as
ECMAScript
ECMAScript Edition 3 is widely supported and is what we
will call “JavaScript”
JavaScript is the most popular scripting language on the
internet
WHAT IS JAVASCRIPT?
JavaScript is a scripting language (a scripting language is a
lightweight programming language) produced by Netscape
for use within HTML Web pages.
JavaScript is an interpreted language (means that scripts
execute without preliminary compilation)
JavaScript makes HTML pages more dynamic and
interactive.
JavaScript is loosely based on Java and it is built into all
the major modern browsers.
such as Internet Explorer, Mozilla, Firefox, Netscape, Opera.
What is JavaScript?
JavaScript is an interpreted language
◦ A program called an interpreter runs on the client’s computer.
◦ One instruction at a time, the interpreter figures out what to do
by reading your text program file.
◦ Interpreted programming language can run on any platform or
O/S as long as there is an interpreter that runs on that particular
setup.
◦ Interpreted languages are usually slower.
◦ Speed may not be a big factor because programs written in JavaScript are
not usually that complex
What is JavaScript?
(continued)
JavaScript is an object-oriented language
◦ program elements are organized into "objects"

JavaScript is case sensitive


Common uses for JavaScript are:
 image manipulation,
form validation,
dynamic changes of content.
improve the design
create cookies
JavaScript is?
(continued)
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
The <noscript> Tag
The <noscript> tag is used to display a message to non-JavaScript
browsers. This includes older browsers as well as current browsers with
JavaScript turned off. To use it, simply place text between the opening
and closing <noscript> tags:
<noscript>Your browser doesn’t support JavaScript.</noscript>
Browsers that do support JavaScript ignore the text between the
<noscript> tags. Older browsers ignore the <noscript> tags and display
the text.
Using HTML Comments
One problem with older browsers is that they might ignore the <script> tags and
display your JavaScript code in the body of the page. To avoid this, you can
enclose your JavaScript code within HTML comments:
<script language=”JavaScript”>
◦ <!-document.write(“Your browser supports JavaScript.”); // -->

</script>
The <!-- and --> tags begin and end the HTML comment. This will prevent older
browsers from displaying the script, while allowing the script to work on
browsers that support it.
The // in the last line is a JavaScript comment—this prevents the HTML comment
tag from being detected as a JavaScript error.
JavaScript Syntax
Created with basic text editors.
JavaScript statements are placed within the <script>... </script> tag in
HTML web page.
You can place the <script> tag containing your JavaScript anywhere
within you web page but it is preferred way to keep it within the
<head> tags.
The <script> tag alert the browser program to begin interpreting all the
text between these tags as a script. So simple syntax of your JavaScript
will be as follows
The JavaScript interpreter that will be running your code will look line-
by-line through the code to see what to do.
In order for the interpreter to understand what you've written, there
are some rules you must follow, i.e., syntax.
JavaScript Statements

Within the <script> tags,


you can use one or more JavaScript statements, or commands, to
create a script.
Each statement should end with a semicolon (;). E.g.:

<script language="javascript" type="text/javascript">


alert(“Hello!”);
</script>
JavaScript Syntax
(Continued)
<script language="javascript" type="text/javascript">
JavaScript code
</script>

The script tag takes two important attributes:


language: This attribute specifies what scripting language you are using.
Typically, its value will be JavaScript.
◦Although recent versions of HTML (and XHTML, its successor) have phased out the use
of this attribute.

type: This attribute is what is now recommended to indicate the scripting


language in use and its value should be set to "text/javascript".
JavaScript Syntax
(Continued)
The <script> tag: Defines a client-side script (JavaScript).
<script> tag either contains scripting statements, or it points to an external
script file through the src attribute.

The <noscript> tag: Defines an alternate content for users that have
disabled scripts in their browser or have a browser that doesn't support
client-side scripts. E.gs.
<noscript>Sorry, your browser does not support JavaScript!</noscript>
<noscript>
Sorry...JavaScript is needed to go ahead.
</noscript>
JavaScript Syntax
(Continued)
Whitespace and Line Breaks:

JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.
◦ you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and
understand.

Semicolons are Optional:

if your statements are each placed on a separate line. E.g.

<script language="javascript" type="text/javascript">


<!--
var1 = 10
var2 = 20
//-->
</script>

The following required semicolons :


<script language="javascript" type="text/javascript">
<!--
var1 = 10; var2 = 20;
//-->
</script>
JavaScript Syntax
(Continued)
Case Sensitivity:

JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and
any other identifiers must always be typed with a consistent capitalization of letters.

E.g. identifiers Time, TIme and TIME will have different meanings in JavaScript.

NOTE: Care should be taken while writing your variable and function names in JavaScript.

Comments in JavaScript:

JavaScript supports both C-style and C++-style comments, Thus:

Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript

Any text between the characters /* and */ is treated as a comment. This may span multiple lines

JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-line
comment, just as it does the // comment.

The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as //-->
JavaScript Syntax
(Continued)
JavaScript Placement in HTML File:
Script in <head>...</head> section.

Script in <body>...</body> section.

Script in <body>...</body> and <head>...</head> sections.

Script in and external file and then include in <head>...</head> section.

E.g.
<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
.......
</body>
</html>
Screen Output & Keyboard Input

- The JavaScript model for the HTML document is


the Document object

- The model for the browser display window is


the Window object
- The Window object has two properties, document
and window, which refer to the Document and
Window objects, respectively

- The Document object has a method, write, which


dynamically creates content

- The parameter is a string, often catenated from


parts, some of which are variables

e.g., document.write("Answer: " + result + "<br />");

- The parameter is sent to the browser, so it can


be anything that can appear in an HTML
document (<br />, but not \n)

- The Window object has three methods for creating


dialog boxes, alert, confirm, and prompt
Screen Output (continued)

1. alert("Hej! \n");
An alert is a box that pops
up to give the user a
- Parameter is plain text, not HTML
- Opens a dialog box which displays the message. Here's code for an
parameter string and an OK button alert that displays the
- It waits for the user to press the OK button message "Thanks for your
input!"
2. confirm("Do you want to continue?"); A confirm box is often used
if you want the user to
- Opens a dialog box and displays the parameter
and two buttons, OK and Cancel
verify or accept something.
- Returns a Boolean value, depending on which
button was pressed (it waits for one) When a confirm box pops
up, the user will have to
3. prompt("What is your name?", ""); click either "OK" or "Cancel"
to proceed.
- Opens a dialog box and displays its string
parameter, along with a text box and two A prompt box asks the user
buttons, OK and Cancel for some information and
provides a response field for
- The second parameter is for a default response her answer.
if the user presses OK without typing a
response in the text box (waits for OK)
Your First JavaScript Script:
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
JavaScript Operators
Operator Description Example Result

Arithmetic Operators + Addition x=2


y=2
4

x+y
- Subtraction x=5 3
y=2
x-y
* Multiplication x=5 20
y=4
x*y
/ Division 15/5 3
5/2 2,5
% Modulus (division 5%2 1
remainder)
10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--
JavaScript Operators – 2
Assignment Operators Operator Example Is The Same As

= x=y x=y

+= x+=y x=x+y

-= x-=y x=x-y

*= x*=y x=x*y

/= x/=y x=x/y

%= x%=y x=x%y
JavaScript Operators - 3
Operator Description Example

Comparison Operators == is equal to 5==8 returns false

=== is equal to (checks for both x=5


value and type)
y="5"

x==y returns true

x===y returns false

!= is not equal 5!=8 returns true

> is greater than 5>8 returns false

< is less than 5<8 returns true

>= is greater than or equal to 5>=8 returns false

<= is less than or equal to 5<=8 returns true


JavaScript Operators - 4
Operator Description Example

Logical Operators
&& and x=6

y=3

(x < 10 && y > 1) returns


true

|| or x=6

y=3

(x==5 || y==5) returns


false

! not x=6

y=3

!(x==y) returns true


JavaScript Variables
A variable is a name associated with a piece of data
Variables allow you to store and manipulate data in your programs
Think of a variable as a mailbox which holds a specific piece of
information
In JavaScript variables are created using the keyword var
Example:
var x = 10;
var y = 17;
var color = “red”;
var name = “Katie”;
JavaScript Variables
It is vitally important to distinguish between the name of the variable
and the value of the variable
For example, in the expression var color = “red” ,
◦ color is the name of the variable and red is the value. In other words, color
is the name of the box while red is what is inside the box
JavaScript Variables
oVariables are used to store data.
oA variable is a "container" for information you want to store.
oA variable's value can change during the script. You can refer
to a variable by name to see its value or to change its value.

Rules for variable names:


◦ Variable names are case sensitive
◦ They must begin with a letter or an underscore character
◦ strname – STRNAME (not same)
Data Types
Primitive Data Types Numbers - A number can be either
◦ Numbers an integer or a decimal
Strings - A string is a sequence of
◦ Strings letters or numbers enclosed in single
◦ Boolean (True, False) or double quotes
Boolean - True or False

Composite Data Types


◦ Arrays
◦ Objects
Variables & Data Types
JavaScript is untyped; It does not have explicit data types
For instance, there is no way to specify that a particular variable
represents an integer, string, or real number
The same variable can have different data types in different contexts
Implicit Data Types
Although JavaScript does not have explicit data types, it does have
implicit data types
If you have an expression which combines two numbers, it will evaluate
to a number
If you have an expression which combines a string and a number, it will
evaluate to a string
Example: Variables
var x = 4; Ans = x + y;
Ans => 15
var y = 11; Ans = x + y + z;
Ans => 15cat
Ans = z + x;
Ans = q + x + y;
var z = “cat”; Ans => cat4 Ans => 17411

var q = “17”; Ans = x + q;


Ans => 417
JavaScript Basic
Examples
<script>
document.write("Hello World!")
</script>  format text with HTML code - heading

<script>
alert("Hello World!")
</script>
Example
<script>
x=“Hello World!”
document.write(x)
</script>

<script>
x=“John Kofi….”
document.write(“Merhaba” +x)
</script>  use line break html code
JavaScript Popup Boxes
Alert Box
◦ a JS command that pops up a dialog box with a message
◦ An alert box is often used if you want to make sure information comes
through to the user.
◦ When an alert box pops up, the user will have to click "OK" to proceed.

<script>
alert("Hello World!")
</script>
JavaScript Popup Boxes
-2
Confirm Box
◦ A confirm box is often used if you want the user to verify or accept
something.
◦ When a confirm box pops up, the user will have to click either "OK" or
"Cancel" to proceed.
◦ If the user clicks "OK", the box returns true. If the user clicks "Cancel", the
box returns false.
JavaScript Popup Boxes
-3
Prompt Box
◦ A prompt box is often used if you want the
user to input a value before entering a
page.
◦ When a prompt box pops up, the user will
have to click either "OK" or "Cancel" to
proceed after entering an input value.
◦ If the user clicks "OK“, the box returns the
input value. If the user clicks "Cancel“, the
box returns null.
Prompt Box Example
<script>
x=prompt (“Michael Edna”, “ ”)
document.write(“Merhaba <br>”,
+x)
</script>
JavaScript Introduction
Prompt window example:

GUY-VINCENT JOURDAN :: CSI 3140 :: BASED ON JEFFREY C.


JACKSON’S SLIDES
Embedding External
JavaScript File
File JSHelloWorld.js:

HTML document executing this code:

script element used


to load and execute
JavaScript code
JavaScript Introduction
Web page and alert box generated by JSHelloWorld.html
document and JSHelloWorld.js code:

GUY-VINCENT JOURDAN :: CSI 3140 :: BASED ON JEFFREY C.


JACKSON’S SLIDES
JS Examples -1
<script>
x=3
y=20*x+12
alert(y)
</script>
Examples -2
<script>
s1=12
s2=28
toplam=s1+s2
document.write(“Michael Edna: "+toplam)
</script>
Control Structures
There are three basic types of control
structures in JavaScript: the if
statement, the while loop, and the
for loop
Each control structure manipulates a
block of JavaScript expressions
beginning with { and ending with }
The If Statement
The if statement allows If ( x = = 10)
JavaScript programmers to a make { y = x*x;
decision
}
Use an if statement whenever
you come to a “fork” in the else
program
{ x = 0;
}
Repeat Loops
A repeat loop is a group of statements that is repeated until a specified
condition is met
Repeat loops are very powerful programming tools; They allow for
more efficient program design and are ideally suited for working with
arrays
The While Loop
The while loop is used to execute
count = 0;
a block of code while a certain
condition is true while (count <= 10) {
document.write(count);
count++;
}
The For Loop
The for loop is used when there is a need to have a counter of some
kind
The counter is initialized before the loop starts, tested after each
iteration to see if it is below a target value, and finally updated at the
end of the loop
Example: For Loop
// Print the numbers 1 through 10 i=1 initializes the counter

for (i=1; i<= 10; i++) i<=10 is the target


document.write(i); value

i++ updates the


counter at the end
of the loop
Example: For Loop
<SCRIPT <SCRIPT
LANGUAGE= LANGUAGE=
"JavaScript"> "JavaScript">
document.write("1");
document.write("2"); for (i=1; i<=5; i++)
document.write("3"); document.write(i);
document.write("4");
document.write("5");
</SCRIPT>
Conditional Statements
to perform different actions for different decisions.
In JavaScript we have the following conditional statements:
if statement - use this statement if you want to execute some code
only if a specified condition is true
if...else statement - use this statement if you want 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 if you want to select
one of many blocks of code to be executed
switch statement - use this statement if you want to select one of
many blocks of code to be executed
Conditional Statements
-2
xamples -1
if (condition)
{
code to be executed if condition
is true
}

Examples -2

if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Conditional Statements
Examples
<script>
x=3
if(x<0)
{
alert (“negative”)
}
else
{
alert (“positive”)
}
</script>
Conditional Statements
Examples
<script>
- 2
c=confirm(“are you a member?”)
if(c)
{
alert (“I am a member”)
}
else
{
alert (“I am not a member”)
}
</script>
Conditional Statements
Examples - 3
<script>
p=prompt(“animal name)
if(p==“Dog")
{
alert(“yes")
}
else
{
alert(“No")
}
</script>

You might also like