0% found this document useful (0 votes)
2 views259 pages

Our JavaScript Complete Slides

Uploaded by

aylar.unknowns
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views259 pages

Our JavaScript Complete Slides

Uploaded by

aylar.unknowns
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

WELCOME

JAVA SCRIPT

Welcome to Pargar JavaScript Course!

[Link]
What is JavaScript?

• JavaScript or JS is a dynamic programming language that we use in HTML


document to add dynamic interactivity.
• JavaScript is the world's most popular programming language.
• JavaScript is the programming language of the Web.
• It can update and change both HTML and CSS.
• It can calculate, manipulate and validate data
• JavaScript is easy to learn.

W W W . P A R G A R . AF 2
JS is the scripting language for HTML

JavaScript is a scripting language, which means it is


used to add interactivity and functionality to web
pages. It enhances HTML by enabling dynamic
content, such as animations, form validations, and
interactive features, making web pages more engaging
and user-friendly.

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.

• When this langage was submitted for standardization to ECMA International


it was given a standard name ECMAScript.

• Even Microsoft back then created their own version called JScript for their
browser.

• Then the name was later changed to JavaScript.

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].

<script type="text/javascript" src="/path/to/the/file/[Link]"></script>

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”?

JavaScript is a case-sensitive language. This means


lower case letters and upper case letters are treated
differently. For example, name and Name are different
even though they are the same word.

W W W . P A R G A R . AF 37
What are “Instructions”?

Programs are list of instructions that are


executed by the computer. JavaScript
programs are instructions that are
executed by the web browser.

W W W . P A R G A R . AF 38
What is a “Statement”?

• JavaScript statements are the


instructions written by a
programmer.
• In JS, each statement should end
with a semi-colon.
W W W . P A R G A R . AF 39
Consider “Semicolon”
• Every statement in JavaScript ends with a semicolon ;

• In the following example we have an statement that will


print "Hello World" in the browser console.

W W W . P A R G A R . AF 40
What is “Token”?
❖The smallest individual unit in a program is called token.

❖List of JavaScript tokens.


⮚Reserved Keywords
⮚Identifiers
⮚Punctuators
⮚Literals

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:

1. Brackets: [] for arrays, {} for objects, and () for functions.


2. Periods: . to access properties and methods of objects.
3. Commas: , to separate items in arrays or arguments in functions.
4. Semicolons: ; to end statements (though often optional).
5. Colons: : in object literals to separate keys and values.

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

The value of the Boolean literal are


true and false. These are logical
values.

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.

• In the following example we have a string enclosed in double quote.

• In the following example we have a string enclosed in single quote.

W W W . P A R G A R . AF 51
4. Numeric literal
❖We use Numeric literal to represent numbers or numerical
value.

❖Following are the types of numerical values.


A. Decimal System
B. Hexadecimal System
C. Octal System

W W W . P A R G A R . AF 52
A. Decimal System

A decimal number system consists of 10 digits: 0, 1, 2,


3, 4, 5, 6, 7, 8 and 9. So, any number that we use in
our daily life is actually in decimal number system.

W W W . P A R G A R . AF 53
B. Hexadecimal System / hex

• Hexadecimal is a base-16 number system.


• Uses 16 symbols: 0-9 and A-F
• Each digit represents values from 0 to 15.

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

⮚STEP#2: Multiply each digit by 16 raised to the power of


its position.

⮚STEP#3: Add the results together.

W W W . P A R G A R . AF 56
Example: Let‘s Convert 2A3 to Decimal

• Specify the position: 2 A 3

Add: 512 + 160 + 3 = 675


Result: 2A3 in hex = 675 in decimal

W W W . P A R G A R . AF 57
Practice Numbers

•Convert 1B4 to decimal.


•Convert 7F2 to decimal.
•Convert 0A7 to decimal.
•Convert 3C0 to decimal.
•Convert FA1 to decimal.

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

❑STEP#2: Multiply each digit by 8 raised to the power


of its position.

❑STEP#3: Add the results together.


W W W . P A R G A R . AF 62
Convert 345 to Decimal

• Specify the position: 3 4 5

• Add: 192 + 32 + 5 = 229


• Result: 345 in octal = 229 in decimal
W W W . P A R G A R . AF 63
Practice Numbers

•Convert 123 to decimal.


•Convert 457 to decimal.
•Convert 075 to decimal.
•Convert 600 to decimal.
•Convert 527 to decimal.

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?

• Variables are named containers that hold


some value.
• Variables store data that can be used and
manipulated in a program.

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:

• Lowercase first word followed by uppercase words:

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:

var username = "Ehsanullah Naseri";

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.

• The typeof operator will give boolean.

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.

• The typeof operator will give object.

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.

• The typeof operator will give undefined.

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.

• 3e9 = 3 x 10^9 = 3 x 1000000000 = 3000000000


• 314e-2 = 314 x 10^-2 = 314 x 0.01 = 3.14
• The typeof operator will give number.

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.

• The typeof operator will give 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.

Syntax: var ObjName = {


property1 : value,
property2 : value,

};

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.

• The typeof operator will give 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.

•Following is the list of arithmetic operators.

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

Modulus (to get remainder) % 5%2


Answer: 1 (remainder)
10
W W W . P A R G A R . AF
0
Addition
• In the following example we are adding the value of two variables.

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

Addition and assignment += x += 10

Subtraction and assignment -= x -= 10

Multiplication and assignment *= x *= 10

Division and assignment /= x /= 10


Modulus (to get remainder) and assignment %= x %= 10

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.

Is not equal to or not of same !== x !== y


This will return true if value on both sides are not equal to each other or not of same type.
type
Is greater than > x>y
This will return true if value on left side is greater than the value on the right side.

Is less than < x<y


This will return true if value on left side is less than the value on the right side.

Is greater than or equal to >= x >= y


This will return true if value on left side is greater than or equal to the value on the right side.

Is less than or equal to <= x <= y


This will return true if value on left side is less than or equal to the value on the right side.

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

• We use the logical operator to compare two conditional


statement to see if they satisfy the condition to execute a
piece of code.

• This is commonly used in conditional statements and


loops.

13
W W W . P A R G A R . AF
1
There Are Three Main Logical
Operators

Operator Name Description Example

Returns true if both are true, otherwise it


&& AND true && true → true
will return false

|| OR Returns true if at least one is true true || false → true

!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

• Binary is a number system that uses only two digits: 0 and 1.


• It’s the language computers use to store and process data.
• Each digit in a binary number is called a bit, and together they
represent values and instructions for everything digital — from
documents to games to websites.

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

& AND Returns 1 if both bits are 1 5&3→1

| OR Returns 1 if either bit is 1 5|3→7

^ XOR Returns 1 if bits are different 5^3→6

~ NOT Flips all bits (inverts) ~5 → -6

<< Left Shift Moves bits to the left, fills with zeros 5 << 1 → 10

>> Right Shift Moves bits right, keeps sign 5 >> 1 → 2

>>> 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

Bitwise Operators are not very useful in practical work;


therefore, having a comprehension of them would be
enough for this course.

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

Name of JavaScript functions must be unique and can use


only the following characters.
Letters a-z A-Z
Digit 0-9
Dollar sign $
Underscore _

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.

• Following is an example of a function declaration.

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

• We use commas between a function parameters.

• Function parameters are like variables and follow the same


naming convention.

• The actual value that we pass to the function is called argument.


15
W W W . P A R G A R . AF
6
Return
• It sends a value back from the function to wherever the function was called.
• It also stops the function immediately — any code after return won’t run.

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?

• With functions you can reuse code

• You can write code that can be used many times.

• 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.

Syntax: var ObjName = {


property1 : value,
property2 : value,

};

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.

• Syntax propertyName : propertyValue

• The propertyValue can be of any type - null, undefined,


number, string, object, function and even an array.
16
W W W . P A R G A R . AF
3
an object student having some properties and
values

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.

• Another way to access object property is by using [ ] square


brackets and placing the object property name in quotes.

• In the following examples we are accessing the name property of


the student object in two ways:

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:

Use if to specify a block of code to be executed, if a specified condition is


true
Use else to specify a block of code to be executed, if the same condition is
false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed

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:

• 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.
• The break keyword is used to get out of the switch scope.
• If there is no match, the default code block is executed.
• The default code block is optional. If it didn’t exist in the code and there
were no match, our switch will have no result.

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.

• This will stop the execution inside 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

• The getDay() method returns the weekday as a number between 0 and 6.

• (Sunday=0, Monday=1, Tuesday=2 ..)

• 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

order to avoid repeating the same code block.

• In the following example case 1 and case 2 share the same code block.

Similarly, case 3 and case 4 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

JavaScript supports different kinds of loops:


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

for - loops through a block of code a number of times

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.

2. Even Numbers Between 1 and 20


Use a while loop to print only even numbers between 1 and 20.

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:

• Elements: An array is a list of values, known as elements.


• Ordered: Array elements are ordered based on their index.
• Zero indexed: The first element is at index 0, the second at index 1, and so
on. (in the above example, apple is index 0, mango is 1 and orange is 2 – it
can be seen in the console as well)
• Dynamic size: Arrays can grow or shrink as elements are added or removed.
• Heterogeneous: Arrays can store elements of different data types (numbers,
strings, objects and other arrays).

21
W W W . P A R G A R . AF
1
How to define an array?
Method #1:

Method #2: Using square brackets []

21
W W W . P A R G A R . AF
2
How to find number of elements in an array?

We use the length property to find the 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?

A string is a sequence of characters enclosed in single or double quotes.

Example: "Apple" and 'Orange' are 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?

• We use the length property to find the number of characters in a string.


• In the following example we are printing 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

• To create an instance of the Date object we use the new keyword.


• The following will give the complete date and time with region (current local
time):

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?

We can add event handlers to an element in the following ways:


Using Special Attributes in the HTML Element

Adding Event Handler Inside the Script Tag

In a separate JS File

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

You might also like