JS 1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 57

JAVA SCRIPT - INTRODUCTION

Dr. A. Beulah
AP/CSE

Feb 15, 2022 A. Beulah Unit II 1


LEARNING OBJECTIVE
• Design and implement dynamic web pages with
JavaScript and DOM (K3)
• To Understand the concepts of JS

Feb 15, 2022 A. Beulah Unit II 2


INTRODUCTION
• JavaScript is one of the 3 languages all web developers must learn:

1. HTML to define the content of web pages ( Markups)


2. CSS to specify the layout of web pages (Rules)
3. JavaScript to program the behaviour of web pages (statements)

• Web pages are not the only place where JavaScript is used. Many
desktop and server programs use JavaScript.

• Node.js is the best known. Some databases, like MongoDB and


CouchDB, also use JavaScript as their programming language.
Feb 15, 2022 A. Beulah Unit II 3
JAVASCRIPT CAN CHANGE HTML CONTENT
• getElementById()
– "finds" a HTML element (with id=“ex"), and changes the element content (innerHTML) to "Hello
JavaScript"
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript</h2>

<p id=“ex">JavaScript changes HTML content.</p>

<button type="button"
onclick='document.getElementById(“ex").innerHTML =
"Hello You are learning JavaScript!"'>Click Me!</button>

</body>
</html>

Feb 15, 2022 A. Beulah Unit II 4


JAVASCRIPT CAN CHANGE HTML CONTENT
<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>

Feb 15, 2022 A. Beulah Unit II 5


JAVASCRIPT CAN CHANGE HTML ATTRIBUTE VALUES
<!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>

Feb 15, 2022 A. Beulah Unit II 6


CAN CHANGE HTML STYLES (CSS)
<!DOCTYPE html>
<html>
<body>

<h2>JS -- styles</h2>

<p id="demo">JavaScript changes the style of an HTML


element.</p>

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


style.color='blue'">Click Here</button>

</body>
</html>

Feb 15, 2022 A. Beulah Unit II 7


CAN HIDE HTML ELEMENTS
• Hiding HTML elements can be done by changing the display
style
<html>
<body>
<h2>No display</h2>
<p id="demo">Hello Students! You can
hide me.</p>

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

</body>
</html>
Feb 15, 2022 A. Beulah Unit II 8
CAN SHOW HTML ELEMENTS
• Showing hidden HTML elements can also be done by changing
the display style
<html>
<body>
<p>Show hidden element!</p>
<p id="demo" style="display:none">I am
hidden element</p>

<button type="button"
onclick="document.getElementById('demo')
.style.display='block'">Show hidden
element</button>

</body>
</html>
Feb 15, 2022 A. Beulah Unit II 9
WHERE TO WRITE JS
• The <script> Tag
– In HTML, JavaScript code is inserted between <script> and </script>
tags.
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "My First JavaScript";}
</script>
• JavaScript Functions and Events
– A JavaScript function is a block of JavaScript code, that can be
executed when "called" for.
– For example, a function can be called when an event occurs, like when
the user clicks a button.

Feb 15, 2022 A. Beulah Unit II 10


WHERE TO WRITE JS
• JavaScript in <head> or <body>
– can place any number of scripts in an HTML document.
– Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.
• JavaScript in <head>
<html>
<head>
<script> function myFunction() {
document.getElementById("demo").innerHTML =
"Script Inside head tag"; } </script>
</head>
<body>
<h2>JavaScript in Head</h2>
<p id="demo">Script comes here....</p>
<button type="button"
onclick="myFunction()">Inside head
tag</button>
</body>
</html>
Feb 15, 2022 A. Beulah Unit II 11
WHERE TO WRITE JS
• JavaScript in <body>
<html>
<body>
<h2>JavaScript inside Body Tag</h2>
<p id="demo">Demo</p>
<button type="button“ onclick="myFun
()"> Click here</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML
= "The script tag is placed inside body
tag"; }
</script>
</body>
</html>
Feb 15, 2022 A. Beulah Unit II 12
WHERE TO WRITE JS
• External JavaScript
<!DOCTYPE html> External scripts cannot contain <script> tags.
<html>
<body>
<h2>External JavaScript</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p>(myFunction is stored in an external file called "myScript.js")</p>
<script src="myScript.js"></script>
</body>
</html>

myScript.js
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}

Feb 15, 2022 A. Beulah Unit II 13


WHERE TO WRITE JS
• External JavaScript Advantages
– It separates HTML and code
– It makes HTML and JavaScript easier to read and maintain
– Cached JavaScript files can speed up page loads
– To add several script files to one page - use several script tags
<script src="myScript1.js"></script>
<script src="myScript2.js"></script>

Feb 15, 2022 A. Beulah Unit II 14


WHERE TO WRITE JS
• External References
– External scripts can be referenced with a full URL or with a path
relative to the current web page.

<script src="https://www.w3schools.com/js/myScript1.js"></script>
script located in a specified folder on the current web site
<script src="/js/myScript1.js"></script>
script located in the same folder as the current page
<script src="myScript1.js"></script>

Feb 15, 2022 A. Beulah Unit II 15


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().

Feb 15, 2022 A. Beulah Unit II 16


JAVASCRIPT STATEMENTS
• JavaScript statements are composed of:
– Values, Operators, Expressions, Keywords, and Comments.
• Semicolons ;
– Semicolons separate JavaScript statements.
– Add a semicolon at the end of each executable statement:
var a, b, c; // Declare 3 variables
a = 5; // Assign the value 5 to a
b = 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c

Feb 15, 2022 A. Beulah Unit II 17


WHITE SPACE
• White Space
– JavaScript ignores multiple spaces. You can add white space to your
script to make it more readable.
– The following lines are equivalent:
var person = "Hege";
var person="Hege";
– A good practice is to put spaces around operators ( = + - * / ):
var x = y + z;

Feb 15, 2022 A. Beulah Unit II 18


KEYWORDS

Feb 15, 2022 A. Beulah Unit II 19


JAVASCRIPT SYNTAX
• JavaScript syntax is the set of rules, how JavaScript programs
are constructed.
// How to create variables:
var x;
let y;

// How to use variables:


x = 5;
y = 6;
let z = x + y;

Feb 15, 2022 A. Beulah Unit II 20


JAVASCRIPT VALUES
• The JavaScript syntax defines two types of values:
• Fixed values
• Variable values
• Fixed values are called Literals.
• Variable values are called Variables.

Feb 15, 2022 A. Beulah Unit II 21


JAVASCRIPT LITERALS
• The two most important syntax rules for fixed values are:
– Numbers are written with or without decimals
– Strings are text, written within double or single quotes

Feb 15, 2022 A. Beulah Unit II 22


JAVASCRIPT VARIABLES
• In a programming language, variables are used to store data
values.
• JavaScript uses the keywords var, let and const to declare
variables.
• An equal sign is used to assign values to variables.

Feb 15, 2022 A. Beulah Unit II 23


JAVASCRIPT VARIABLES
• JavaScript variables are containers for storing data values.
<html>
<body>
<h2>JavaScript Variables</h2>
<p id="a"></p>
<p id="b"></p>
<p id="c"></p>
<p id="d"></p>
<script>
let a = "Hello"; // block scope
document.getElementById("a").innerHTML = a;
var b = 'Sam'; // global scope
document.getElementById("b").innerHTML = b;
//let a = 'hello’;
// SyntaxError: Identifier 'a' has already been declared
//document.getElementById("c").innerHTML = a;
var b = 'hello’; // No problem, 'Sam' is replaced.
document.getElementById("d").innerHTML = b; </script>
</body>
</html>
Feb 15, 2022 A. Beulah Unit II 24
LINE LENGTH AND LINE BREAKS
• For best readability, programmers often like to avoid code lines
longer than 80 characters.
• If a JavaScript statement does not fit on one line, the best place
to break it is after an operator:
document.getElementById("demo").innerHTML = "Hello Dolly!";

Feb 15, 2022 A. Beulah Unit II 25


OPERATORS
• Operators operate on operands to achieve the desired results
• JavaScript has numerous operators, classified in many
categories. We will look at only a few of them belonging to
the following categories:
– Assignment operators -- Arithmetic operators
– Comparison operators -- String operators
– Logical operators

Feb 15, 2022 A. Beulah Unit II 26


ASSIGNMENT OPERATOR “=”

• total_number_of_students = 984 ;

• title = “Understanding Computers” ;

• swapFlag = false ;

• x = y + 33 ;
Feb 15, 2022 A. Beulah Unit II 27
ARITHMETIC OPERATORS
Multiply 2*4→8
Divide 2 / 4 → 0.5
Modulus 5%2→1
Add 2+4→6
Subtract 2 - 4 → -2
Negate -(5) → -5
Feb 15, 2022 A. Beulah Unit II 28
COMPARISON OPERATORS
Not the same as the
assignment “=” operator

The “equal to (==)” Comparison Operator

if ( today == “Sunday” )
document.write(“The shop is closed”);

The string “The shop is closed” will be written to the


document only if the variable today has a value
equal to “Sunday”
Feb 15, 2022 A. Beulah Unit II 29
COMPARISON OPERATORS
a == b True if a and b are the same

a != b True if a and b are not the same

a>b True if a is greater than b

a >= b True if a is greater than or equal to b

a<b True if a is less than b

a <= b True if a is less than or equal to b

Feb 15, 2022 A. Beulah Unit II 30


COMPARISON OPERATORS
if ( x != 0 )
result = y / x;
else
result = “not defined”;

Feb 15, 2022 A. Beulah Unit II 31


LOGICAL OPERATORS

The “AND (&&)” Logical Operator

if ( (pitch == “hard”) && (bowler == “fast”) )


myStatus = “Pulled muscle”;

The value of the variable myStatus will be set to


“Pulled muscle” if both of the conditions are true
Feb 15, 2022 A. Beulah Unit II 32
LOGICAL OPERATORS

a && b AND True if both are true

a || b OR True of either or both are true

!a NOT True if a is false

Feb 15, 2022 A. Beulah Unit II 33


LOGICAL OPERATORS
if ( x || y )
document.write (“Either or both are true”);
else
document.write (“Both are false”);

Feb 15, 2022 A. Beulah Unit II 34


THE “+” STRING OPERATOR

The “+” operator can be used to concatenate two


strings

title = “java” + “script”

The value of the variable title becomes “javascript”


Feb 15, 2022 A. Beulah Unit II 35
; OPERATOR
Terminate all JavaScript statements with a semicolon. It is not
always necessary, but highly recommended.

a = 23 ;
quotient = floor( a / 2) ;
remainder = a % 2 ;

Feb 15, 2022 A. Beulah Unit II 36


JAVASCRIPT DATA TYPES
• JavaScript variables can hold many data types: numbers, strings, objects
and more:

• var length = 16; // Number


var lastName = "Johnson"; // String
var x = {firstName:"John",lastName:"Doe"}; // Object

Feb 15, 2022 A. Beulah Unit II 37


NUMBERS, STRINGS, OBJECTS
<h2>JavaScript</h2>

<p>When adding a string and a number, JavaScript will treat the number as a
string.</p>

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

<script>
var x = "Volvo" + 16;
document.getElementById("demo").innerHTML = x;
</script>

Feb 15, 2022 A. Beulah Unit II 38


JS TYPES ARE DYNAMIC

• JavaScript has dynamic types. This means that the same


variable can be used to hold different data types:
var x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String

Feb 15, 2022 A. Beulah Unit II 39


BOOLEANS
• Booleans can only have two values: true or false.
var x = 5;
var y = 5;
var z = 6;
(x == y) // Returns true
(x == z) // Returns false

Feb 15, 2022 A. Beulah Unit II 40


ARRAYS
• JavaScript arrays are written with square brackets.
• Array items are separated by commas.
• The following code declares (creates) an array called cars,
containing three items (car names):
var cars = ["Saab", "Volvo", "BMW"];

Feb 15, 2022 A. Beulah Unit II 41


ARRAYS
<p>Array indexes are zero-based, which means the first item is [0].</p>

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

<script>
var cars = ["Saab","Volvo","BMW"];

document.getElementById("demo").innerHTML = cars[0];
</script>

Feb 15, 2022 A. Beulah Unit II 42


OBJECTS
• JavaScript objects are written with curly braces {}.
• Object properties are written as name:value pairs, separated
by commas.
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};

Feb 15, 2022 A. Beulah Unit II 43


OBJECTS
<h2>JavaScript Objects</h2>

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

<script>
var person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

Feb 15, 2022 A. Beulah Unit II 44


THE TYPEOF OPERATOR
• You can use the JavaScript typeof operator to find the type of a
JavaScript variable.
• The typeof operator returns the type of a variable or an
expression:
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof "John Doe" // Returns "string"

Feb 15, 2022 A. Beulah Unit II 45


THE TYPEOF OPERATOR

typeof 0 // Returns "number"


typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
typeof (3 + 4) // Returns "number"

Feb 15, 2022 A. Beulah Unit II 46


UNDEFINED
• In JavaScript, a variable without a value, has the value
undefined. The type is also undefined.
var car; // Value is undefined, type is undefined

Feb 15, 2022 A. Beulah Unit II 47


EMPTY VALUES
• An empty value has nothing to do with undefined.
• An empty string has both a legal value and a type.
var car = ""; // The value is "", the typeof is "string"

Feb 15, 2022 A. Beulah Unit II 48


NULL
• It is supposed to be something that doesn't exist.
• In JS, the data type of null is an object.
• You can consider it a bug in JavaScript that typeof null is an object. It
should be null.
• You can empty an object by setting it to null
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
person = null; // Now value is null, but type is still an object
• You can also empty an object by setting it to undefined

Feb 15, 2022 A. Beulah Unit II 49


DIFFERENCE BETWEEN UNDEFINED AND NULL
• undefined and null are equal in value but different in type:
• typeof undefined // undefined
typeof null // object
• === equal value and equal type
== equal to
!== not equal value or not equal type
!= not equal to
null === undefined // false
null == undefined // true
Feb 15, 2022 A. Beulah Unit II 50
DIFFERENCE BETWEEN UNDEFINED AND NULL
<p>Undefined and null are equal in value but different in
type:</p>

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

<script>
document.getElementById("demo").innerHTML =
typeof undefined + "<br>" +
typeof null + "<br><br>" +
(null === undefined) + "<br>" +
(null == undefined);
</script>

Feb 15, 2022 A. Beulah Unit II 51


PRIMITIVE DATA
• A primitive data value is a single simple data value with no
additional properties and methods.
• The typeof operator can return one of these primitive types:
•string
•number
•boolean
•undefined

Feb 15, 2022 A. Beulah Unit II 52


COMPLEX DATA
• The typeof operator can return one of two complex types:
function
object
• The typeof operator returns "object" for objects, arrays, and null.
• The typeof operator does not return "object" for functions.

Feb 15, 2022 A. Beulah Unit II 53


COMPLEX DATA
<h2>JavaScript typeof</h2>
<p>The typeof operator returns object for both objects, arrays, and null.</p>
<p>The typeof operator does not return object for functions.</p>

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

<script>
document.getElementById("demo").innerHTML =
typeof {name:'john', age:34} + "<br>" +
typeof [1,2,3,4] + "<br>" +
typeof null + "<br>" +
typeof function myFunc(){};
</script>

Feb 15, 2022 A. Beulah Unit II 54


TEST YOUR KNOWLEDGE
• Use comments to describe the correct data type of the
following variables:
• var length = 16; //
• var lastName = "Johnson"; //
• var x = { firstName: "John", lastName: "Doe" }; //

Feb 15, 2022 A. Beulah Unit II 55


SUMMARY
• Introduction to HTML
• Basic HTML Tags
• Formatting tags, colors etc.

Feb 15, 2022 A. Beulah Unit II 56


REFERENCE

• Jackson, Jeffrey C. Web Technologies: A Computer Science


Perspective. Pearson India, 2011.
• HM Deitel-Deitel & Associates, Inc, Internet & world wide web:
How to program. Pearson Education India 5e.
• https://www.w3schools.com/html/

Feb 15, 2022 A. Beulah Unit II 57

You might also like