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

JavaScript Notes

Uploaded by

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

JavaScript Notes

Uploaded by

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

JavaScript Notes

Version 1 - 15/04/2022
Prepared by Mudassar Islam for Students in the Web Development Course
_____________________________________________________________________

—------------------------------------------------------------------------
Introduction
—------------------------------------------------------------------------

JavaScript is the language of the web browser. It is used alongside HTML and
CSS to make websites more useful. JavaScript is used to add special
functionality to your websites. A few applications may include:

● Dropdown Menus
● Accordions
● Sliders
● Image Galleries
● Form Validation
● Show / Hide Elements
● Animations

JavaScript can also be used outside of the browser to make Desktop


Applications or Mobile Applications. It can also be used to make games and
other types of applications.
—------------------------------------------------------------------------
Fundamentals of JavaScript
—------------------------------------------------------------------------
JavaScript is a complete programming language with all the features and
fundamentals that are found in other languages. If you learn JavaScript, it’s
very easy to transfer that knowledge onto other languages.

The fundamentals of JavaScript are:


● Syntax
● Variables and Constants
● Data Types
● Operators
● Functions
● If Statements
● Loops

—------------------------------------------------------------------------
Syntax of JavaScript
—------------------------------------------------------------------------
JavaScript follows the C family syntax. Below is a basic example of this syntax.
The syntax of JavaScript has some important properties:

● A statement is a line of code. Each statement must end with a “ ; ”.


● Code is written in the form of Code Blocks. These blocks are
represented by a starting and ending curly brace. These include “ { “
and “ } “.
○ Any code written between the curly braces will now be part of
that Code Block. These blocks may be used in functions, if else
statements, or for loops.
■ Blocks also control Variable Scope. Variables declared inside
Code Blocks will not be accessible outside that code block.
However, they can still be accessed in the children of that
code block.

● Functions are called by adding () after the function name.


○ Parameters of functions are written inside the brackets.

● Code is executed sequentially line by line.


—------------------------------------------------------------------------
Variables and Constants
—------------------------------------------------------------------------

Variables in programming are used to store a value so that we can use it for
any purpose later on.

For example, we may take user input for a number, and show them the
Multiplication Table of that number. To do this we must store the number
entered by the user in our code. We can use Variables to do this.

Variables in JavaScript are declared using the “let” keyword. Variables have
some properties that you need to remember:

● Variable Naming Rules:


○ Variable names cannot include spaces or special characters. You
should use Underscores instead of spaces.
○ Variable names cannot start with a number.
○ Refer to W3Schools for the complete ruleset.

● Variables must be declared with the “let” word before usage.


● You can assign a value to a variable using the “=” symbol.
● Variables can be used to store any data-type. For example numbers,
strings, arrays, objects or booleans.
● The value of a variable can be changed later in the code by using “=”.
● Variables are Scoped.
○ Variable scope means that the variable can only be used in the
code block where it is declared or children of that code block.
■ A variable declared inside a code block CANNOT be used in
another code block OUTSIDE of it. However It CAN be used
in code blocks INSIDE of it.

● Some variables such as Function Parameters don’t need to be declared


with the “let” keyword. They are automatically declared by JavaScript.
Constants are the same as variables but they are declared with the “const”
keyword. A value of a constant cannot be changed like a variable.

Constants are used to store data that will not change. For example the value
of Pi, The number of items in a dozen. This data can never change So it can be
stored as a constant.

However, for data that will change, You must use Variables. For example,
The time of day. The time of day changes every passing second, So it cannot
be stored in a constant.

—------------------------------------------------------------------------
Data Types in JavaScript
—------------------------------------------------------------------------
JavaScript variables are used to store any kind of data. This data stored inside
variables is represented by Data-Types. JavaScript has the following
data-types:
● Numbers

○ Mathematical numbers (0-9, ie 4819, 3841, 491, 123, etc)


○ Can be Negative or Positive (ie 85 is positive, -48 is negative)
○ Can also have a decimal point if you need (38.4, 3.14, 2.5)

● Strings

○ A string means collection of characters. This can be a single word,


sentence or anything else that is text.
○ Strings are always represented with QUOTES around them.
■ These can be single quotes or double quotes ( ‘ ‘ or “ “ )
○ Strings are used to store names, descriptions, or anything else
that can be represented in the form of text.
○ 2 or more strings can be combined by using the “+” operator.

● Booleans

○ Boolean just means ON or OFF.


○ In JavaScript, booleans are represented by “true” or “false”.
○ This data-type is used to store values that can only be true or
false.

● Arrays

○ An array is a data-type that can store multiple values inside of it.


For example, an array of student names, or array of prime
numbers.
○ Arrays are represented by Square Brackets. These are “[“ and “]”.
■ The concept of an array is like Matrix or Set in Mathematics.
○ Each Element in an array has an Index.
■ The index is the address of an element.
■ Array indexes start at 0.
○ An array can have another array inside of it. This is called a Multi
Dimensional Array.
○ An array can also have objects inside of it.
○ Each Array element behaves like an individual variable and can be
used in functions, It’s value can be changed and so on.
○ Arrays have functions like push() and pop() to add and remove
elements from an array.
○ Arrays are usually used with loops.
■ Loops can iterate over every element of an array and
perform any action that you want on it.
■ You can use the for loop, or the built in “forEach” function of
the array to loop over it.
● Objects

○ Objects are the building blocks of JavaScript. JavaScript is a


language of Objects.
■ JavaScript has a lot of built in objects like “document”,
“window” etc.
■ These objects have values and functions inside of them.
■ Values inside an object are accessed using a Dot ( . ).
○ Objects are represented by starting and ending curly braces which
are “{“ and “}”.
○ Objects are also used to store multiple values in a single variable.
○ Each element in the object behaves like an individual variable.
○ Objects store values in the form of key: value pairs.
■ Every element in an object has a “key” and a “value”.
■ A key: value pair is just a data structure where you first
describe the name of the value, then the value itself.
■ For example, When storing the name of a person, You will
set the key to “name” and the value to “Ali”.
■ Following is an example of key value pairs:


■ Key value pairs are also called Associative Array or Hash Map
in other programming languages.

○ Objects can also have functions inside of them.


○ Objects can also have other objects inside of them.
○ Objects can also have arrays inside of them.
○ Difference between Arrays and Objects.

Objects Arrays
Represented by curly braces Represented by square
“{“ and “}” brackets “[“ and “]”
Store data with key: value Store data with Indexes that
pairs. start from 0.
Values inside objects are Values inside arrays are
accessed with the Dot ( . ) accessed with square brackets
symbol with the key. “ [ ] “ with the index.

i.e. student.name will access i.e. students[2] will access the


the “name” value of the object. item with the index of 2.
If an array has objects inside of it. You can loop over the array and use the
object as you would normally.

—------------------------------------------------------------------------
Operators in JavaScript
—------------------------------------------------------------------------

JavaScript has 2 types of Operators. These are Arithmetic Operators for


Adding, Subtracting, Multiplying, Dividing Numbers, Comparison Operators
for comparing values with each other and Bitwise Operators for combining
multiple conditions or changing their result. The “=” sign is considered its
own type and does not belong to arithmetic or comparison operators.

● Assignment Operator “ = “. Used to assign a value to a variable, array


element, object key or anything else.

● Arithmetic Operators

○ Plus ( + )
■ The Plus operator is used to add numbers to each other.
● i.e. 12 + 15, variable1 + variable2.
■ The plus operator can also be used with strings to combine
them together.
● i.e. “My name is “ + “Mudassar” will become “My
name is Mudassar”
■ Plus is the only operator that can be used with both strings
and numbers.
○ Minus ( - )
■ The minus operator is used to subtract one value from
another.
● i.e. 8 - 5, variable1 - variable2;
■ It can only be used on number-like values.

○ Multiply ( * )
■ The multiply sign is the asterisk ( * ).
■ It is used to multiply values to each other.
● i.e. 8 * 16, variable1 * variable2.
■ It can only be used on number-like values.

○ Divide ( / )
■ The divide sign is the forward slash ( / ).
■ It is used to divide one value by another.
● i.e. 5 / 2, variable1 / variable2.
■ It can only be used on number-like values.

○ Modulus ( % )
■ The modulus sign is the percentage symbol ( % ).
■ It is used to take the modulus of a value by another.
● Modulus just means division but the remainder is
returned instead of decimal value.
○ Modulus of 4 % 2 is 0, Whereas 5 % 2 is 1
● i.e. 7 % 2, variable1 % variable2.
■ It is only used on number-like values.
○ Exponent ( ** )
■ The exponent sign is double-asterisk ( ** ).
■ Exponent means raising the power of a number by another.
■ It is used to raise a number to any power.
● i.e. 8**2 (8 squared), variable1**variable2.
■ It is only used on number-like values

● Comparison Operators - All comparison operators result true or false.


They can be used on strings as-well as numbers.

○ Greater Than ( > )


■ Checks whether a value is greater than another.
■ i.e. 8 > 2, variable1 > variable2

○ Less Than ( < )


■ Checks whether a value is less than another.
■ i.e. 5 < 32, variable1 < variable2
○ Equals To ( == )
■ The equals-to symbol is the double equals sign ( == ).
■ Checks whether a value is equal to another.
■ i.e. 5 == 5, variable1 == variable2

○ Greater Than or Equal To ( >= )


■ The symbol is the >= sign.
■ Checks whether a value is greater than or equal to another
value.
■ i.e. 8 >= 4, variable1 >= variable2

○ Less Than or Equal To ( <= )


■ The symbol is the <= sign.
■ Checks whether a value is less than or equal to another
value.
■ i.e. 4 <= 4, variable1 <= variable2

○ Not Equal To ( != )
■ The symbol is the != sign.
■ Checks whether a value is not equal to another value.
■ i.e. 7 != 4, variable1 != variable2
● Bitwise Operators - They are used to combine multiple conditions
together. They can also be used to invert the result of a condition.
These operations represent the logic gates in mathematics.

○ AND ( && )
■ The symbol of the and operator is double-ampersand ( && ).
● The ampersand symbol is Shift + 7 on your keyboard.
■ This operator ONLY evaluates when the result of 2 or more
conditions is TRUE.
■ i.e. 8 > 5 && 6 < 4
● Will only evaluate if both conditions are True.

○ OR ( || )
■ The symbol of the and operator is double-pipe ( || ).
● The pipe symbol is under the backspace key on your
keyboard. You need to press Shift + Backspace to get
the pipe.
■ This operator evaluates even when only 1 condition from
multiple is true.
● If you have 5 conditions, and 4 of them are false but
one of them is true, This operator will evaluate.
■ i.e. 8 > 5 || 6 < 4
● Will evaluate as long as at-least one condition is true.

○ NOT ( ! )
■ The symbol of the and operator is exclamation ( ! ).
● The exclamation symbol is Shift + 1.
■ This operator INVERTS the result of any given condition.
● For example if you have a condition that is true such as
8 > 5, You can invert it’s result by !(8 > 5).
● If a condition is true, the not symbol will turn it to false.
● If a condition is false, the not symbol will turn it to true.

■ i.e. !(8 > 5)


● Will only run if the condition inside the brackets is
false.
● The not operator is usually used when you want to
check if a non-numeric value does not exist or does not
match.
○ For example, You may want to check if a user is
NOT an admin to show them a different part of
the website.
■ if (!user.admin)

—------------------------------------------------------------------------
Functions in JavaScript
—------------------------------------------------------------------------

A function in programming refers to a reusable block of code. If we have code


in our app that needs to be used again and again, we can write it inside a
block of code and call that function whenever we need it.

● Each function starts with its declaration with the “function” keyword.
● Then you write the function name which follows the same rules as the
variable naming scheme.
● After the function name, you add brackets ().
○ You can specify any parameters for that function in those brackets.
○ Parameters are just variables inside the function.
○ You don’t have to declare parameters with the “let” keyword.
They are declared automatically.
○ Parameters are used to work with dynamic values inside your
function.
○ When a function is called, we can specify any value as the
parameter.
● After the brackets, we start a code block with “{“ and “}”.
● Inside this code block, we write all the code of the function body.
○ This code will not be executed automatically.
○ We need to call the function to execute this code in our
application.
● A function may or may not have a return value.
○ A function without a return value is called a Void Function.
○ A function with a return value can be used in variables and if
statements to assign that value.


You can also make functions that have no name. These are usually used with
Events and callbacks. For example, when a button is clicked. We may want to
call a function, but we don’t have to give this function a name because It only
be called by the button and never again in the application.

In this case, we can use an unnamed function like so:

Unnamed function declaration is the same but You skip the function name.

—------------------------------------------------------------------------
If, Else If, Else in JavaScript
—------------------------------------------------------------------------

If, Else if, Else or If statements for short, are used to evaluate conditions in
JavaScript. For example, You may want to check if a student passed an exam,
or If a user’s password is correct before logging them in.
We use If statements to do this in JavaScript. Any time you want to check a
condition, You must use an if statement.

● An If statement starts with the “if” word followed by brackets ().


● Inside those brackets, You write your condition.
○ This can be a single condition using the comparison operators,
multiple conditions using bitwise operators and also the result of a
function or a variable.
● After the conditions, You start a code block with “{“ and “}”.
● Inside this code block, You write the code that you want to run if the
condition matches.
● After the if code block, You can add another “else if” code block to
check another condition if the first “if” does not match.
● You can keep adding as many “else if” blocks as you want.
● After this code block, You can add an “else” code block to run some
code if NO CONDITION MATCHES.
● An If statement can only have 1 “else” block but unlimited “else if”
blocks.

An example of an If, Else if, Else statement is given below.


—------------------------------------------------------------------------
Loops in JavaScript
—------------------------------------------------------------------------

A Loop is a code block in JavaScript that repeats the same action over and
over again. If you want to perform the same action in your code over and
over again in a sequence, You can use a Loop to do that.

There are 2 Types of Loops in JavaScript:

● For Loop
○ This loop runs for a specific amount of iterations and uses a loop
variable.
○ This is the most common and important type of loop.

● While Loop
○ This loop runs as long as a given condition matches.
○ While loop is not used as much as for loop. If you want to learn
about the while loop, Refer to W3Schools.

For Loop Usage.

A for loop uses a Loop variable, a condition and an increment / decrement to


work. It runs only for a specific amount of times that are derived by the
Condition & Increment of the loop variable.

The structure of a for loop is similar to an If statement.

● The loop starts with the “for” keyword.


● After the keyword, you add brackets ().
● Inside of the brackets, You need to give some information for the loop.
○ The first of these is the declaration of the loop variable.
■ The loop variable is declared with “let” and usually named
‘i’. It also usually starts at 0. However you may give it any
initial value.
■ The loop variable keeps track of the current iteration of the
loop while it is running.
○ After that, you add a ‘;’.
○ After the semi-colon, You describe the condition for the loop.
■ This condition must make use of the loop variable.
■ For example “i <= 10” - The loop will keep running as long as
the value of i is less than or equal to 10.
○ Add another ‘;’.
○ Finally, You must describe the increment / decrement of the loop
variable after every iteration.
■ You basically must describe how the loop variable should
change every time the loop runs.
■ For example: “i++” or “i = i + 1” means that the value of ‘i’
will increase by 1 everytime the loop runs.
■ The initial value is 0, after 1 time it will become 1, after 2
times it will become 2, and so on until the condition does
not match.

● After the loop information, You can start a code block with “{“ and “}”.
Any code within this block will keep repeating over and over again.
Always remember that the Loop Variable is accessible in the Loop Body.

—------------------------------------------------------------------------
Concluding Messages & Project Ideas
—------------------------------------------------------------------------

These notes only cover the fundamentals of JavaScript. You need to have a
very strong grip of the fundamentals in order to work with the language.

JavaScript is a language of Functions, Objects and Events. We did not read


about events in these notes because You will only understand events If you
write the code yourself.
15 minutes of Hands on practice is better than 2 hours in a lecture. Practice
these fundamentals in however way you like. It’s fine If you keep failing for a
bit, you will eventually understand everything and It will Click.

Here’s a few small project ideas to practice these fundamentals. These are
both advanced and beginner topics so choose one you feel is good for you.

● Factorial Calculator. (Easy)


○ Write a function that accepts a number.
○ Return the factorial of that number using a for loop.

● Multiplication Table Printer. (Easy)


○ Write a function that accepts a number.
○ Print the multiplication table (from 1 to 10) of that number.

● Create a Counter in JavaScript. (Easy)


○ Have 2 buttons and a paragraph in your HTML.
○ Reference these buttons and paragraph in your JavaScript.
○ The counter should start at 0.
○ One button will be a Decrement button.
■ When the decrement button is pressed, the number should
decrease by 1.
○ The other button will be an Increment button.
■ When the increment button is pressed, the number should
increase by 1.
● Create a Coin Flip Toss application. (Easy)
○ Have a button on your website.
■ When the button is pressed, A coin should be flipped and
Either Heads or Tails should be shown to the user.
○ BONUS Points for adding an animation with CSS.

● Create an Accordion Menu with JavaScript. (Easy)


○ Look at the Bootstrap Accordion Component for a demo.
○ Try to recreate the bootstrap accordion component by yourself in
JavaScript.

● Create a Dropdown Menu with JavaScript. (Easy)


○ Look at the Bootstrap Dropdown Menu for a demo.
○ Try to recreate the bootstrap dropdown component by yourself in
JavaScript.

● Create a Color Generator in JavaScript .(Intermediate)


○ Have a button on your website.
■ When the button is pressed, a random color should be
generated and applied to the body

● Create an Animated Modal in JavaScript. .(Intermediate)


○ Have a button on your website.
■ When this button is pressed, a modal should appear on the
page with an animation.
■ You can look at the Bootstrap modal for an example.
■ Try to recreate that modal along with CSS transitions.
● Sort an array of numbers in JavaScript (Difficult)
○ Have an array of numbers i.e. [ 8, 1, 3, 6, 93, 31 ]
■ Sort this array using a For Loop.
■ Implement an algorithm like Bubble Sort or one of your
choice.
■ DO NOT USE THE BUILT IN SORT FUNCTION.

● Create a Password Strength Progress Bar (Difficult)


○ Have a password input and progress bar on your page.
○ When the user types in something, you need to show them the
strength of their password by the following rules:
■ Minimum 8 characters = 50% strength. Yellow Color
■ Below 50% strength = Red Color
■ Above 80% strength = Green Color
■ Maximum strength goes to 100% and after that if the user
types in more characters, It stays at 100%.

You might also like