0% found this document useful (0 votes)
9 views

Javascript Notes

Uploaded by

kamblivivan20
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Javascript Notes

Uploaded by

kamblivivan20
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 89

WEB APP

DEVELOPMENT
CLIENT-SIDE SCRIPTING
Client Side Scripting
Why use client-side programming?
PHP already allows us to create dynamic web pages. Why also use
client-side scripting?
 client-side scripting (JavaScript) benefits:

 usability: can modify a page without having to post back to the server
(faster UI)
 efficiency: can make small, quick changes to page without waiting for
server
 event-driven: can respond to user actions like clicks and key presses
Why use client-side programming?
 server-side programming (PHP) benefits:
 security:
has access to server's private data; client can't see source code
 compatibility: not subject to browser compatibility issues

 power: can write files, open connections to servers, connect to databases, ...
TERMS USED: CLIENT SIDE AND
SERVER SIDE

• Client side and server side -describe where


application code runs.
• frontend vs. backend & client-side/server-side
• Serverless architecture-serverless vendors
What is Javascript?
 a lightweight programming language ("scripting language")
 used to make web pages interactive
 insert dynamic text into HTML (ex: user name)

 react to events (ex: page load user click)

 get information about a user's computer (ex: browser type)

 perform calculations on user's computer (ex: form validation)


What is Javascript?
 a web standard (but not supported identically by all browsers)
 NOT related to Java other than by name and some syntactic
similarities
What is JavaScript?
⚫ Created by Netscape
⚫ Originally called LiveWire then LiveScript
⚫ A client-side scripting language
⚫ Client-side refers to the fact that it is executed in the client (software)
that the viewer is using. In the case of JavaScript, the client is the
browser.
⚫ A server-side language is one that runs on the Web server.
Examples: PHP, Python
⚫ Interpreted on-the-fly by the client
⚫ Each line is processed as it loads in the browser
8
JavaScript is not Java
⚫ Completely different types of languages that just happen to be
similarly named
⚫ JavaScript - programs are interpreted in the browser
⚫ Java - programs are compiled and can be run as stand alone
applications

9
WHAT IS JAVASCRIPT?
JavaScript can execute not only in the browser, but also on the server,
or actually on any device that has a special program called the
JavaScript engine.
The browser has an embedded engine sometimes called a “JavaScript
virtual machine”.

Different engines have different “codenames”. For example:


V8 – in Chrome, Opera and Edge.
SpiderMonkey – in Firefox.
There are other codenames like “Chakra” for IE, “JavaScriptCore”,
“Nitro” and “SquirrelFish” for Safari.
11

WHAT IS JAVASCRIPT?
..CONTD
The engine (embedded if it’s a browser) reads (“parses”) the
script. Then it converts (“compiles”) the script to machine
code.
And then the machine code runs, pretty fast.
The engine applies optimizations at each step of the process. It
even watches the compiled script as it runs, analyzes the data
that flows through it, and further optimizes the machine code
based on that knowledge.
12

WHAT IS JAVASCRIPT?
..CONTD
• In-browser JavaScript can do everything related to webpage manipulation,
interaction with the user, and the webserver.
• For instance, in-browser JavaScript is able to:
• Add new HTML to the page, change the existing content, modify styles.
• React to user actions, run on mouse clicks, pointer movements, key
presses.
• Send requests over the network to remote servers, download and upload
files.
• Get and set cookies, ask questions to the visitor, show messages.
• Remember the data on the client-side (“local storage”).
13

PRINTING “HELLO WORLD”-USING


INTERNAL JAVASCRIPT
PRINTING “HELLO WORLD”-USING 14

EXTERNAL JAVASCRIPT
app.js
15

STATEMENTS IN JAVASCRIPT

• A statement is a piece of code that either declares a variable or


instructs the JavaScript engine to perform a task. A simple
statement ends with a semicolon (;).
• Note that the semicolon (;) is optional, but you should use it to
terminate a statement.
• For example, the following declares a variable and shows it to the
console:
let message = "Welcome to JavaScript";
console.log(message);
16

BLOCK

• A block is a sequence of zero or more simple statements. A block is delimited by


a pair of curly brackets {}. The purpose of code blocks is to define statements to
be executed together.
For example:
if (window.localStorage)
{
console.log('The local storage is supported’);
}
17

IDENTIFIERS
• An identifier is a name you choose for variables, parameters, functions, classes,
etc.
• An identifier name starts with a letter (a-z, or A-Z), an underscore(_), or a dollar
sign ($) and is followed by a sequence of characters including (a-z, A-Z),
numbers (0-9), underscores (_), and dollar signs ($).
• Identifiers in JavaScript are case-sensitive. For example, the message is different
from the Message.
18

COMMENTS
• Comments allow you to include notes or hints in JavaScript code. When executing the code, the
JavaScript engine ignores the comments.
• JavaScript supports both single-line and block comments.

• Single-line comments
• A single-line comment starts with two forward-slashes characters (//). It turns all the text following
the // on the same line into a comment. For example:
• // this is a single-line commentCode language: JSON / JSON with Comments (json)

• Block comments
• A delimited comment begins with a forward slash and asterisk /* and ends with the opposite */ as in
the following example:
• /* This is a block comment that can span multiple lines */
19

EXPRESSIONS
• An expression is a piece of code that evaluates to a value.
• For example: 2 + 1The above expression returns three.
20

KEYWORDS & RESERVED WORDS


• JavaScript defines a list of reserved keywords that have specific uses. You cannot use the
reserved keywords as identifiers.
21

VARIABLES
• A variable is a label that references a value like a number or string. Before using
a variable, you need to declare it.
Declaring a variable
• To declare a variable, you use the var keyword followed by the variable name as
follows:
var variableName;

• A variable name can be any valid identifier. For example:


var message;
22

VARIABLES
• In JavaScript, variable names follow these rules:
• Variable names are case-sensitive. This means that the message and Message are different
variables.
• Variable names can only contain letters, numbers, underscores, or dollar signs and
cannot contain spaces. Also, variable names must begin with a letter, an underscore (_) or
a dollar sign ($).
• Variable names cannot use the reserved words.
• By convention, variable names use camelCase like message, yourAge, and myName.
PRINTING “HELLO WORLD”-USING 23

CONSOLE
PRINTING “HELLO WORLD”-USING 24

DOCUMENT.WRITE
PRINTING “HELLO WORLD”-USING 25

DOCUMENT.WRITE
26

EXTERNAL SCRIPTS
If we have a lot of JavaScript code, we can put it into a separate file.
Script files are attached to HTML with the src attribute:
<script src="/path/to/script.js"></script>
Here, /path/to/script.js is an absolute path to the script from the site root. One can also
provide a relative path from the current page. For instance, src="script.js", just
like src="./script.js", would mean a file "script.js" in the current folder.

We can give a full URL as well. For instance:


<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
To attach several scripts, use multiple tags:
<script src="/js/script1.js"></script>
<script src="/js/script2.js"></script>
WHAT HAPPENS WHEN SRC IS SET AND 27

SCRIPT TAG HAS JAVACRIPT TOO?


A single <script> tag can’t have both the src attribute and code inside.
This won’t work:
<script src="file.js">
alert(1); // the content is ignored, because src is set
</script>
We must choose either an external <script src="…"> or a regular <script> with code.
The example above can be split into two scripts to work:
<script src="file.js"></script>
<script>
alert(1);
</script>
JAVASCRIPT CAN DISPLAY DATA IN 28

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().
PRINTING “HELLO WORLD”-USING 29

INNER HTML
CS380
30

A JAVASCRIPT STATEMENT: ALERT


alert("IE6 detected. Suck-mode enabled.");
JS

• a JS command that pops up a dialog box with a


message
JAVASCRIPT: OPERATORS
Let us take a simple expression 4 + 5 is equal to 9.
Here 4 and 5 are called operands and ‘+’ is called the operator.
JavaScript supports the following types of operators.
❑ Arithmetic Operators
❑ Comparison Operators
❑ Logical or Relational Operators
❑ Assignment Operators
❑ Conditional or ternary Operators

Arithmetic Operators JavaScript supports the following arithmetic operators − Assume


variable A holds 10 and variable B holds 20, then-
JAVASCRIPT: ARITHMETIC OPERATORS
JAVASCRIPT: ARITHMETIC OPERATORS
Note − Addition operator + works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".
Example The following code shows how to use arithmetic operators in JavaScript.
JAVASCRIPT: COMPARISON OPERATORS
Comparison Operators JavaScript supports the following comparison operators − Assume variable A holds
10 and variable B holds 20, then −
JAVASCRIPT: COMPARISONOPERATORS
Comparison Operators JavaScript supports the following comparison operators − Assume variable A holds
10 and variable B holds 20, then −
JAVASCRIPT: COMPARISON OPERATORS
Comparison Operators JavaScript supports the following comparison operators − Assume variable A holds
10 and variable B holds 20, then −
JAVASCRIPT: COMPARISON OPERATORS
JAVASCRIPT: COMPARISON OPERATORS
Example The following code shows how to use comparison operators in JavaScript.
JAVASCRIPT: COMPARISON OPERATORS
Example The following code shows how to use comparison operators in JavaScript.
JAVASCRIPT: LOGICAL OPERATORS
Logical Operators JavaScript supports the following logical operators − Assume variable A holds 10
and variable B holds 20, then −
JAVASCRIPT: LOGICAL OPERATORS
Example Try the following code to learn how to implement Logical Operators in JavaScript.
JAVASCRIPT: LOGICAL OPERATORS
JAVASCRIPT: BITWISE OPERATORS
JavaScript supports the following bitwise operators − Assume variable A holds 2 and variable B holds 3,
then −
JAVASCRIPT: BITWISE OPERATORS
JavaScript supports the following bitwise operators − Assume variable A holds 2 and variable B holds 3,
then −
JAVASCRIPT: BITWISE OPERATORS
JAVASCRIPT: BITWISE OPERATORS
JAVASCRIPT: BITWISE OPERATORS
Example Try the following code to implement Bitwise operator in JavaScript.
JAVASCRIPT: BITWISE OPERATORS
JAVASCRIPT: ASSIGNMENT OPERATORS
JavaScript supports the following assignment operators −
JAVASCRIPT: ASSIGNMENT OPERATORS
JavaScript supports the following assignment operators −
JAVASCRIPT: ASSIGNMENT OPERATORS
JAVASCRIPT: ASSIGNMENT OPERATORS
JAVASCRIPT: MISCALLENOUS OPERATOR
We will discuss two operators here that are quite useful in JavaScript: the
conditional operator ? : and the typeof operator.
Conditional Operator ? : The conditional operator first evaluates an expression
for a true or false value and then executes one of the two given statements
depending upon the result of the evaluation.
JAVASCRIPT: MISCALLENOUS OPERATOR
We will discuss two operators here that are quite useful in JavaScript: the
conditional operator ? : and the typeof operator.
Conditional Operator ? : The conditional operator first evaluates an expression
for a true or false value and then executes one of the two given statements
depending upon the result of the evaluation.
JAVASCRIPT: CONDITIONAL OPERATOR
JAVASCRIPT: TYPEOF OPERATOR
The typeof operator is a unary operator that is placed before its single operand,
which can be of any type. Its value is a string indicating the data type of the
operand. The typeof operator evaluates to "number", "string", or "boolean" if its
operand is a number, string, or boolean value and returns true or false based on
the evaluation.
JAVASCRIPT: TYPEOF OPERATOR
JAVASCRIPT: CONDITIONAL STATEMENTS
Conditional statements are used to decide the flow of execution based on
different conditions.
If a condition is true, you can perform one action and if the condition is false,
you can perform another action.

Different Types of Conditional Statements


There are mainly three types of conditional statements in JavaScript.
1. If statement
2. If…Else statement
3. If…Else If…Else statement
JAVASCRIPT: IF STATEMENT
JAVASCRIPT: IF STATEMENT
JAVASCRIPT: IF…ELSE STATEMENT
JAVASCRIPT: IF…ELSE STATEMENT
JAVASCRIPT: IF…ELSE IF…ELSE STATEMENT
JAVASCRIPT: IF…ELSE IF…ELSE STATEMENT
JAVASCRIPT: IF…ELSE IF…ELSE STATEMENT
JAVASCRIPT: 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
}
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.
JAVASCRIPT: SWITCH STATEMENT
JAVASCRIPT: BREAK KEYWORD
When JavaScript reaches a break keyword, it
breaks out of the switch block.
This will stop the execution of inside the block.
It is not necessary to break the last case in a switch
block.
The block breaks (ends) there anyway.
JAVASCRIPT: DEFAULT KEYWORD
The default keyword specifies the code to run if
there is no case match.
JAVASCRIPT: LOOPING STATEMENT
There are mainly four types of loops in JavaScript.
1. for loop
2. for/in a loop
3. while loop
4. do…while loop
JAVASCRIPT: FOR LOOP

1. The statement1 is executed first even before executing the looping code. So,
this statement is normally used to assign values to variables that will be used
inside the loop.
2. The statement2 is the condition to execute the loop.
3. The statement3 is executed every time after the looping code is executed
JAVASCRIPT: FOR LOOP
JAVASCRIPT: FOR…IN LOOP
Syntax:

The for...in statements combo iterates (loops) over the


properties of an object.
The code block inside the loop is executed once for each
property.
JAVASCRIPT: FOR…IN LOOP

Output:
JAVASCRIPT: WHILE LOOP

1. The “while loop” is executed as long as the specified


condition is true.
2. Inside the while loop, you should include the
statement that will end the loop at some point of time.
3. Otherwise, your loop will never end and your browser
may crash.
JAVASCRIPT: WHILE LOOP
JAVASCRIPT: DO..WHILE LOOP

1. The do…while loop is very similar to while loop. The


only difference is that in do…while loop, the block of
code gets executed once even before checking the
condition.
JAVASCRIPT: DO..WHILE LOOP
79

JAVASCRIPT BUILT IN FUNCTIONS

The following lines illustrate the use of built-in functions:


80

JAVASCRIPT USER DEFINED FUNCTIONS


There are following types of user-defined functions:
1. Named functions

2. Anonymous functions

3. Anonymous functions using Arrow function technique

4. Self-Executing Anonymous Functions


81

JAVASCRIPT NAMED FUNCTIONS


 In case of Named functions, their declarations are hoisted, which means
they are loaded into memory at compilation. That's why in the example
below, the function call works even before the function declaration
appears.
console.log(brag(3))
// I can do 3 pushups
function brag(count)
{
return("I can do " + count + " pushups");
}
console.log(brag(3)) // I can do 3 pushups
82

JAVASCRIPT ANONYMOUS FUNCTIONS


An anonymous function is simply a function that does not have a name.
Unlike named functions, which are declared with a name for easy reference,
anonymous functions are usually created for specific tasks and are often
assigned to variables or used as arguments for other functions.

In JavaScript, you normally use the function keyword followed by a name


to declare a function. However, in an anonymous function, the name is
omitted. These functions are often used in situations where you don’t need
to reuse the function outside its immediate context.

Syntax: Example:
JAVASCRIPT SELF-EXECUTING ANONYMOUS FUNCTIONS
Another common use of anonymous functions is to create self-executing
functions (also known as IIFE – Immediately Invoked Function
Expressions). These functions run immediately after they are defined.
Example:
JAVASCRIPT ANONYMOUS FUNCTION USING
ARROW FUNCTION TECHNIQUE
ES6 introduced a new and shorter way of declaring an anonymous function,
which is known as Arrow Functions. In an Arrow function, everything
remains the same, except here we don’t need the function keyword also.
Here, we define the function by a single parenthesis and then ‘=>’ followed
by the function body. Example:
JAVASCRIPT ANONYMOUS FUNCTION USING
ARROW FUNCTION TECHNIQUE
If we have only a single statement in the function body, we can even remove
the curly braces.

Example:
JAVASCRIPT SELF-EXECUTING ANONYMOUS
FUNCTION USING ARROW FUNCTION TECHNIQUE
Declaring a self-executing anonymous function (without the name itself)
and will see how we may declare it as well as how we may call it in order to
print the resultant value.

Example:
Syntax:
JAVASCRIPT DOM
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM is a standard for how to get, change, add, or delete HTML elements.
The HTML DOM model is constructed as a tree of Objects.

• JavaScript can change all the HTML elements in the page


• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page
CS380
88

EVENT-DRIVEN PROGRAMMING

 split breaks apart a string into an array using a


delimiter
 can also be used with regular expressions (seen later)
 join merges an array into a single string, placing a
delimiter between them
CS380
89

EVENT-DRIVEN PROGRAMMING

 you are used to programs start with a main


method (or implicit main like in PHP)
 JavaScript programs instead wait for user actions
called events and respond to them
 event-driven programming: writing programs
driven by user events
 Let's write a page with a clickable button that
pops up a "Hello, World" window...

You might also like