Unit 5
JavaScript
‘* JavaScript is the world's most popular programming language.
* JavaScript is the programming language of the Web.
* JavaScript is easy to lean.
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
What you can do with javascript?
JavaScript Can Change HTML Content
‘One of many JavaScript HTML methods is getElementByld().
The example below "finds" an HTML element (with id="demo"), and changes the element content
(innerHTML) to "Hello JavaScript"
document.getlementByld("'demo").innerHTML
lello JavaScript";
JavaScript Can Change HTML Attribute Values
JavaScript Can Change HTML Styles (CSS)
Changing the style of an HTML element, is a variant of changing an HTML attribute:
document.getElementByld("demo").style.fontSize Spx";
JavaScript Can Hide HTML Elements
Hiding HTML elements can be done by changing the display style:
document.getElementByld("demo").style.display = "none";
JavaScript Can Show HTML Elements
Showing hidden HTML elements can also be done by changing the display style:
document getElementByld("demo").style.display = "block";
The
code is inserted between tags.
Old JavaScript examples may use a type attribute:
Demo JavaScript in Head
’aragraph changed.";
A Paragraph
Try it
JavaScript in
In this example, a JavaScript function is placed in the section of an HTML page.
The function is invoked (called) when a button is clicked:
Demo JavaScript in Body
A Paragraph
'myFunction()">Try its/button>
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.) 2External JavaScript
Scripts can also be placed in external files:
function myFunction() {
document. getélementByld("demo").innerHTML = "Paragraph changed.";
}
External scripts are practical when the same code is used in many different web pages.
JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the src (source) attribute of
a
You can place an external script reference in or as you like.
The script will behave as if it was located exactly where the
External References
An external script can be referenced in 3 different ways:
With a full URL (a full web address)
With a file path (like /js/)
jout any path
This example uses a full URL to link to myScript.js:
This example uses a file path to link to myScript js:
This example uses no path to link to myScript.js:
JavaScript Display Possil S
JavaScript can “display” data in different ways:
Writing into an HTML element, using innerHTML.
Notes - CSCO 2302 - Introduction to Web Technology 2022-23 (Ms, Londhe K.W.)‘* 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 innerHTML
To access an HTML element, JavaScript can use the document.getElementByld(id) method
The id attribute defines the HTML element. The innerHTML property defines the HTML conter
DOCTYPE htmi>
My First Web Page
My First Paragraph
Using document.write|
For testing purposes, it is convenient to use document.writel):
My First Web Page
My first paragraph.
Using window.alert()
You can use an alert box to display data:
My First Web Page
My first paragraph.
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.)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:
IDOCTYPE htmi>
My First Web Page
My first paragraph.
Using console.log|
For debugging purposes, you can call the console.log() method in the browser to display data.
Script Print
JavaScript does not have any print object or print methods.
You cannot access output devices from JavaScript.
The only exception is that you can call the window.print() method in the browser to print the content of
the current window.
Print this page
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.) 5JavaScript Programs
‘A computer program is a list of “instructions” to be "executed" by a computer.
Ina programming language, these programming instructions are called statements.
A JavaScript program is a list of programming statements.
JavaScript Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
This statement tells the browser to write "Hello Dolly.” inside an HTML element with i
document.getElementByld("demo").innerHTML = "Hello Dolly.";
Most JavaScript programs contain many JavaScript statements.
The statements are executed, one by one, in the same order as they are written.
Semicolons ;
Semicolons separate JavaScript statements.
‘Add a semicolon at the end of each executable statement:
let a, b,c; // Declare 3 variables
// Assign the value 5 toa
b=6; — // Assign the value 6 tob
c=atb; // Assign the sum of aandbtoc
‘When separated by semicolons, multiple statements on one line are allowed:
jb=6;c=a+b;
JavaScript White Space
JavaScript ignores multiple spaces. You can add white space to your script to make it more readable.
The following lines are equivalent:
let person = "Hege";
JavaScript 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.getélementByld("‘demo").innerHTML =
"Hello Doliy!";
JavaScript Code Blocks
JavaScript statements can be grouped together in code blocks, inside curly brackets (...}.
The purpose of code blocks is to define statements to be executed together.
‘One place you will find statements grouped together in blocks, is in JavaScript functions:
Notes - CSCO 2302 - Introduction to Web Technology 2022-23 (Ms, Londhe K.W.)function myFunction() {
document. getElementByld("demo1").innerHTML = "Hello Dolly!
document. getElementByld("demo2").innerHTML = "How are you?"
}
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be performed.
Our Reserved Words Reference lists all JavaScript keywords.
JavaScript keywords are reserved words. Reserved words cannot be used as names for variables.
Here is a list of some of the keywords you will learn about in this tutorial:
Keyword | Description
Var Declares a variable
Let Declares a block variable
Const Declares a block constant
If Marks a block of statements to be executed on a condition
Switch | Marksa block of statements to be executed in different cases
For Marks a block of statements to be executed in a loop
Function | Declares a function
Return _| Exits a function
Try Implements error handling to a block of statements
JavaScript syntax is the set of rules, how JavaScript programs are constructed:
// How to create variables:
var x;
let ys
// How to use variables:
letz= x+y;
JavaScript Values
The JavaScript syntax defines two types of values:
Fixed values
Variable values
Fixed values are called Literals.
Variable values are called Variables.
JavaScript Literals
The two most important syntax rules for fixed values are:
1. Numbers are written with or without decimals:
10.50
1001
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.)2. Strings are text, written within double or single quotes:
“John Doe"
‘John Doe!
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.
In this example, x is defined as a variable. Then, xis assigned (given) the value 6:
let x;
JavaScript Operators
JavaScript uses arithmetic operators | + - * / ) to compute values:
(5 +6)* 10
JavaScript uses an assignment operator ( = ) to assign values to variables:
let x, v5
ye
JavaScript Expressions
An expression is a combination of values, variables, and operators, which computes to a value.
The computation is called an evaluation,
For example, 5 * 10 evaluates to 50:
5*10
Expressions can also contain variable values:
x*10
The values can be of various types, such as numbers and strings.
For example, "John" + "" + "Doe", evaluates to "John Doe”.
"John" +""+"Doe"
JavaScript Keywords
JavaScript keywords are used to identify actions to be performed.
The let keyword tells the browser to create variables:
let x, ys
x=546;
* 10;
The var keyword also tells the browser to create variables:
var x, ¥i
x=54+6;
yex*10;
Notes - CSCO 2302 - Introduction to Web Technology 2022-23 (Ms, Londhe K.W.)JavaScript Comments
Not all JavaScript statements are “executed”.
Code after double slashes // or between /* and */ is treated as a comment.
Comments are ignored, and will not be executed:
letx=5; //|will be executed
//x=6; | will NOT be executed
JavaScript Identifiers / Names
Identifiers are JavaScript names.
Identifiers are used to name variables and keywords, and functions.
The rules for legal names are the same in most programming languages.
A JavaScript name must begin with:
Aletter (A-Z or a-2)
A dollar sign ($)
Or an underscore (_)
Subsequent characters may be letters, digits, underscores, or dollar signs.
Note
Numbers are not allowed as the first character in names.
This way JavaScript can easily distinguish identifiers from numbers.
JavaScript is Case Sensitive
All JavaScript identifiers are case sensitive.
The variables lastName and lastname, are two different variables:
let lastname, lastName;
lastNam
lastname i
JavaScript does not interpret LET or Let as the keyword let.
JavaScript and Camel Case
Historically, programmers have used different ways of joining multiple words into one variable name:
Hyphens:
first-name, last-name, master-card, inter-city.
Hyphens are not allowed in JavaScript. They are reserved for subtractions,
Underscor
first_name, last_name, master_card, inter_city,
Upper Camel Case (Pascal Case):
FirstName, LastName, MasterCard, InterCity.
Lower Camel Case:
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.)JavaScript programmers tend to use camel case that starts with a lowercase letter:
firstName, lastName, masterCard, interCity.
JavaScript Character Set
JavaScript uses the Unicode character set.
Unicode covers (almost) all the characters, punctuations, and symbols in the world.
JavaScript comments can be used to explain JavaScript code, and to make it more readable.
JavaScript comments can also be used to prevent execution, when testing alternative code,
Single Line Comments
Single line comments start with //.
Any text between // and the end of the line will be ignored by JavaScript (will not be executed).
This example uses a single-line comment before each code line:
// Change heading:
document.getElementByld("myl").innerHTML = "My First Page";
// Change paragraph
document.getélementByld('my?").innerHTML = "My first paragraph.";
This example uses a single line comment at the end of each line to explain the code:
letx=5; // Declare x, give it the value of 5
let y=x +2; // Declare y, give it the value of x+2
Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript,
This example uses a multi-line comment (a comment block) to explain the code:
r
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page’
7%
document.getélementByld"my").innerHTML = "My First Page";
document.getElementByld("myP").innerHTML = "My first paragraph.";
Itis most common to use single line comments.
Block comments are often used for formal documentation.
Using Comments to Prevent Execution
Using comments to prevent execution of code is suitable for code testing,
‘Adding // in front of a code line changes the code lines from an executable line to a comment.
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.) 10Nn of one of the code lines:
My First Page"
‘My first paragraph.";
This example uses // to prevent exec
//document.getElementByld("myH").innerHTM|
document getlementByld(" myP").innerHTM
This example uses a comment block to prevent execution of multiple lines:
r
document.getElementByld("myH")innerHTMI
document.getElementByld("myP") innerHTM
A
‘My First Page";
‘My first paragraph.";
4 Ways to Declare a JavaScript Variabl
Using var
Using let
Using const
Using nothing
What are Variables?
Variables are containers for storing data (storing data values).
In this example, x, y, and z, are variables, declared with the var keyword:
var x= 5;
var y = 6;
var 2= x+y;
In this example, x, y, and z, are variables, declared with the let keyword:
letx=5;
let y=6;
letz=x+y3
In this example, x, y, and z, are undeclared variables:
x25;
y=6;
Zexty;
From all the examples above, you can guess:
x stores the value 5
y stores the value 6
zstores the value 11
When to Use JavaScript var?
Always declare JavaScript variables with var,let, orconst.
The var keyword is used in all JavaScript code from 1995 to 2015.
The let and const keywords were added to JavaScript in 2015,
If you want your code to run in older browsers, you must use var.
When to Use JavaScript const?
If you want a general rule: always declare variables with const.
If you think the value of the variable can change, use let.
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.) 1In this example, price1, price2, and total, are variables:
const pricel = 5;
const price2 = 6;
let total = price1 + price2;
The two variables price and price2 are declared with the const keyword.
‘These are constant values and cannot be changed.
The variable total is declared with the let keyword.
This is a value that can be changed.
JavaScript Identifiers
Al JavaScript variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
Names can contain letters,
Names must begin with a letter.
Names can also begin with $ and _ (but we will not use it in this tutorial).
Names are case sensitive (y and Y are different variables).
Reserved words (like JavaScript keywords) cannot be used as names.
Note
JavaScript identifiers are case-sensitive.
igits, underscores, and dollar signs.
The Assignment Operator
In JavaScript, the equal sign (=) is an "assignment" operator, not an “equal to" operator,
This is different from algebra. The following does not make sense in algebra:
X=XtS
In JavaScript, however, it makes perfect sense: it assigns the value of x +5 to x.
((t calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.)
Note
The “equal to” operator is written like
JavaScript Data Types
JavaScript variables can hold numbers like 100 and text values like "John Doe".
In programming, text values are called text strings.
JavaScript can handle many types of data, but for now, just think of numbers and strings.
Strings are written inside double or single quotes. Numbers are written without quotes.
If you put a number in quotes, it will be treated as a text string.
const pi= 3.14;
let person = "John Doe";
let answer = 'Yes | am!";
in JavaScript.
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.) 12Declaring a JavaScript Variable
Creating a variable in JavaScript is called "declaring" a variable.
You declare a JavaScript variable with the var or the let keyword:
var carName;
let carName;
After the declaration, the variable has no value (technically it is undefined).
To assign a value to the variable, use the equal sign:
carName = "Volvo";
You can also assign a value to the variable when you declare it:
let carName
In the example below, we create a variable called carName and assign the value "Volvo" to it.
Then we “output” the value inside an HTML paragraph with id="derno”:
Note
It's a good programming practice to declare all variables at the beginning of a script.
‘One Statement, Many Variables
You can declare many variables in one statement.
Start the statement with let and separate the variables by comma:
let person = "John Doe", carName = "Volvo", price = 20
A declaration can span multiple lines:
let person = "John Doe",
carName = "Volvo",
nnerHTML = carName;
Value = undefined
In computer programs, variables are often declared without a value. The value can be something that has
to be calculated, or something that will be provided later, like user input.
Avariable declared without a value will have the value undefined.
The variable carName will have the value undefined after the execution of this statement:
let carName;
Re-Declaring JavaScript Variables
If you re-declare a JavaScript variable declared with var, it will not lose its value.
The variable carNName will still have the value "Volvo" after the execution of these statements:
var carName
var carName;
Volvo";
Note
You cannot re-declare a variable declared with let or const.
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.) 13This will not work:
let carName = "Volvo";
let carName;
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +
letx=5 +243;
You can also add strings, but strings will be concatenated:
let x= "John" +""+ "Doe";
Also try this:
letx="5"+243;
Note
If you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated.
letx=2+3+"5";
JavaScript Dollar Sign $
Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable names:
let $ = "Hello World";
let $$$ = 2;
let $myMoney = 5;
Using the dollar sign is not very common in JavaScript, but professional programmers often use it as an
alias for the main function in a JavaScript library.
In the JavaScript library jQuery, for instance, the main function $ is used to select HTML elements. In
iQuery $("p"); means “select all p elements".
JavaScript Underscore (_)
Since JavaScript treats underscore as a letter, identifiers containing _ are valid variable names:
let _lastName = "Johnson";
let _x=2;
let _100 = 5;
let keyword
The let keyword was introduced in ES6 (2015),
Variables defined with let cannot be Redeclared.
Variables defined with let must be Declared before use.
Variables defined with let have Block Scope,
Cannot be Redeclared
Variables defined with let cannot be redeclared.
You cannot accidentally redeclare a variable.
With let you can not dot
let x= "John Doe";
letx=0;
// SyntaxError: 'x’ has already been declared
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.) 14With var you can:
Block Scope
Before ES6 (2015), JavaScript had only Global Scope and Function Scope.
ES6 introduced two important new JavaScript keywords: let and const.
These two keywords provide Block Scope in JavaScript.
Variables declared inside a { } block cannot be accessed from outside the block:
{
let x= 2;
}
//xcan NOT be used here
Variables declared with the var keyword can NOT have block scope.
Variables declared inside a { } block can be accessed from outside the block.
{
varx= 2;
}
//xCAN be used here
Redeclaring Variables
Redeclaring a variable using the var keyword can impose problems.
Redeclaring a variable inside a block will also redeclare the variable ou
var x= 10;
//Here xis 10
{
var x= 2;
If Here xis 2
}
// Here xis2
the block:
Redeclaring a variable using the let keyword can solve this problem.
Redeclaring a variable inside a block will not redeclare the variable outside the block:
let x= 10;
// Here xis 10
{
let x= 2;
// Here xis2
}
// Here xis 10
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.) 15Redeclaring
Redeclaring a JavaScript variable with var is allowed anywhere in a program:
var x= 2;
// Now xis 2
var x= 3;
1/ Now xis 3
With let, redeclaring a variable in the same block is NOT allowed:
var x= 2; // Allowed
letx=3; // Not allowed
{
letx=2;
// Allowed
letx=3; // Not allowed
Redeclaring a variable with let, in another block, IS allowed:
letx=2; // Allowed
// Allowed
i I Allowed
const keyword
The const keyword was introduced in ES6 (2015)
Variables defined with const cannot be Redeclared.
Variables defined with const cannot be Reassigned.
Variables defined with const have Block Scope.
Cannot be Reassigned
A const variable cannot be reassigned:
const PI = 3.141592653589793;
Pl= 3.14; // This will give an error
PL= PI+ 10; // This will also give an error
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.)
16Must be Assigned
JavaScript const variables must be assigned a value when they are declared:
const PI = 3.14159265359;
When to use JavaScript con:
Always declare a variable with const when you know that the value should not be changed.
Use const when you declare:
Anew Array
Anew Object
Anew Function
Anew RegExp
Constant Objects and Arrays
The keyword const is a little misleading
It does not define a constant value. It defines a constant reference toa value.
Because of this you can NOT:
Reassign a constant value
Reassign a constant array
Reassign a constant object
But you CAN:
Change the elements of constant array
Change the properties of constant object
Constant Arrays
You can change the elements of a constant array:
//Nou can create a constant array:
const cars = ["Saab", "Volvo", "BMW"];
// You can change an element:
cars[0] = "Toyota";
//You can add an element:
cars.push("Audi};
But you can NOT reassign the arra
const cars = ["Saab", "Volvo", "BMW"];
cars = ["Toyota", "Volvo", "Audi"]; // ERROR
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.)
7Constant Objects
You can change the properties of a constant object:
//Nou can create a const object:
const car = {type:"Fiat", mode|:"500", color:"white"};
//You can change a property:
car.color = "red";
//You can add a property:
car.owner = "Johnson";
But you can NOT reassign the object:
const car = {type:"Fiat", model:"500", color:"white"};
car = {type:"Volvo", model:"—X60", color:"red"};_// ERROR
JavaScript Operators
The assignment operator (=) assigns a value to a variable.
let x= 10;
The addition operator (+) adds numbers:
let x=5;
let y=2;
letz=x+y;
The multiplication operator (*) multiplies numbers.
let x=5;
lety
letz=x* y;
‘Types of JavaScript Operators
There are different types of JavaScript operators:
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
Conditional Operators
Type Operators
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.)
18JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic on numbers:
Operator Description
+ Addition
- Subtraction
= Multiplication
Exponentiation (ES2016)
Division
Modulus (Division Remainder)
Increment
Decrement
JavaScript Assignment Operators
Assignment operators assign values to JavaScript variables.
Operator | Example Same As
x=y x=y
X=xty
i x=x/y
= X=XHY
we xeK*ty
Adding JavaScript Strings
The + operator can also be used to add (concatenate) strings.
let text = "John";
let text2 = "Doe";
let text3 = text1 +" + text2;
JavaScript Comparison Operators
Operator Description
equal to
equal value and equal type
not equal
not equal value or not equal type
greater than
less than
greater than or equal to
Tess than or equal to
ternary operator
Notes - CSCO 2302 - Introduction to Web Technology 2022-23 (Ms, Londhe K.W.)
19JavaScript Logical Operators
JavaScript Type Operators
Operator | __ Description
&& logical and
I logical or
! logical not
Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an instance of an object type
JavaScript Bitwise Operators
Bit operators work on 32 bits numbers.
Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to a
JavaScript number.
Operator Description Example Same as Result | Decimal
& ‘AND 5&1 0101 & 0001 0001
T OR 514 0101 | 0001 0101
e NOT “5 0101 1010 10
a XOR SAL (0101 * 0002 0100 4
<« left shift 5<<1 O101<<1 1010 10
> right shift Sool 0101 >> 1 0010
>> unsigned right shift Sopp 0101 >>> 1 0010
Script Data Types
JavaScript provides different data types to hold different types of values.
There are two types of data types in JavaScript.
Primitive data type
Non-primitive (1
reference) data type
JavaScript is a dynamic type language, means you don’t need to specify type of the variable because itis
dynamically used by JavaScript engine. You need to use var here to specify the data type. It can hold any
type of values such as numbers, strings etc. For example:
var a=40;//holdi
Rahul";/
var
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.)
ing number
/Jholding string
20JavaScript primitive data types
There are five types of primitive data types in JavaScript. They are as follows:
Data Type Description
String represents sequence of characters e.g. “hello”
Number _ | represents numeric values e.g. 100
Boolean _ | represents boolean value either false or true
Undefined | represents undefined value
Null represents null i.e. no value at all
JavaScript non-primitive data types
The non-primitive data types are as follows:
Data Type Description
Object represents instance through which we can access members
Array represents group of similar values
RegExp represents regular expression
JavaScript variables can hold different data types: numbers, strings, objects and more:
let length = 16; // Number
let lastName = "Johnson"; /{ String
// Object
let x = {firstName:"John", lastName:"Doe"
The Concept of Data Typ
In programming, data types is an important concept.
To be able to operate on variables, itis important to know something about the type.
Without data types, a computer cannot safely solve this:
let x= 16 + "Volvo";
Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will it produce a result?
JavaScript will treat the example above as:
let x= "16"
When adding a number and a string, JavaScript will treat the number as a string.
"Volvo";
JavaScript Strings
Astring (or a text string) is a series of characters like "John Doe".
Strings are written with quotes. You can use single or double quotes:
let carName: folvo XC60"; // Using double quotes
let carName2 = ‘Volvo XC60'; // Using single quotes
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
let answer = "It's alright"; / Single quote inside double quotes
let answer2 = "He is called ‘Johnny; // Single quotes inside double quotes
let answer = 'He is called "Johnny"; // Double quotes inside single quotes
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.) a1JavaScript Numbers
JavaScript has only one type of numbers.
Numbers can be written with, or without decimals:
let x1 = 34.00; // Written with decimals
letx2= 34; — // Written without decimals
Extra large or extra small numbers can be written with scientific (exponential) notation:
lety=123e5; //12300000
letz=123e-5; // 0.00123
JavaScript Booleans
Booleans can only have two values: true or false.
letx
letz
y) // Returns true
(x==2) — // Returns false
Booleans are often used in conditional testing.
JavaScript 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):
const cars = ["Saab", "Volvo", "BMW";
Array indexes are zero-based, which means the first item is [0], second is [1], and so on
JavaScript Objects
JavaScript objects are written with curly braces {}.
Object properties are written as name:value pairs, separated by commas.
const person = {firstName: "John", lastName:"Doe", age:50, eyeColor:"blue"};
‘The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor.
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"
Notes - CSCO 2302 - Introduction to Web Technology 2022-23 (Ms, Londhe K.W.)
22typeof 0. // Returns "number"
typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
typeof (3+4) — // Returns "number"
Undefined
In JavaScript, a variable without a value, has the value undefined. The type is also undefined.
let car; // Value is undefined, type is undefined
Any variable can be emptied, by setting the value to undefined. The type will also be undefined.
car=undefined; // Value is undefined, type is undefined
Empty Values
An empty value has nothing to do with undefined.
‘An empty string has both a legal value and a type.
let car=""; // The value is "*, the typeof is "string"
Control Structures
JavaScript If-else
The JavaScript if-else statement is used to execute the code whether condition is true or false. There are
three forms of if statement in JavaScript.
1. If Statement
2. If else statement
3, if else if statement
JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if statement is given below.
if(expression){
//content to be evaluated
}
Let's see the simple example of if statement in javascript.
JavaScript If...else Statement
It evaluates the content whether condition is true of false. The syntax of JavaScript if-else statement is given
below.
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.) 23iflexpression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
Let's see the example of if-else statement in JavaScript to find out the even or odd number.
JavaScript If...else if statement
It evaluates the content only if expression is true from several expressions. The signature of JavaScript if else
if statement is given below.
iffexpression1){
//content to be evaluated if expression1 is true
}
else if(expression2}{
//content to be evaluated if expression? is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
Let's see the simple example of if else if statement in javascript.
JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple expressions. It is just like else if
statement that we have learned in previous page. But it is convenient than if..else..if because it can be used
with numbers, characters etc,
The signature of JavaScript switch statement is given below.
switch(expression){
case value:
code to be executed;
break;
case value2:
code to be executed;
break;
default:
code to be executed if above values are not matched;
}
Let’s see the simple example of switch statement in javascript.
Let’s understand the behaviour of switch statement
JavaScript.
Notes - CSCO 2302 - Introduction to Web Technology 2022-23 (Ms, Londhe K.W.) 25
JavaScript Loops
The JavaScript loops are used to iterate the piece of code usit
the code compact. It is mostly used in array.
There are four types of loops in JavaScript.
1. for loop
2. while loop
3, do-while loop
4, for-in loop
¥ for, while, do while or for-in loops. It makes
1) JavaScript For loop
‘The JavaScript for loop iterates the elements for the fixed number of times. It should be used if number of
iteration is known. The syntax of for loop is given below,
for (initialization; condition; increment)
{
code to be executed
}
Let's see the simple example of for loop in javascript.
site)
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.) 262) JavaScript while loop
The JavaScript while loop iterates the elements for the infinite number of times. It should be used if number
of iteration is not known. The syntax of while loop is given below.
while (condition)
{
code to be executed
}
Let’s see the simple example of while loop in javascript.
The JavaScript do while loop iterates the elements for the infinite number of times like while loop. But, code
is executed at least once whether condition is true or false. The syntax of do while loop is given below.
dof
code to be executed
while (condition);
Let's see the simple example of do while loop in javascript.
Different Kinds of Loops
JavaScript supports different kinds of loops:
+ for-loops through a block of code a number of times
‘+ for/in - loops through the properties of an object,
+ for/of -loops through the values of an iterable object
‘+ while - loops through a block of code while a specified condition is true
«© do/while - also loops through a block of code while a specified condition is true
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.) 7The For Loop
The for statement creates a loop with 3 optional expressions:
for (expression 1; expression 2; expression 3) {
// code block to be executed
}
Expression 1 is executed (one time) before the execution of the code block.
Expression 2 defines the condition for executing the code block.
Expression 3 is executed (every time) after the code block has been executed,
Example
for (let i= 0; i< 5; i++) {
text += "The number is" +i+ " ";
}
From the example above, you can read:
Expression 1 sets a variable before the loop starts (let i = 0).
Expression 2 defines the condition for the loop to run (i must be less than 5).
Expression 3 increases a value (i++) each time the code block in the loop has been executed.
The For In Loop
The JavaScript for in statement loops through the properties of an Object:
for (key in object) {
/{ code block to be executed
}
Example
const person = {fname:"John", Iname:"Doe", age:25};
let text
for (let x in person) {
text += person[x];
}
Example Explained
The for in loop iterates over a person object
+ Each iteration returns a key (x)
+ The key is used to access the value of the key
+The value of the key is person[x]
For In Over Arrays
The JavaScript for in statement can also loop over the properties of an Array:
for (variable in array) {
code
}
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.) 28const numbers = [45, 4, 9, 16, 25];
let txt =
for (let x in numbers) {
txt += numbers[x];
}
Array forEach()
The forEach() method calls a function (a callback function) once for each array element.
const numbers = [45, 4, 9, 16, 25];
let txt
numbers.forEach(myFunction);
function myFunction(value, index, array) {
txt 4 value;
}
The For Of Loop
The JavaScript for of statement loops through the values of an iterable object.
It lets you loop over iterable data structures such as Arrays, Strings, Maps, Nodelists, and more:
for (variable of iterable) {
// code block to be executed
}
variable - For every iteration the value of the next property is assigned to the variable. Variable can be
declared with const, let, or var.
iterable - An object that has iterable properties.
For/of is not supported in Internet Explorer.
Looping over an Array
const cars = ["BMW", "Volvo", "Min
let text =";
for (let x of cars) {
text += x;
}
Looping over a String
let language = "JavaScript";
let text =";
for (let x of language) {
text += x;
}
Notes - CSCO 2302 - Introduction to Web Technology 2022-23 (Ms, Londhe K.W.)
29JavaScript function
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).// Function to compute the product
of pl and p2
function myFunction(p1, p2) {
return p1 * p2;
}
JavaScript Function Syntax
A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
‘The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when itis invoked.
Inside the function, the arguments (the parameters) behave as local variaFunction Invocation
The code inside the function will execute when "something" invokes (calls) the function:
When an event occurs (when a user clicks a button)
When it is invoked (called) from JavaScript code
Automatically (self invoked)
Function Return
‘When JavaScript reaches a return statement, the function will stop executing,
If the function was invoked from a statement, JavaScript will "return" to execute the code after the
invoking statement.
Functions often compute a return value. The return value is "returned" back to the "calle
let x= myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b) {
return a* b; // Function returns the product of a and b
}
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.) 30Why Functions?
You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce different results.
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementByld("demo").innerHTML = toCelsius(77);
The () Operator Invokes the Function
Using the example above, toCelsius refers to the function object, and toCelsius() refers to the function
result,
Accessing a function without () will return the function object instead of the function result.
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementByld("demo").innerHTML = toCelsius;
JavaScript Objects
Real Life Objects, Properties, and Methods
In real life, a car is an object.
A car has properties like weight and color,
and methods like start and stop:
Properties Methods
car.name = carstart()
a Fiat
we carcdrive()
Loa car.model =
500 car-brake()
car.weight= —_car.stop()
850kg
car.color =
white
All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different times.
JavaScript Objects
You have already learned that JavaScript variables are containers for data values.
This code assigns a simple value (Fiat) to a variable named car:
let car = "Fiat"
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, S00, white) to a variable named car:
Notes - CSCO 2302 - Introduction to Web Technology 2022-23 (Ms, Londhe K.W.) 31const car = {type:"Fiat", model:"500", color:"white"};
The values are written as nameivalue pairs (name and value separated by a colon).
Object Properties
The name:values pairs in JavaScript objects are called properties:
Property Property Value
firstName John
lastName Doe
Age 50
eyeColor blue
Accessing Object Properties
You can access object properties in two ways:
‘objectName.propertyName
person.lastName;
or
objectName|"propertyName"]
personf"lastName"];
JavaScript objects are containers for named values called properties.
Object Methods
Objects can also have methods.
Methods are actions that can be performed on objects.
Methods are stored in properties as function d
Property Property Value
firstName John
lastName Doe
‘Age 50
eyeColor blue
fullName function() {return this. firstName + "” + this.lastName;}
‘Amethod is a function stored as a property.
const person = {
firstName: “John",
lastName : "Doe",
id 15566,
fullName : function() {
return this firstName +
}
i
+ this.lastName;
Notes - CSCO 2302 Introduction to Web Technology 2022-23 (Ms. Londhe K.W.)
32