[Go to site: main page, start]

0% found this document useful (0 votes)
4 views60 pages

Java Script

JavaScript is a lightweight, interpreted programming language used for creating dynamic web content, functioning on both client and server sides. It allows interaction with HTML and CSS, supports various data types, and utilizes the Document Object Model (DOM) for manipulating web pages. The language is loosely typed and provides different ways to display data, including through HTML elements, alerts, and console logs.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views60 pages

Java Script

JavaScript is a lightweight, interpreted programming language used for creating dynamic web content, functioning on both client and server sides. It allows interaction with HTML and CSS, supports various data types, and utilizes the Document Object Model (DOM) for manipulating web pages. The language is loosely typed and provides different ways to display data, including through HTML elements, alerts, and console logs.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript

Introduction to JavaScript
• JavaScript is a programming language used to create dynamic content
for websites. (complex animations, clickable buttons, popup menus,
etc.)
• It is a lightweight, cross-platform, and single-threaded programming
language.
• It's an interpreted language that executes code line by line, providing
more flexibility.
Client side vs Server side
• Client Side: On the client side, JavaScript works along with HTML
and CSS. HTML adds structure to a web page, CSS styles it, and
JavaScript brings it to life by allowing users to interact with elements
on the page, such as actions on clicking buttons, filling out forms, and
showing animations.
• JavaScript on the client side is directly executed in the user's browser.
• JavaScript extends the core language by supplying objects to control a
browser and its Document Object Model (DOM)
Client side vs Server side
• Server Side: On the Server side (on Web Servers), JavaScript is used
to access databases, file handling, and security features to send
responses, to browsers.
Advanced Server Side version of JavaScript
• There are also more advanced server side versions of JavaScript such
as [Link], which allow you to add more functionality to a website
than downloading files (such as realtime collaboration between
multiple computers).
• Inside a host environment (for example, a web browser), JavaScript
can be connected to the objects of its environment to provide
programmatic control over them.
JavaScript vs Java
• The JavaScript language resembles Java but does not have Java's static
typing and strong type checking.
• JavaScript follows most Java expression syntax, naming conventions
and basic control-flow constructs which was the reason why it was
renamed from LiveScript to JavaScript.
• In contrast to Java's compile-time system of classes built by
declarations, JavaScript supports a runtime system based on a small
number of data types representing numeric, Boolean, and string
values.
JavaScript vs Java
• JavaScript is a very free-form language compared to Java.
• You do not have to declare all variables, classes, and methods.
• You do not have to be concerned with whether methods are public,
private, or protected
The DOM Model
• The HTML DOM (Document Object Model) is a structured
representation of a web page that,
• allows developers to access, modify, and control its content and
structure using JavaScript.
• It powers most dynamic website interactions, enabling features like
real-time updates, form validation, and interactive user interfaces.
Interpretation of the DOM
• The HTML Document Object Model (DOM) is a tree structure, where
each HTML tag becomes a node in the hierarchy.
• At the top, the <html> tag is the root element, containing both <head>
and<body> as child elements.
• These in turn have their own children, such as <title>, <div>, and
nested elements like <h1>, <p>,<ul>, and<li>.
Interpretation of the DOM
• Elements that contain other elements are labeled as container
elements,
• while elements that do not are simply child elements.
• This hierarchy allows developers to navigate and manipulate web
page content using JavaScript by traversing from parent to child and
vice versa.
Structure of the HTML DOM
Imagine your webpage as a tree:
• The document is the root.
• HTML tags like <html>, <head>, and <body> are branches.
• Attributes, text, and other elements are the leaves.
Working of the DOM
The DOM connects your webpage to JavaScript, allowing you to:
Access elements (like finding an <h1> tag).
Modify content (like changing the text of a <p> tag).
React to events (like a button click).
Create or remove elements dynamically.
Types of DOM
• Core DOM: It is standard model for all document types(All DOM
implementations must support the interfaces listed as "fundamental" in
the code specifications).
• XML DOM: It is standard model for XML Documents( as the name
suggests, all XML elements can be accessed through the XML DOM
.)
• HTML DOM: It is standard model for HTML documents (The
HTML DOM is a standard for how to get, change, add, or delete
HTML elements.)
Properties of the DOM
• Node-Based: Everything in the DOM is represented as a node (e.g.,
element nodes, text nodes, attribute nodes).
• Hierarchical: The DOM has a parent-child relationship, forming a tree
structure.
• Live: Changes made to the DOM using JavaScript are immediately
reflected on the web page.
• Platform-Independent: It works across different platforms, browsers,
and programming languages.
Writing JavaScript Programs
<html>
<head>
<title>Hello World</title>
</head>
<body>
<script type="text/javascript">
[Link]("Hello World")
</script>
<noscript>
Your browser doesn't support or has disabled JavaScript
</noscript>
</body>
</html>
Note
• Web pages that use the HTML tag <script language="javascript">, but that usage
has now been deprecated.
• The previous example uses the more recent and preferred
<script type="text/javascript">
• or you can just use <script> on its own if you like.
• The other thing to note in this example is the <noscript> and </noscript> pair of
tags.
• These are used when you wish to offer alternative HTML to users whose browsers
do not support JavaScript or who have it disabled.
Where to use the <script> tag?
• In addition to placing a script within the body of a document,
• you can put it in the <head> section, which is the ideal place if you wish to execute
a script when a page loads.
• Note: Another reason for placing a script in the document head is to enable
JavaScript to write things such as meta tags into the <head> section, because the
location of your script is the part of the document it writes to by default
Including JavaScript Files
• In addition to writing JavaScript code directly in HTML documents,
you can include files of JavaScript code either from your website or
from anywhere on the internet
• <script type="text/javascript" src="[Link]"></script>
Important Note:
The script file itself must not include any <script> or </script> tags, because they
are unnecessary: the browser already knows that a JavaScript file is being loaded.
Putting them in the JavaScript files will cause an error
Debugging JavaScript Errors
• JavaScript handles error messages in a way that changes according to
the browser used.
Semicolons
• A JS code does not require semicolons if there is only a single
statement in the line eg. x+=10
• For multiple statements, it is required
• However, when in doubt, always use a semi-colon
x+=10; y-=5; z=0
Variable
• It is a container that stores a particular value.
• Rules for defining variables in JS.
A variable may include only the letters a–z, A–Z, 0–9, the $ symbol, and the
underscore (_).
No other characters, such as spaces or punctuation, are allowed in a variablename.
The first character of a variable name can be only a–z, A–Z, $, or _ (no numbers).
Names are case-sensitive. Count, count, and COUNT are all different variables.
There is no set limit on variable name lengths.
Numeric Variable
• Creating a numeric variable is as simple as assigning a value, like
these examples:
count = 42
temperature = 98.4
• Like strings, numeric variables can be read from and used in
expressions and functions
String Variable
• JavaScript string variables should be enclosed in either single or double quotation marks, like this:
greeting = "Hello there"
warning = 'Be careful’
• You may include a single quote within a double-quoted string or a double quote within a
single-quoted string. But you must escape a quote of the same type by using the backslash
character, like this:
greeting = "\"Hello there\" is a greeting"
warning = '\'Be careful\' is a warning'
• To read from a string variable, you can assign it to another one, like this:
newstring = oldstring
• or you can use it in a function, like this:
status = "All systems are working"
[Link](status)
Arrays
• An array can contain string or numeric data, as well as other arrays.
• To assign values to an array, use the following syntax:
toys = ['bat', 'ball', 'whistle', 'puzzle', 'doll’]
To create a multidimensional array, nest smaller arrays within a larger one.
face = [['R', 'G', 'Y'], ['W', 'R', 'O'], ['Y', 'W', 'G’ ]]
OR
top = ['R', 'G', 'Y']
mid = ['W', 'R', 'O']
bot = ['Y', 'W', 'G']
face = [top, mid, bot]
Operators
• Can be mathematical, relational and logical in JS
Operators
Operators
Operators
Escape Characters
• Escape characters, as commonly used to insert quotation marks in strings, can also
be used to insert various special characters such as tabs, newlines, and carriage
returns.
• Here is an example using tabs to lay out a heading—it is included here merely to
illustrate escapes, because in web pages, there are better ways to do layout:
heading = "Name\tAge\tLocation"
Variable Typing
• JavaScript is a very loosely typed language;
• the type of a variable is determined only when a value is assigned and can change as the
variable appears in different contexts.
<script>
n = '838102050' // Set 'n' to a string
[Link]('n = ' + n + ', and is a ' + typeof n + '<br>')
n = 12345 * 67890; // Set 'n' to a number
[Link]('n = ' + n + ', and is a ' + typeof n + '<br>')
n += ' plus some text' // Change 'n' from a number to a string
[Link]('n = ' + n + ', and is a ' + typeof n + '<br>’)
</script>
Try this
n = "123"
n *= 1 // Convert 'n' into a number
n = 123
n += "" // Convert 'n' into a string
Or Try this
n = "123"
n = parseInt(n) // Convert 'n' into an integer number
n = parseFloat(n) // Convert 'n' into a floating point
number
n = 123
n = [Link]() // Convert 'n' into a string
Functions
• A simple function declaration in JS looks like:
• This function takes the two parameters passed, multiplies them together, and
returns the product.
<script>
function product(a, b)
{
return a*b
}
</script>
Global Variables
• Global variables are ones defined outside of any functions
• (or defined within functions but without the var keyword).

a=123
var b=156
if (a==123)
var c=789

Note: Regardless of whether you are using the var keyword, as long as a variable is
defined outside of a function, it is global in scope. This means that every part of a
script can have access to it
Local Variables
• Parameters passed to a function automatically have local scope,
• that is, they can be referenced only from within that function.
• To define a local variable that has scope only within the current
function, and has not been passed as a parameter, use the var
keyword.
• Example in next slide
Example
<script>
function test()
{
a = 123 // Global scope
var b = 456 // Local scope
if (a == 123)
var c = 789 // Local scope
}
</script>
<script>
test()
if (typeof a != 'undefined’) [Link]('a = "' + a + '"<br>')
if (typeof b != 'undefined’) [Link]('b = "' + b + '"<br>')
if (typeof c != 'undefined’) [Link]('c = "' + c + '"<br>')
function test()
{
a = 123
var b = 456
if (a == 123)
var c = 789 What is the output?
}

</script>
JavaScript Display Options
JavaScript can "display" data in different ways:
• Writing into an HTML element, using innerHTML or innerText.
• Writing into the HTML output using [Link]().
• Writing into an alert box, using [Link]().
• Writing into the browser console, using [Link]().
Note: Changing the innerHTML property of an HTML element is the most
common way to display data in HTML.
Try
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "<h2>Hello World</h2>";
</script>
</body>
</html>
Another option
•To access an HTML element, use the
[Link](id) method.
•Then use the innerText property to change the inner text of
the HTML element.
Try
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
[Link]("demo").innerText = "Hello World";
</script>
</body>
</html>
Note:
Use innerHTML when you want to change an HTML element.
Use innerText when you only want to change the plain text.
The use of [Link](), used for testing
purposes
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
[Link](5 + 6);
</script>
</body>
</html>
Note: Using [Link]() after an HTML document is loaded, will delete all
existing HTML, hence this method should only be used for test
Using [Link]()
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
[Link](5 + 6);
</script>
</body>
</html>
Note on [Link]()
• You can skip the window keyword.
• In JavaScript, the window object is the global scope object.
• This means that variables, properties, and methods by default belong
to the window object.
• This also means that specifying the window keyword is optional.
• Rewrite the previous, using just alert
Using [Link]()
• For debugging purposes, you can call the [Link]() method in the
browser to display data.

<html>
<body>
<script>
[Link](5 + 6);
</script>
</body>
</html>
JavaScript print
• JavaScript does not have any print object or print methods.
• We cannot access output devices from JavaScript.
• The only exception is that you can call the [Link]() method in
the browser to print the content of the current window.
Try
<html>
<body>
<button this page</button>
</body>
</html>
Operators and their precedence
Unary, Binary and Ternary operators
• Unary operators, such as incrementing (a++) or negation (-a), take a
single operand.
• Binary operators, which represent the bulk of JavaScript
operators—including addition, subtraction, multiplication, and
division—take two operands.
• The one ternary operator, which takes the form ? x : y, requires
three operands. It’s a terse single-line if statement that chooses
between two expressions depending on a third one.
JS Logical Operators
<script>

a = 1; b = 0

[Link]((a && b) + "<br>")

[Link]((a || b) + "<br>")

[Link](( !b ) + "<br>")

</script>
Conditional Statements
• Conditionals alter program flow.
• They enable you to ask questions about certain things and respond to
the answers you get in different ways.
• There are three types of nonlooping conditionals:
the if statement,
the switch statement, and
the ? operator
The if statement
if (a > 100)
{ b=2
[Link]("a is greater than 100")
}
if (b == 10) [Link]("b is equal to 10")
The else statement
if (a > 100)
{
[Link]("a is greater than 100") }
else
{
[Link]("a is less than or equal to 100")
}
if (a > 100) {
[Link]("a is greater than 100")
}
else if(a < 100)
{
[Link]("a is less than 100")
}
else
{
[Link]("a is equal to 100")
}
The let, var and const keywords in Python
• JavaScript provides three ways to declare variables: var, let, and const,
but they differ in scope, hoisting behaviour, and re-assignment rules.
• var: Declares variables with function or global scope and allows
re-declaration and updates within the same scope.
• let: Declares variables with block scope, allowing updates but not
re-declaration within the same block.
• const: Declares block-scoped variables that cannot be reassigned after
their initial assignment.

You might also like