Вы находитесь на странице: 1из 22

DMI-ST.

JOHN THE BAPTIST UNIVERSITY


MANGOCHI, MALAWI

Programme: Bachelor of Computer Science


Semester: VII
Module Code: 351CS73
Module Name: Web Programming

Unit 2 Detailed Notes

School of Computer Science & Information Technology

Module Teacher: Mrs.M.sinthuja ME (CSE)


Unit III Java Script:
Overview of JavaScript; Object orientation and JavaScript; General syntactic characteristics;
Primitives, Operations, and expressions; Screen output and keyboard input; Control statements;
Object creation and Modification; Arrays; Functions; Constructor; Pattern matching using
expressions; Errors in scripts; Examples.
Overview of JavaScript

 JavaScript is the world's most popular programming language.

 JavaScript is the programming language of the Web.

 JavaScript is easy to learn.

 JavaScript is a text-based programming language used both on the client-side and


server-side that allows you to make web pages interactive.

 Where HTML and CSS are languages that give structure and style to web
pages, JavaScript gives web pages interactive elements that engage a user.

 JavaScript, need is a text editor and a browser.

 JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in
1997.

 ECMA-262 is the official name of the standard. ECMAScript is the official name of the
language.

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 to program the behavior of web pages

<!DOCTYPE html>

<html>

<body>

<h2>My First JavaScript</h2>

<button type="button"

onclick="document.getElementById('demo').innerHTML = Date()">

Click me to display Date and Time.</button>

<p id="demo"></p>
</body>

</html>

Output

My First JavaScript

Click me to display Date and Time.

Fri Sep 25 2020 19:01:52 GMT+0530 (India Standard Time)

JavaScript Can Change HTML Content

• One of many JavaScript HTML methods is getElementById().


• The example below "finds" an HTML element (with id="demo"), and changes the
element content (innerHTML) to "Hello JavaScript":

<!DOCTYPE html>

<html>

<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello


JavaScript!"'>Click Me!</button>

</body>

</html>

Output

• What Can JavaScript Do?


• JavaScript can change HTML content.
• Click Me!
• After click me
• What Can JavaScript Do?
• Hello JavaScript!
• Click Me!
JavaScript Can Change HTML Attribute Values

In this example JavaScript changes the value of the src (source) attribute of an <img> tag:

<!DOCTYPE html>

<html>

<body>

<h2>What Can JavaScript Do?</h2>

<p>JavaScript can change HTML attribute values.</p>

<p>In this case JavaScript changes the value of the src (source) attribute of an image.</p>

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the


light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the


light</button>

</body>

</html>

Output

What Can JavaScript Do?


JavaScript can change HTML attribute values.

In this case JavaScript changes the value of the src (source) attribute of an image.

• Turn on the light   Turn off the light

JavaScript Can Change HTML Styles (CSS)

Changing the style of an HTML element, is a variant of changing an HTML attribute:

<!DOCTYPE html>

<html>

<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can change the style of an HTML element.</p>

<button type="button"
onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button>

</body>

</html>

Output
• What Can JavaScript Do?
• JavaScript can change the style of an HTML element.
• Click Me!
• After click me
• What Can JavaScript Do?
• JavaScript can change the style of an HTML element.
• Click Me!

JavaScript Can Hide HTML Elements

Hiding HTML elements can be done by changing the display style:

<!DOCTYPE html>

<html>

<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can hide HTML elements.</p>

<button type="button"
onclick="document.getElementById('demo').style.display='none'">Click Me!</button>

</body>

</html>

Output

• What Can JavaScript Do?


• JavaScript can hide HTML elements.
• Click Me!
• After click me
• What Can JavaScript Do?
• Click Me!
JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language
with first-class functions. While it is most well-known as the scripting language for Web
pages, many non-browser environments also use it, such as Node.js, Apache
CouchDB and Adobe Acrobat. 

JavaScript is a prototype-based, multi-paradigm, single-threaded, dynamic language,


supporting object-oriented, imperative, and declarative (e.g. functional programming) styles.

ECMAScript (European Computer Manufacturers Association Script)

The standard for JavaScript is ECMAScript. As of 2012, all modern browsers fully support


ECMAScript 5.1. Older browsers support at least ECMAScript 3. On June 17, 2015, ECMA
International published the sixth major version of ECMAScript, which is officially called
ECMAScript 2015, and was initially referred to as ECMAScript 6 or ES6. 

2 .Object orientation and JavaScript

JavaScript is a prototype based object oriented language, which means it doesn't have classes
rather it define behaviors using constructor function and then reuse it using the prototype. no
classes in JavaScript we have only Object. 

There are certain features or mechanisms which makes a Language Object Oriented like:
 Object
 Classes
 Encapsulation
 Inheritance

Object– An Object is a unique entity which contains property and methods. For example “car”


is a real life Object, which have some characteristics like color, type, model, horsepower and
performs certain action like drive. The characteristics of an Object are called as Property, in
Object Oriented Programming and the actions are called methods. An Object is an instance of a
class. Objects are everywhere in JavaScript almost every element is an Object whether it is a
function,arrays and string.
Note: A Method in javascript is a property of an object whose value is a function.
Object can be created in two ways in JavaScript:

Using an Object Literal

Using an Object Constructor

Classes– Classes are blueprint of an Object. A class can have many Object, because class is
a template while Object are instances of the class or the concrete implementation.
Before we move further into implementation, we should know unlike other Object Oriented
Language there is no classes in JavaScript we have only Object. To be more precise, JavaScript
is a prototype based object oriented language, which means it doesn’t have classes rather it
define behaviors using constructor function and then reuse it using the prototype.
Encapsulation – The process of wrapping property and function within a single unit is
known as encapsulation.Sometimes encapsulation refers to hiding of data or data
Abstraction which means representing essential features hiding the background detail. Most of
the OOP languages provide access modifiers to restrict the scope of a variable, but there are no
such access modifiers in JavaScript but there are certain way by which we can restrict the scope
of variable within the Class/Object.

Inheritance – It is a concept in which some property and methods of an Object is being used by
another Object. Unlike most of the OOP languages where classes inherit classes, JavaScript
Object inherits Object i.e. certain features (property and methods)of one object can be reused by
other Objects.

3. General syntactic characteristics

• 1.JavaScript are embedded either directly or indirectly in XHTML documents

• 2.Scripts can appear directly as the content of a <script> tag.

• 3.The type attribute of <script> must be set to “text/JavaScript”.

• 4.The JavaScript can be indirectly embedded in an XHTML document using the src
attribute of a <script> tag, whose value is name of a file that contains the script.

• Eg. <script type=”text/JavaScript” src=”tst_number.js”>

• </script>

• Closing tag is required even if script element has src attribute included.

• The indirect method of embedding JavaScript in XHTML has advantages of

1)Hiding the script from the browser user.

2)It also avoids the problem of hiding scripts from older browsers.

3)It is good to separate the computation provided by JavaScript from the layout and
presentation provided by XHTML and CSS respectively.

• But it is sometimes not convenient and cumbersome to place all JavaScriptcode in


separate file JavaScript identifiers or names are similar to programminglanguages.

1. Must begin with (-), or a letter. Subsequent characters may be letters,underscores or digits.

2. No length limitations for identifiers.

3. Case sensitive

4. No uppercase letters
All primitive values have one of the five primitive types:

• Number,

• String,

• Boolean,

• Undefined, or Null.

• In JavaScript, a primitive (primitive value, primitive data type) is data that is not an


object and has no methods.

• There are 6 primitive data types: string, number, bigint, boolean, undefined, and symbol.
...

• All primitives are immutable, i.e., they cannot be altered.

• Numeric literals – just like Java

• - All numeric values are stored in double-precision floating point

• - String literals are delimited by either ' or "

• - Can include escape sequences (e.g., \t)

• Boolean values are true and false

• - The only Null value is null

• - The only Undefined value is undefined

• - JavaScript is dynamically typed – any variable can

• be used for anything (primitive value or reference

• to any object)

• - The interpreter determines the type of a particular

• occurrence of a variable

• - Variables can be either implicitly or explicitly

• declared

• var sum = 0,

• today = "Monday",
• flag = false;

Expressions

• An expression is any valid set of literals, variables, operators, and expressions that
evaluates to a single value.

• The value may be a number, a string, or a logical value. Conceptually, there are two types
of expressions: those that assign a value to a variable, and those that simply have a value.
For example, the expression

• x = 7 is an expression that assigns x the value 7. This expression itself evaluates to 7.


Such expressions use assignment operators.

•  On the other hand, the expression 3 + 4 simply evaluates to 7; it does not perform an
assignment. The operators used in such expressions are referred to simply as operators.

• An expression is any valid unit of code that resolves to a value.

• JavaScript has the following expression categories:

• Arithmetic: evaluates to a number, for example 3.14159. (Generally uses arithmetic


operators.)

• String: evaluates to a character string, for example, "Fred" or "234". (Generally


uses string operators.)

• Logical: evaluates to true or false. (Often involves logical operators.)

JavaScript has the following kinds of expressions:

• Arithmetic: evaluates to a number, for example

• String: evaluates to a character string, for example "Fred" or "234"

• Logical: evaluates to true or false

• The special keyword null denotes a null value. In contrast, variables that have not been
assigned a value are undefined, and cannot be used without a run-time error.

Conditional expressions

• A conditional expression can have one of two values based on a condition. The syntax is

• (condition) ? val1 : val2


• If condition is true, the expression has the value of val1, Otherwise it has the value
of val2. You can use a conditional expression anywhere you would use a standard
expression.

• For example,

• status = (age >= 18) ? "adult" : "minor" This statement assigns the value "adult" to the
variable status if age is eighteen or greater. Otherwise, it assigns the value "minor" to
status.

• Primary expressions: Basic keywords and general expressions in JavaScript.

• Left-hand-side expressions: Left values are the destination of an assignment.

Operators

JavaScript supports the following types of operators.

• Arithmetic Operators

• Comparison Operators

• Logical (or Relational) Operators

• Assignment Operators

• Conditional (or ternary) Operators

Assignment operators:

• An assignment operator assigns a value to its left operand based on the value of its right
operand. The basic assignment operator is equal (=), which assigns the value of its right
operand to its left operand. That is, x = y assigns the value of y to x.

• The other operators are shorthand for standard arithmetic operations as follows:

• x += y means x = x + y

There are additional assignment operators for bitwise operations:

• x <<= y means x = x << y

• x >>= y means x = x >> y

• x >>>= means x = x >>> y

• x &= means x = x & y


• x ^= means x = x ^ y

• x |= means x = x | y

Arithmetic operators

• Arithmetic operators take numerical values (either literals or variables) as their operands
and return a single numerical value.

• Standard Arithmetic Operators

• The standard arthmetic operators are addition (+), subtraction (-), multiplication (*), and
division (/). These operators work in the standard way

• Modulus (%)

• The modulus operator is used as follows:


var1 % var2

The modulus operator returns the first operand modulo the second operand, that
is, var1 modulo var2, in the statement above, where var1 and var2 are variables. The
modulo function is the remainder of integrally dividing var1 by var2. For example, 12 %
5 returns 2

• The increment operator is used as follows:


var++ or ++var

• This operator increments (adds one to) its operand and returns a value. If used postfix,
with operator after operand (for example x++), then it returns the value before
incrementing. If used prefix with operator before operand (for example, ++x), then it
returns the value after incrementing.

• For example, if x is 3, then the statement

• y = x++

• increments x to 4 and sets y to 3.

• If x is 3, then the statement

• y = ++x

• increments x to 4 and sets y to 4.

• The decrement operator is used as follows:

• var-- or --var
• This operator decrements (subtracts one from) its operand and returns a value. If used
postfix (for example x--) then it returns the value before decrementing. If used prefix (for
example, --x), then it returns the value after decrementing.

• For example, if x is 3, then the statement

• y = x--

• decrements x to 2 and sets y to 3.

• If x is 3, then the statement

• y = --x

• decrements x to 2 and sets y to 2.

The bitwise logical operators

• The bitwise logical operators work conceptually as follows:

• The operands are converted to 32-bit integers, and expressed a series of bits (zeros and
ones).

• Each bit in the first operand is paired with the corresponding bit in the second operand:
first bit to first bit, second bit to second bit, and so on.

• The operator is applied to each pair of bits, and the result is constructed bitwise.

• The bitwise operators are:

• Bitwise AND & returns a one if both operands are ones.

• Bitwise OR | returns a one if either operand is one.

• Bitwise XOR ^ returns a one if one but not both operands are one.

A comparison operator

• A comparison operator compares its operands and returns a logical value based on
whether the comparison is true or not.

• The operands may be numerical or string values.

• When used on string values, the comparisons are based on the standard lexicographical
ordering.

• The operators are:


• Equal (= =): returns true if the operands are equal.

• Not equal (!=): returns true if the operands are not equal.

• Greater than (>): returns true if left operand is greater than right operand. Example: x > y
returns true if x is greater than y.

• Greater than or equal to (>=): returns true if left operand is greater than or equal to right
operand. Example: x >= y returns true if x is greater than or equal to y.

• Less than (<): returns true if left operand is less than right operand. Example: x < y
returns true if x is less than y.

• Less than or equal to (<=): returns true if left operand is less than or equal to right
operand. Example: x <= y returns true if x is less than or equal to y.

String operators

• In addition to the comparison operators, which may be used on string values, the
concatenation operator (+) concatenates two string values together, returning another
string that is the union of the two operand strings. For example,

• "my " + "string"

• returns the string

• "my string"

• The shorthand assignment operator += can also be used to concatenate strings. For
example, if the variable mystring is a string that has the value "alpha", then the
expression

• mystring += "bet“

• evaluates to "alphabet" and assigns this value to mystring.

Operator Precedence

• The precedence of operators determines the order they are applied when evaluating an
expression. You can override operator precedence by using parentheses.

• The precedence of operators, from lowest to highest is as follows:

• comma ,
• assignment = += -= *= /= %= <<= >>= >>>= &= ^= |=

• conditional ?:

• logical-or ||

• logical-and &&

• bitwise-or |

• bitwise-xor ^

• bitwise-and &

• equality == !=

• relational < <= > >=

• bitwise shift << >> >>>

• addition/subtraction + -

• multiply/divide * / %

• negation/increment ! ~ - ++ --

• call, member () [] .

Screen output and keyboard input

• JavaScript Display Possibilities.JavaScript can "display" data in different ways:

• Writing into an HTML element,

• using innerHTML.

• Writing into the HTML output

• using document.write().

• Writing into an alert box,

• using window.alert().

• Writing into the browser console,

• using console.log().

Using inner.HTML
• 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:

• <!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My First Paragraph</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html>

KEYBOARD INPUT

• Every time a key is pressed in a browser window a keyboard event is triggered.

• There are three types of keyboard events:

• keydown

• keypress

• keyup

• The keydown event occurs when a key is pressed, followed immediately by


the keypress event. Then, the keyup event is generated when the pressed key is released.

• The registered event handlers receive a subclass of the Event object


called KeyboardEvent with relevant information about the activities performed with the
keyboard.

• The keydown and keyup events keep track of the physical keys pressed on the keyboard.


These events allow to identify the pressed or released key using a code, this code can be
accessed through the keyCode attribute in the KeyboardEvent object.
Conditional statements

• Conditional statements are used to perform different actions based on different conditions

• 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

The if statement

• Use the if statement to specify a block of JavaScript code to be executed if a condition is


true.

Syntax

• if (condition) {
  //  block of code to be executed if the condition is true
}

• Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript
error.

Example

• Make a "Good day" greeting if the hour is less than 18:00:

• if (hour < 18) {
  greeting = "Good day";
}

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
}

The else if statement


• Use the else if statement to specify a new condition if the first condition is false.

Syntax

• 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
}

The switch statement

• The switch statement is used to perform different actions based on different conditions.

• Use the switch statement to select one of many code blocks to be executed.

Syntax

• switch(expression) {
  case x:
     // code block
    break;
  case y:
     // code block
    break;
  default:
    // code block
}

• 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.

• If there is no match, the default code block is executed.

EXAMPLE

• The getDay() method returns the weekday as a number between 0 and 6.

• (Sunday=0, Monday=1, Tuesday=2 ..)


• This example uses the weekday number to calculate the weekday name:

• switch (new Date().getDay()) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
     day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case 6:
    day = "Saturday";
}

LOOPS

• Loops can execute a block of code a number of times.

• The While Loop

• The while loop loops through a block of code as long as a specified condition is true.

Syntax

• while (condition) {
   // code block to be executed
}

• <!DOCTYPE html>

• <html>

• <body>
• <h2>JavaScript While Loop</h2>

• <p id="demo"></p>

• <script>

• var text = "";

• var i = 0;

• while (i < 10) {

• text += "<br>The number is " + i;

• i++;

• }

• document.getElementById("demo").innerHTML = text;

• </script>

• </body>

• </html>

The do/while statement

• 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.

Syntax

• do {
   // code block to be executed
}
while (condition);

Example

• The example below uses a do/while loop. The loop will always be executed at least once,
even if the condition is false, because the code block is executed before the condition is
tested:
• The example below uses a do/while loop. The loop will always be executed at least once,
even if the condition is false, because the code block is executed before the condition is
tested:

• Example

• do {
  text += "The number is " + i;
  i++;
}
while (i < 10);

Вам также может понравиться