Our JavaScript Complete Slides
Our JavaScript Complete Slides
JAVA SCRIPT
[Link]
What is JavaScript?
W W W . P A R G A R . AF 2
JS is the scripting language for HTML
W W W . P A R G A R . AF 3
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
Prerequisite:
• You must have some basic knowledge of HTML and CSS.
W W W . P A R G A R . AF 4
Brief history
• The language was given the name Mocha then it was renamed
to LiveScript when NetScape and Sun Microsystem did a license agreement.
• Even Microsoft back then created their own version called JScript for their
browser.
W W W . P A R G A R . AF 5
JavaScript is not Java
Though JavaScript has some similarities to
programming languages like Java and others
like C and C++. And it was given this name to
attract developer at that time.
W W W . P A R G A R . AF 6
How to run JavaScript?
Code written in JavaScript runs on client side i.e., the web browser. We don't have to
compile JavaScript code.
Requirements:
• In order to learn and practice JavaScript we will need some software.
• Text Editor: This is where we write the code. Some of the commonly used text editors
are Notepad++, Sublime Text, Brackets, Atom, Visual Studio Code, TextMate etc.
• IDE: We can also use IDE (integrated development environment) like Eclipse and
NetBeans.
• Web browser: We will need a web browser like Chrome, Firefox, Safari, Edge etc.
W W W . P A R G A R . AF 7
How to Print “Hello World” in JS
W W W . P A R G A R . AF 8
JS SCRIPT TAG
[Link]
W W W . P A R G A R . AF 9
JS Script Tag
• We use the script tag to tell the browser the starting and ending point of a
script inside the HTML document.
• In the following example we have created a script tag and set the value of
the type attribute to text/javascript and written some code.
W W W . P A R G A R . AF 10
NOTE!
W W W . P A R G A R . AF 11
How to Include an External JS File into
HTML
• We can also use the script tag to include an external javascript file into the
HTML document.
• In the following example we have created a script tag and set the value of
the src attribute to the javascript file path /path/to/the/file/[Link].
W W W . P A R G A R . AF 12
noscript tag
• We use the noscript tag to provide alternative content if JavaScript is turned
off in a browser.
• In the following example we are using the noscript tag.
• We can turn off JavaScript in the settings of browsers (not recommended)
W W W . P A R G A R . AF 14
Hello World in console (1)
In the following example we
are going to use the
[Link]() method to print
the famous "Hello World!"
text in our browser console.
W W W . P A R G A R . AF 15
Hello World in console (2)
• Now open the [Link] file in the browser and open Console.
• Chrome: View -> Developer -> Developer Tools
• Firefox: Tools -> Web Developers -> Web Console
• Safari: Developer -> Show Error Console
• Or, simply right click on the page and select Inspect / Inspect Element and
then click on the Console tab.
• Once you are in the Console tab you will see the following output:
W W W . P A R G A R . AF 16
W W W . P A R G A R . AF 17
Hello World in console (3)
• Similarly, we can create a javascript file (say [Link]) and write the
following code inside.
[Link]("Hello World!");
• And then include the js file inside the [Link] file using the script
tag. And when the html file will be opened in the browser it will give us the
same result.
W W W . P A R G A R . AF 18
JS COMMENTS
[Link]
JS Comments
• Like most of the programming languages like C++, Java, PHP, C#
etc. JavaScript also has comments - Single line comments and
Multi line comments.
• 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 Comment
• 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:
W W W . P A R G A R . AF 21
Another Example
• This example uses a single line comment at the end of each line to explain
the code:
W W W . P A R G A R . AF 22
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:
W W W . P A R G A R . AF 23
Using Comments to Prevent Execution
(1)
• 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.
• This example uses // to prevent execution of one of the code lines:
W W W . P A R G A R . AF 24
Using Comments to Prevent Execution
(2)
• This example uses a comment block to prevent
execution of multiple lines:
W W W . P A R G A R . AF 25
W W W . P A R G A R . AF 26
JS OUTPUT/JAVASCRIPT
DISPLAY POSSIBILITIES
We will learn some of the possible ways we can display output in JavaScript.
[Link]
W W W . P A R G A R . AF 27
Output Methods
1. Writing into an HTML element, using innerHTML.
2. Writing into the HTML output using [Link]().
3. Writing into an alert box, using [Link]().
4. Writing into the browser console, using [Link]().
W W W . P A R G A R . AF 28
Method #1: innerHTML
• To access an HTML element, JavaScript can use the
[Link](id) method.
• The id attribute defines the HTML element. The innerHTML property
defines the HTML content:
W W W . P A R G A R . AF 29
Method #2: [Link]()
CASES:
• STRING: [Link](“String”); or [Link](‘String’);
• NUMBER: We can also include calculations: [Link](1+3);
• STRING + NUMBER: [Link](“This is our result: “ + 10)
W W W . P A R G A R . AF 30
W W W . P A R G A R . AF 31
Method #3: (window.)alert();
We use this method to display the output in an alert box
when the page is loaded.
CASES:
• STRING: alert(“your message”); or alert(‘your message’);
• NUMBER: We can also include calculations: alert (1+3); 🡺 Result: 3
• STRING + NUMBER: alert(“This is our result: “ + 10)
NOTE: 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.
W W W . P A R G A R . AF 32
Method #4: [Link]()
For debugging purposes, you can call the [Link]() method in the browser
to display data.
Debug: finding and fixing the problem in a code.
CASES:
• STRING: [Link](“your message”); or [Link](‘your message’);
• NUMBER: We can also include calculations: [Link](1+3); 🡺 Result: 3
• STRING + NUMBER: [Link](“This is our result: “ + 10)
W W W . P A R G A R . AF 34
JS BASIC CONCEPTS
JavaScript borrows most of its syntax from languages like C/C++, Java, Python
etc.
[Link]
What is “Case sensitive”?
W W W . P A R G A R . AF 37
What are “Instructions”?
W W W . P A R G A R . AF 38
What is a “Statement”?
W W W . P A R G A R . AF 40
What is “Token”?
❖The smallest individual unit in a program is called token.
W W W . P A R G A R . AF 41
What are “Reserved Keywords”?
• Reserved keywords are words that carry a special meaning and must not be
used to name variables and functions.
• Following are some of the commonly used JavaScript reserved keywords.
break case const continue
default delete do else
false final for function
if instanceof new null
return static switch this
true typeof var While
W W W . P A R G A R . AF 42
What are “Identifiers”?
• Identifiers are sequence of characters that are used to
name the variables, functions etc.
• Characters of an identifier can be a letter, digit, dollar sign
and underscore. The first character cannot be a digit.
⮚Letter a-z A-Z
⮚Digit 0-9
⮚Dollar sign $
⮚Underscore _
W W W . P A R G A R . AF 43
Following are valid identifiers:
W W W . P A R G A R . AF 44
Following are invalid identifiers:
W W W . P A R G A R . AF 45
What are “Punctuators”?
punctuators are special symbols used to structure and organize
code. They include characters like:
W W W . P A R G A R . AF 46
What are “Punctuators”?
W W W . P A R G A R . AF 47
What are “Literals”?
❖We use literals to represent value in JavaScript.
/ It simply means value.
❑List of literals.
⮚Null literal
⮚Boolean literal
⮚String literal
⮚Numeric literal
W W W . P A R G A R . AF 48
1. Null literal
The value of the Null literal is null. It represent
null or empty.
W W W . P A R G A R . AF 49
2. Boolean literal
W W W . P A R G A R . AF 50
3. String literal
• Strings are sequence of characters enclosed in double and single quotes in
JavaScript.
W W W . P A R G A R . AF 51
4. Numeric literal
❖We use Numeric literal to represent numbers or numerical
value.
W W W . P A R G A R . AF 52
A. Decimal System
W W W . P A R G A R . AF 53
B. Hexadecimal System / hex
W W W . P A R G A R . AF 54
More: Hexadecimal Values
⮚0 =0
⮚1 = 1
⮚9 = 9
⮚2 = 2 ⮚A = 10
⮚3 = 3 ⮚B = 11
⮚4 = 4 ⮚C = 12
⮚5 = 5 ⮚D = 13
⮚6 = 6 ⮚E = 14
⮚7 = 7
⮚F = 15
⮚8 = 8
W W W . P A R G A R . AF 55
More: Converting Hex to Decimal
⮚STEP#1: Identify the position of each digit (from right to
left, starting at 0).
W W W . P A R G A R . AF 56
Example: Let‘s Convert 2A3 to Decimal
W W W . P A R G A R . AF 57
Practice Numbers
W W W . P A R G A R . AF 58
Practice Answers
⮚1B4 = 436
⮚7F2 = 2034
⮚0A7 = 167
⮚3C0 = 960
⮚FA1 = 4001
W W W . P A R G A R . AF 59
C. Octal System
• Octal is a base-8 number system.
• Uses 8 symbols: 0-7.
• Each digit represents values from 0 to 7.
W W W . P A R G A R . AF 60
Octal Values
⮚0 = 0
⮚1 = 1
⮚2 = 2
⮚3 = 3
⮚4 = 4
⮚5 = 5
⮚6 = 6
⮚7 = 7
W W W . P A R G A R . AF 61
Converting Octal to Decimal
❑STEP#1: Identify the position of each digit (from
right to left, starting at 0).
W W W . P A R G A R . AF 64
Practice Answers
•123 = 83
•457 = 303
•075 = 61
•600 = 384
•527 = 343
W W W . P A R G A R . AF 65
JS Variables
Variables are named container that holds some value.
[Link]
66
What is a Variable?
W W W . P A R G A R . AF 67
Creating Variables in JavaScript
• Use the var keyword to declare a variable
in JavaScript.
W W W . P A R G A R . AF 68
Naming JavaScript Variables
• Variable names must be unique and can use:
• Letters a-z, A-Z
• Digits 0-9
• Dollar sign $
• Underscore _
• Variable names must not start with a digit or use reserved
keywords.
• Variable names are case-sensitive (name and Name are different).
W W W . P A R G A R . AF 69
Valid & Invalid Variable Names
Valid Invalid
var name; var 1address;
var age; var student-name;
var school_name;
var _temp;
W W W . P A R G A R . AF 70
Using Camel Case
• Camel case is a typographic convention where each word starts with a
capital letter with no punctuation or spaces.
• Valid camel case variable names:
W W W . P A R G A R . AF 71
Assigning Value to a Variable
• Use the assignment operator = to assign value to a variable.
• In the following example we have assigned the value 10 to the variable
score.
W W W . P A R G A R . AF 72
Merging the Creation and Value of a var in One
Line
We can combine the creation of variable and its
assignment in one line:
W W W . P A R G A R . AF 73
74
Declaring Multiple Variables
• We declare multiple variables by separating them
with commas.
W W W . P A R G A R . AF 75
Undefined Value
• If a value is not assigned to a variable then it gets the undefined value.
• Following code will print undefined in the browser console.
W W W . P A R G A R . AF 76
W W W . P A R G A R . AF 77
Re-declaring a variable
• When a variable is re-declared then it retains its previous value.
• In the following example we have declared a variable name and set it to
“Ehsanullah Naseri" and then re-declared it.
• Js code is conducted line by line, so if we assign a var two values, the last
one will be considered.
• It will print “Ehsanullah Naseri” in the console.
W W W . P A R G A R . AF 78
JS DATA TYPES
We will learn about JavaScript data types.
[Link]
W W W . P A R G A R . AF 79
Data Type
• Data types tells us about the type of the data that a
variable holds. And depending on the type of data
the operators that can work on that data is defined.
• For example, if a variable holds a data of type number
then we can perform arithmetic operations like
addition and subtractions using + and - operators.
W W W . P A R G A R . AF 80
W W W . P A R G A R . AF 81
JavaScript is a loosely typed language! /
JavaScript is dynamic typing!
• "JavaScript is a loosely typed language" means you don't have to specify the
type of data (like number, string, or boolean) when you create a variable.
You can change the type of data stored in a variable at any time without any
errors.
• Example: var x = “Ehsan”; / var x = 30; / var x = false;
• In the above example, var x can take any datatype.
• In more strictly typed languages, like Java, C#, C and C++, you have to
explicitly declare the type of a variable, and it can't change:
• Examples (Java): int number = 5; / char letter = 'A'; / boolean isJavaFun = true;
W W W . P A R G A R . AF 82
Data Types
Following are the different data types available.
1. Primitive
2. Object
3. Function
If the variable is only one letter/char, then we should use typeof(char) e.g. typeof (C)
W W W . P A R G A R . AF 83
1. Primitive data types
Primitive data types are the basic data types that hold single value.
Following are the primitive data type.
a. boolean
b. null
c. undefined
d. number
e. string
W W W . P A R G A R . AF 84
A. boolean data type
• If data type of a variable is boolean then it can take either true value or
false value.
• In the following example we have a boolean type variable.
W W W . P A R G A R . AF 85
B. null data type
• If a variable has null value then it is of null data type. null means the
variable is empty or not set.
• In the following example we have a null type variable.
W W W . P A R G A R . AF 86
C. undefined data type
• If a variable has undefined value then it is of undefined data type. If a
variable is not initialized with a value then it is set to undefined.
• In the following example variable name will set to undefined by default.
W W W . P A R G A R . AF 87
D. number data type
• If a variable holds number then it is of number data type.
• Number can be both positive and negative. It can have fractional part as well and can be
expressed in exponential form.
• In the following example we have number variables.
W W W . P A R G A R . AF 88
E. string data type
• If a variable holds a sequence of characters within single or double quote, it
is called a String.
• In the following example variable str is of type string.
W W W . P A R G A R . AF 89
Escape Sequence (1)
• These are special sequence of characters starting with backward slash \.
• Following are some of the commonly used escape sequence.
Escape Sequence Meaning
\' Single quote
\" Double quote
\\ Backslash character
\n Line feed character
\r Carriage return character
\t Horizontal tab
W W W . P A R G A R . AF 90
Escape Sequence (2)
• We use the escape sequence inside string.
• For example if we want to include double quotation inside a string
which is enclosed in double quote we use the escape sequence \".
• Output:
This "word" is in double quote.
W W W . P A R G A R . AF 91
2. Object (1)
• An object is a multi value data type i.e, unlike Primitive Datatypes, it can
hold multiple values as a key-value pairs also known as properties of the
object.
W W W . P A R G A R . AF 92
W W W . P A R G A R . AF 93
2. Object (2)
• In the following example we have created a student object.
W W W . P A R G A R . AF 94
3. Function (1)
• A function is a block of code that is generally given a name. When
the function is called the code inside it is executed.
• We use functions to avoid rewriting the same piece of code.
• In the following example we have defined a hello function.
W W W . P A R G A R . AF 95
How to Call a Function
• In order to call a function, we simply need to use its name concluding with a
semi-colon:
W W W . P A R G A R . AF 96
3. Function (2)
•The typeof operator will give function.
W W W . P A R G A R . AF 97
JS ARITHMETIC
OPERATORS
We will learn about JavaScript arithmetic operators.
[Link]
W W W . P A R G A R . AF 98
JS Arithmetic Operators
•In JavaScript like other programming languages
we use different arithmetic operators to do
maths.
W W W . P A R G A R . AF 99
Operator Symbol Example
Addition + 1+2
Answer: 3
Subtraction - 1-2
Answer: -1
Multiplication * 4*5
Answer: 20
Division / 10 / 2
Answer: 5
W W W . P A R G A R . AF 101
Subtraction
• In the following example we are subtracting the value of two variables.
W W W . P A R G A R . AF 102
Division
• In the following example we are dividing the value of two variables.
W W W . P A R G A R . AF 103
Multiplication
• In the following example we are multiplying the value of two variables.
W W W . P A R G A R . AF 104
Modulus
• In the following example we are finding the remainder by using modulus
operator:
W W W . P A R G A R . AF 105
Incrementing & Decrementing by 1
• In JavaScript and in other programming languages
incrementing and decrementing value of a variable
by 1 is very common.
• There are two ways to do so:
• Using the +1 and -1
• Using the Increment Operator (++) and Decrement
Operator (- -)
W W W . P A R G A R . AF 106
Method #1
Increment by 1 Decrement by 1
In the following example we are In the following example we are
incrementing the value of decrementing the value of
variable x by 1. variable x by 1.
W W W . P A R G A R . AF 107
Method #2
Increment operator ++ Decrement operator --
In the following example we are In the following example we are
incrementing the value of decrementing the value of
variable x by 1. variable x by 1.
W W W . P A R G A R . AF 108
JS ASSIGNMENT
OPERATOR
We will learn about JavaScript assignment operators.
[Link]
10
W W W . P A R G A R . AF
9
JS Assignment Operator
• We use the assignment operator to assign value to a variable.
• In JavaScript (and in other programming languages) the equal to sign = is
the assignment operator and it assigns the value on the right side to the
variable on the left side.
• In the following example we are assigning the value 10 to the variable x
using the assignment operator.
W W W . P A R G A R . AF 110
Shorthand Notation (1)
• We can combine the assignment operator and arithmetic operator together
to get a shorthand notation if we are operating on a given variable.
• In the following example we are adding 10 to variable x and then assigning
the result to the variable x.
W W W . P A R G A R . AF 111
Shorthand Notation (2)
We can get the same result by combining the
operators together.
W W W . P A R G A R . AF 112
Addition and assignment
(In the following example we are assigning the result of addition to a
variable.)
Long Shorthand
W W W . P A R G A R . AF 113
Subtraction and assignment
(In the following example we are assigning the result of subtraction to a
variable.)
Long Shorthand
W W W . P A R G A R . AF 114
Division and assignment
(In the following example we are assigning the result of division to a
variable.)
Long Shorthand
W W W . P A R G A R . AF 115
Multiplication and assignment
(In the following example we are assigning the result of multiplication to a
variable.)
Long Shorthand
W W W . P A R G A R . AF 116
Modulus and assignment
(In the following example we are assigning the result of modulus to a
variable.)
Long Shorthand
W W W . P A R G A R . AF 117
List of Shorthand Assignment Operators Used
with Arithmetic Operators
Operator Symbol Example
W W W . P A R G A R . AF 118
JS COMPARISON
OPERATORS
We will learn about JavaScript comparison operators.
[Link]
11
W W W . P A R G A R . AF
9
JS Comparison Operators
• We use the comparison operator when we want to execute
a set of code when the condition is satisfied.
• The result of a comparison operator is a Boolean value.
• This is commonly used in conditional statements and loops
that will be studied in the upcoming lessons.
12
W W W . P A R G A R . AF
0
Following is a list of conditional
operators:
Operator Symbol Example
Is equal to == x == y
This will return true if value on both sides are equal to each other.
Is not equal to != x != y
This will return true if value on both sides are not equal to each other.
Is equal to and of same type === x == y
This will return true if value on both sides are equal to each other and of the same type.
12
W W W . P A R G A R . AF
1
Is equal to (==)
In the following example we are checking whether x is
equal to y.
12
W W W . P A R G A R . AF
2
Is not equal to (!=)
In the following example we are checking whether x is
not equal to y.
12
W W W . P A R G A R . AF
3
Is equal to and of same type (===)
In the following example we are checking whether x is equal to and
of same type as y.
12
W W W . P A R G A R . AF
4
Is not equal to or not of same type (!==)
In the following example we are checking whether x is not
equal to or not of same type as y.
12
W W W . P A R G A R . AF
5
Is greater than
In the following example we are checking whether x is
greater than y.
12
W W W . P A R G A R . AF
6
Is less than
In the following example we are checking
whether x is less than y.
12
W W W . P A R G A R . AF
7
Is greater than or equal to
In the following example we are checking whether x is
greater than or equal to y.
12
W W W . P A R G A R . AF
8
Is less than or equal to
In the following example we are checking whether x is
less than or equal to y.
12
W W W . P A R G A R . AF
9
JS LOGICAL
OPERATORS
Logical operators are used to combine or invert Boolean values. They return true or false
based on logic.
[Link]
JS Logical Operators
13
W W W . P A R G A R . AF
1
There Are Three Main Logical
Operators
!true → false
! NOT Inverts the Boolean value
!false true
13
W W W . P A R G A R . AF
2
1. AND (&&)
It gives us true if both x and y (username and password) are true, otherwise, it returns false.
13
W W W . P A R G A R . AF
3
Example
13
W W W . P A R G A R . AF
4
2. OR (||)
It returns true, if either x is true or y is true.
13
W W W . P A R G A R . AF
5
Example
13
W W W . P A R G A R . AF
6
3. NOT (!)
It inverts the value. If x = true, then !x = false. If x = false, then !x = true.
13
W W W . P A R G A R . AF
7
Example
13
W W W . P A R G A R . AF
8
BINARY LANGUAGE
Binary is a number system that uses only two digits: 0 and 1. It’s the language computers use
to store and process data.
[Link]
Binary Language
14
W W W . P A R G A R . AF
0
How to Convert Decimal Number to Binary
Number
Method #1: Method #2: JavaScript Method
Mathematical/Manual
STEP#1: Divide the decimal by 2. We can convert a decimal number to binary
STEP#2: Record the remainder (0 or 1). in JavaScript using .toString(2):
Continue the steps until the result becomes 0.
Example: Convert 13 to binary:
Division Result Remainder
13 ÷ 2 6 1
6÷2 3 0
3÷2 1 1
1÷2 0 1
The reverse of the remainder will be the result.
Therefore, 13₁₀ = 1101₂
14
W W W . P A R G A R . AF
1
JS BITWISE
OPERATORS
We use the bitwise operator to work with bits (0s and 1s).
[Link]
What Are Bitwise Operators?
• They work with binary digits (bits): 0 and 1
• Instead of checking if something is true or false, bitwise
operators do math on the binary form of numbers.
Example:
5 in binary = 0101
3 in binary = 0011
14
W W W . P A R G A R . AF
3
Bitwise Operators Overview
Operator Name Description Example
<< Left Shift Moves bits to the left, fills with zeros 5 << 1 → 10
>>> Zero-fill Right Shift Moves bits right, fills left with 0s 5 >>> 1 → 2
14
W W W . P A R G A R . AF
4
& (Bitwise AND)
Compares each bit of two numbers. Returns 1 only if both bits are 1
Example: What is the result of 5 & 3?
14
W W W . P A R G A R . AF
5
| (Bitwise OR)
Compares each bit of two numbers. Returns 1 if at least one bit is 1.
Example:
14
W W W . P A R G A R . AF
6
(Bitwise XOR)
Returns 1 if the bits are different, 0 if they’re the same.
Example:
14
W W W . P A R G A R . AF
7
NOTE
14
W W W . P A R G A R . AF
8
JS FUNCTIONS
A function is a reusable block of code that performs a specific task.
[Link]
What Is a Function?
• A function is a block of code that is executed when the function is called.
• We use functions in order to reuse a piece of code.
Syntax:
function function_name() {
Code to run…
}
15
W W W . P A R G A R . AF
0
Naming Functions
15
W W W . P A R G A R . AF
1
Invoking/Calling a Function
A function will be executed when it is called. In order to call/invoke a
function, we call its name.
15
W W W . P A R G A R . AF
2
Function Declaration
• Function declaration is the creation of a function with zero or more
parameters.
15
W W W . P A R G A R . AF
3
Function Expression (Stored in a
Variable)
• A function expression is when you create a function and assign it to a
variable — just like storing a value.
• We can call a function expression using the name of the variable that is
holding it. In the following case the function expression is assigned to hello
variable so, to invoke the function we use hello().
15
W W W . P A R G A R . AF
4
Function Parameters
• Function parameters are placeholder for values that we pass to a
function. These are names inside the parenthesis ( )
15
W W W . P A R G A R . AF
8
Without return, JS will give undefined
• This defines a function called sayHi. • Then you call the function.
• Inside the function, it prints "Hi!" to the • It runs [Link]("Hi!"), so you see Hi! in
screen using [Link]. the console.
• But notice: there’s no return statement. • But since there’s no return, JavaScript
automatically gives back undefined.
15
W W W . P A R G A R . AF
9
Why Functions?
• You can use the same code with different arguments, to produce
different results.
16
W W W . P A R G A R . AF
0
JS OBJECTS
JavaScript object is a special type of variable that can hold multiple named values.
[Link]
JS Objects
• An object is a multi value data type i.e, unlike Primitive Datatypes, it can
hold multiple values as a key-value pairs also known as properties of the
object.
16
W W W . P A R G A R . AF
2
Object Property and Value
• Inside the opening-closing braces we have name-value pair.
These are called the object property and property value.
So, in the above example student is an object. name and studentid are the
properties of the student object. Ehsan Naseri and 123 are the values of the
properties.
16
W W W . P A R G A R . AF
4
The propertyValue can be of any type - null, undefined, number, string,
object, function and even an array.
Object Method
• When property of an object is assigned a function then it is a method of the
object.
• In the following example we have added object method displayStream to
the student object.
16
W W W . P A R G A R . AF
6
Invoking (calling) Object Method
• To invoke or call an object method we use the following structure:
[Link]();
• In the following example we are calling the displayStream method of the
student object.
16
W W W . P A R G A R . AF
7
Accessing Object Property
• In order to access a property of an object we use the object name
followed by the . operator and then the name of the property.
16
W W W . P A R G A R . AF
8
Adding new property to the object
There are two ways we can add a new property to an object:
1. [Link] = ItsValue;
2. ObjectName[“NewPropertyName”] = ItsValue;
17
W W W . P A R G A R . AF
0
CONDITIONAL
STATEMENTS
Conditional statements are used to perform different actions based on different conditions.
[Link]
Conditional Statements
In JavaScript we have the following conditional statements:
17
W W W . P A R G A R . AF
2
1. if statement
We use the if keyword to create an if statement.
17
W W W . P A R G A R . AF
3
2. The else Statement
Use the else statement to specify a block of code to be executed if the
condition is false.
17
W W W . P A R G A R . AF
4
3. The else if Statement
Use the else if statement to specify a new condition if the first condition is
false. / It is used to create multiple conditions.
17
W W W . P A R G A R . AF
5
Nesting if/else
• We can have if/else statements inside another if/else statement.
• Following is an example of a nested if/else statement.
17
W W W . P A R G A R . AF
7
JS CONDITIONAL
STATEMENTS - SWITCH
The switch statement is used to perform different actions based on different conditions.
[Link]
The JavaScript Switch Statement
Use the switch statement to select one of many code blocks to be executed.
17
W W W . P A R G A R . AF
9
This is how it works:
18
W W W . P A R G A R . AF
0
The break Keyword
• When JavaScript reaches a break keyword, it breaks out of the switch block.
• It is not necessary to break the last case in a switch block. The block breaks
(ends) there anyway.
• If you omit the break statement, execution will continue to the next case
regardless of whether its condition matches.
18
W W W . P A R G A R . AF
2
getDay() method
• This example below uses the weekday number to calculate the weekday
name using switch:
18
W W W . P A R G A R . AF
3
The default Keyword (1)
• The default keyword specifies the code to run if there is no case match.
• The getDay() method returns the weekday as a number between 0 and 6.
• If today is neither Saturday (6) nor Sunday (0), write a default message:
18
W W W . P A R G A R . AF
5
The default Keyword (2)
• The default case does not have to be the last case in a switch block.
• If default is not the last case in the switch block, remember to end the
default case with a break.
18
W W W . P A R G A R . AF
6
Multiple case sharing same code
• If multiple case value have the same code then we can join them together in
• In the following example case 1 and case 2 share the same code block.
18
W W W . P A R G A R . AF
7
JS LOOP - WHILE
Loops can execute a block of code a number of times.
[Link]
What is a loop?
• A loop is a piece of code that allows us to repeat a code multiple time based
on some condition.
• We use loop to avoid retyping a piece of code when we want to repeat it
multiple times.
• Example: We can use loop and print "Hello World" 10 times using one
[Link]() or we can write the [Link]() 10 times and get the job
done.
• Though, the first option looks better than the second.
19
W W W . P A R G A R . AF
0
JavaScript Loops
Loops are handy, if you want to run the same code over and over again.
Instead of writing:
We can write:
19
W W W . P A R G A R . AF
1
Different Kinds of Loops
do/while - also loops through a block of code while a specified condition is true
19
W W W . P A R G A R . AF
2
while loop
• The while loop loops through a block of code as long as a specified
condition is true.
• We use the while keyword to create a while loop.
19
W W W . P A R G A R . AF
3
Example
In the following example, the code in the loop will run, over and over again,
as long as a variable (i) is less than or equal to 10:
19
W W W . P A R G A R . AF
4
The Do While Loop
• The do while loop is a variant of the while loop. This loop will execute the code block
once, before checking if the condition is true, then it will repeat the loop as long as the
condition is true.
• What is the difference between while loop and do while loop?
• In a while loop, first the condition is checked and then the code is executed, but in a do
while loop, first the code is executed and then the condition is checked.
19
W W W . P A R G A R . AF
5
Example
The example below uses a do while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed
before the condition is tested:
19
W W W . P A R G A R . AF
6
While Loop Practice
1. Print Numbers 1 to 10
Use a while loop to print numbers from 1 to 10 in the console.
3. Countdown from 10 to 1
Use a do-while loop to print a countdown from 10 to 1.
19
W W W . P A R G A R . AF
8
JS LOOP - FOR
Loops can execute a block of code a number of times.
[Link]
The For Loop
The for statement creates a loop with 3 optional expressions:
OR
20
W W W . P A R G A R . AF
0
Explanation
• 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.
20
W W W . P A R G A R . AF
1
Example
20
W W W . P A R G A R . AF
2
What is the result of the following code?
20
W W W . P A R G A R . AF
3
break out of for loop
• We use the break keyword when we want to break out of the loop.
• In the following example we will break out of the for loop when the value of i = 4.
• Therefore, when i equals 4, it breaks out of the for loop and the get “Hello World”
three times printed.
20
W W W . P A R G A R . AF
4
What is the output of the following code:
20
W W W . P A R G A R . AF
5
continue the for loop
• We use the continue keyword when we want to continue to the update part
of the loop.
• In the following example, when i is equal to 4, the “if” part is executed (not
the else part), therefore, when i = 4, there is no output.
20
W W W . P A R G A R . AF
6
For Loop Practice
1. Print "Hello World" 10 Times
Use a for loop to print "Hello World" 10 times.
2. Print Multiples of 5 up to 50
Use a for loop to print all multiples of 5 from 5 to 50.
3. Skip Multiples of 3
Use a for loop to print numbers from 1 to 20, but skip multiples of 3 using
continue.
4. Break at 7
Use a for loop to print numbers from 1 to 10, but stop the loop when the
number reaches 7 using break.
20
W W W . P A R G A R . AF
7
Challenge
Write a program using a for loop that prints the following pattern in the
console:
*
**
***
****
*****
20
W W W . P A R G A R . AF
8
JS ARRAY
An array is a variable that holds multiple values under same name.
[Link]
Key characteristics of JavaScript arrays are:
21
W W W . P A R G A R . AF
1
How to define an array?
Method #1:
21
W W W . P A R G A R . AF
2
How to find number of elements in an array?
21
W W W . P A R G A R . AF
3
How to access value of an array?
• Values stored in an array are called elements of the array. We use the array
index to access the elements. Array indexing starts from 0.
• So, if an array has 3 elements then the first element is at index 0, second
element is at index 1 and the third element is at index 2.
• To access specific value of an index, we use ArrayName[Index]
21
W W W . P A R G A R . AF
4
Printing an array elements using For Loop
In the following example, we print the elements of an array using for loop:
21
W W W . P A R G A R . AF
5
Changing an Array Element
To change the value of an element, we use the following syntax:
ArrayName[Index] = “NewValue”;
21
W W W . P A R G A R . AF
6
Adding Elements to an Empty Array
We use this syntax: ArrayName[Index] = “NewValue”;
If we don’t assign any value to an index, it will be set to undefined.
21
W W W . P A R G A R . AF
7
ARRAY METHODS
Array methods in JavaScript are built-in functions that allow you to manipulate, access, and iterate over array elements
efficiently. They help with tasks like adding, removing, sorting, filtering, and transforming data stored in arrays
[Link]
1. concat( )
• We use the concat( ) method to concatenate two arrays into a new one.
• In the following example we are concatenating two arrays.
• In the above code we are concatenating arr2 after arr1 and assigning the
resultant array to fruits.
21
W W W . P A R G A R . AF
9
2. pop( )
We use the pop( ) method to remove the last element from the array. We can
save the popped element in a variable.
22
W W W . P A R G A R . AF
0
3. push( )
It is the vice versa form of pop() method. We use the push( ) method to add
an element to the end of an array. We can save the popped element in a
variable.
22
W W W . P A R G A R . AF
1
4. indexOf( )
indexOf( ) method is used to return the first index at which the given element
is found. It gives -1 if the element is not found/available.
22
W W W . P A R G A R . AF
2
The following code shows if an array element is
available or not:
22
W W W . P A R G A R . AF
3
5. join( )
• We use the join( ) method to combine the elements of the array into a
string separated by a character that we pass as parameter to the method.
• If no separator character is passed then , comma is used as default
separator.
22
W W W . P A R G A R . AF
4
6. reverse( )
We use the reverse( ) method to reverse the order of the elements in an
array.
22
W W W . P A R G A R . AF
5
7. shift( )
We use the shift( ) method to remove the first elements of an array. The
removed element is returned by this method which can be saved in a
variable.
22
W W W . P A R G A R . AF
6
8. unshift( )
We use the unshift( ) method to add elements at the beginning of an array.
The method returns length of the new array after adding the elements.
22
W W W . P A R G A R . AF
7
9. sort( )
We use the sort( ) method to arrange the elements of the array in
alphabetical order.
22
W W W . P A R G A R . AF
8
JS STRING
A string is a sequence of characters enclosed in single or double quotes.
[Link]
What is a string?
23
W W W . P A R G A R . AF
0
How to create string? There are 2 ways:
Using String object Using String literal
• In this case we instantiate the String • In this case we assign a string value
object to create a string. to a variable.
• In the following example we are • In the following example we are
creating a string "Hello World". creating a string using string literal.
23
W W W . P A R G A R . AF
1
Difference between String object and String literal
• A string created using string literal (a regular text) hold the value of the
string itself.
• A string created by instantiating the String object is holding the value in an
object.
• So, we can easily compare string literal. But we can't compare value of
String object using == and === comparison operator.
Remember!
== means equal to
=== means equal to and of same type
23
W W W . P A R G A R . AF
2
Example
String Literal String Object
23
W W W . P A R G A R . AF
3
How to find the number of characters in a string?
23
W W W . P A R G A R . AF
4
How can we print each character
of a string separately using the
for loop?
Challenge
[Link]
STRING METHODS
String methods in JavaScript are built-in functions that allow you to manipulate and interact
with string values.
[Link]
1. charAt( )
We use the charAt() method to get character at a given position/index in a
string.
23
W W W . P A R G A R . AF
8
2. concat( )
We use the concat() method to concatenate strings together to get a new
string.
23
W W W . P A R G A R . AF
9
3. toUpperCase( ) and toLowercase
We use the toUpperCase( ) method to get uppercase value of a string and we
use the toLowercase() method to get the lowercase value of a string.
24
W W W . P A R G A R . AF
0
JS DATE OBJECT
We use the Date object to set and get certain time value.
[Link]
Instance of the Date object
24
W W W . P A R G A R . AF
2
getDate( )
We use the getDate() method to get the day of the month (1-31) for the
specified date based on local time.
24
W W W . P A R G A R . AF
3
getDay( )
• We use the getDay() method to get the day of the week (0-6) for the
specified date based on local time.
• 0 is for Sunday, 1 is for Monday and so on.
24
W W W . P A R G A R . AF
4
getFullYear( )
We use the getFullYear() method to get the full year (4 digit) for the specified
date based on local time.
24
W W W . P A R G A R . AF
6
getHours( )
We use the getHours() method to get the hour (0-23) for the specified date
based on local time.
24
W W W . P A R G A R . AF
7
getMilliseconds( )
We use the getMilliseconds() method to get the milliseconds (0-999) for the
specified date based on local time.
24
W W W . P A R G A R . AF
8
getMinutes( )
We use the getMinutes() method to get the minutes (0-59) for the speicified
date based on local time.
24
W W W . P A R G A R . AF
9
getMonth( )
We use the getMonth() method to get the month (0-11) for the specified date
based on local time.
25
W W W . P A R G A R . AF
0
getSeconds( )
We use the getSeconds() method to get the seconds (0-59) for the specified
date based on local time.
25
W W W . P A R G A R . AF
1
JS EVENT HANDLERS
Events are actions that happen in the browser, like clicks, key presses, or page loads.
Handlers are responses to the events.
[Link]
What Are JavaScript Events?
• Events are actions that happen in the browser—like clicks, key presses, or
page loads.
• JavaScript can “listen” for these events and respond with code.
• Common events:
onclick: when a user clicks
onmouseover: when mouse hovers
onkeydown: when a key is pressed
onscroll: when user scrolls
ondblclick: when a user double clicks
25
W W W . P A R G A R . AF
3
What Are Event Handlers in JavaScript
• Event handlers are functions that run in response to specific actions (called
events) that happen in the browser—like when a user clicks a button,
presses a key, moves the mouse, or submits a form.
• Think of them as listeners that wait for something to happen, and then
react.
25
W W W . P A R G A R . AF
4
Example of Event and Event Handler
Lets say we have a button in the page. When a user clicks the button we get
the "click" event. This click event can be handled by "onclick" event listener in
JavaScript.
25
W W W . P A R G A R . AF
5
How to add event handlers?
25
W W W . P A R G A R . AF
6
1. Using Special Attributes in the HTML
• Lets say we have a button and we want to alert "Hello World" message
when it is clicked.
• One way of solving this is by adding the onclick event handler to the button.
25
W W W . P A R G A R . AF
7
2. Adding Event Handler Inside the Script Tag
• In this way, we create a function that generates an alert window.
• And call that function in the onclick attribute.
25
W W W . P A R G A R . AF
8
3. Adding Event Handler in a Separate JS File
• We make our button in the html file with an ID.
• Then, we call it in the JS file as the value for a variable using
[Link]("")
• Then, we use the onclick handler with a function.
25
W W W . P A R G A R . AF
9