You are on page 1of 46

HTML

What is HTML?

1. HTML is the standard markup language for creating Web pages.

2. HTML describes the structure of a Web page


3. HTML consists of a series of elements
4. HTML elements tell the browser how to display the content

HTML is HyperText Markup Language for creating web pages, and its about
structure of the web page. It contains from elements so element describes how
we want to display the content

Difference between tag and element

Tag is opening or closing entity like <p></p>

Element is the whole thing that contains tag and text/content (optional) within
it,

like <p>hello world</p>

lets skip the types of HTML

What it DOCTYPE?

1. All HTML documents must start with a <!DOCTYPE> declaration.


2. The declaration is not an HTML tag. It is an "information" to the browser
about what document type to expect.
3. In HTML 5, the declaration is simple:
4. <!DOCTYPE html>

Meta tags in HTML?

 The <meta> tag defines metadata about an HTML document. Metadata is


data (information) about data.
 <meta> tags always go inside the <head> element, and are typically
used to specify character set, page description, keywords, author of the
document, and viewport settings.
 Metadata will not be displayed on the page, but is machine parsable.
 Metadata is used by browsers (how to display content or reload page),
search engines (keywords), and other web services.

 All HTML elements can have attributes

 Attributes provide additional information about elements

 Attributes are always specified in the start tag

 Attributes usually come in name/value pairs


like: name="value"
Semantic HTML?

Semantic HTML is the use of HTML markup to reinforce the semantics, or


meaning, of the information in webpages and web applications rather than
merely to define its presentation or look.

 Semantic elements = elements with a meaning.


 What are Semantic Elements?
 A semantic element clearly describes its meaning to both the browser and
the developer.
 Examples of non-semantic elements: <div> and <span> - Tells nothing
about its content.
 Examples of semantic elements: <form>, <table>, and <article> -
Clearly defines its content.

Inline and Block elements?


HTML has a default display values such as: block and inline

 A block-level element always starts on a new line, and the browsers


automatically add some space (a margin) before and after the element.
 A block-level element always takes up the full width available (stretches
out to the left and right as far as it can).
 EX: <p>, <h1>, <li>, <footer>, <section>, <form>

 An inline element does not start on a new line.


 An inline element only takes up as much width as necessary.
 Note: An inline element cannot contain a block-level element!
 EX: <span>, <a>, <br>, <img>, <select>, <textarea>
CSS

CSS – Cascading Style Sheets is used for styling the HTML document

CSS removed style formatting from the HTML page! It saves a lot of work.

What is Cascading?

 The “cascading” in CSS refers to the fact that styling rules “cascade”
down from several sources. This means that CSS has an inherent
hierarchy and styles of a higher precedence will overwrite rules of a lower
precedence.

Ways to insert CSS?

 External CSS
 we can change the look of an entire website by changing just one
file!
 External styles are defined within the <link> element, inside the
<head> section of an HTML page:

 Internal CSS

 An internal style sheet may be used if one single HTML page has a
unique style.
 The internal style is defined inside the <style> element, inside the
<head> section.

 Inline CSS

 An inline style may be used to apply a unique style for a single


element.
 Inline styles are defined within the "style" attribute of the relevant
element

If some properties have been defined for the same selector (element) in
different style sheets, the value from the last read style sheet will be used.

1. Inline style (inside an HTML element)


2. External and internal style sheets (in the head section)
3. Browser default

So, an inline style has the highest priority, and will override external and internal styles and browser defaults.

In choosing what CSS styles to apply to an HTML element, specificity overrides generality according
to a cascading set of rules that settle conflicts between styles:
1. Without CSS, the HTML will be displayed according to the browser’s default styles.
2. CSS tag selectors (matching the HTML tag) override browser defaults.
3. CSS class selectors (with .) override tag references.
4. CSS ID selectors (with #) override class references.
5. Inline CSS coded into an HTML tag override ID, class, and tag CSS.
6. Adding the !important value to a CSS style overrides everything else.
7. If CSS selectors are identical, the browser combines their properties. If the resulting CSS
properties conflict, the browser chooses the property value that appeared later or most
recently in the code.
A CSS selector that matches a more specific combination of tags, classes, and/or IDs will take
priority. Of the following examples, the first will take precedence over the second, regardless of
their order of appearance in the CSS:

Box Model?

All HTML elements can be considered as boxes.

The CSS box model is essentially a box that wraps around every HTML element. It
consists of:

 margins,
 borders,
 padding,
 content.

When you set the width and height properties of an element with CSS, you just
set the width and height of the content area. To calculate the full size of an
element, you must also add padding, borders and margins.

Total element width = width + left padding + right padding + left border +
right border + left margin + right margin

Total element height = height + top padding + bottom padding + top border
+ bottom border + top margin + bottom margin

Margin Collapse?

Top and bottom margins of elements are sometimes collapsed into a single
margin that is equal to the largest of the two margins.

This does not happen on left and right margins! Only top and bottom
margins!

 margin: 25px 50px 75px 100px;

o top margin is 25px

o right margin is 50px

o bottom margin is 75px

o left margin is 100px

The Position Properties?


The position property specifies the type of positioning method used for an element.

There are five different position values:

 static

 relative

 fixed

 absolute

 sticky

Elements are then positioned using the top, bottom, left, and right properties.
However, these properties will not work unless the position property is set first.
They also work differently depending on the position value.

Static

 all elements positioned static by default, means is not positioned in any


special way, but according to normal flow of the page
 these elements are not affected by the top, bottom, left, right

Relative

 element positioned relative to its normal position


 Setting the top, right, bottom, and left properties of a relatively-positioned
element will cause it to be adjusted away from its normal position.

Fixed

 positioned relative to the viewport, which means it always stays in the same
place even if the page is scrolled. The top, right, bottom, and left properties
are used to position the element.
 A fixed element does not leave a gap in the page where it would normally
have been located.

Absolute

 positioned relative to the nearest positioned ancestor (instead of positioned


relative to the viewport, like fixed)

 However; if an absolute positioned element has no positioned ancestors,


it uses the document body, and moves along with page scrolling.
 Note: Absolute positioned elements are removed from the normal flow,
and can overlap elements.

Sticky

 positioned based on the user's scroll position


 A sticky element toggles between relative and fixed, depending on the scroll
position. It is positioned relative until a given offset position is met in the
viewport - then it "sticks" in place (like position: fixed).
 You must also specify at least one of top, right, bottom or left for sticky
positioning to work
Transforming Elemenets?

The transform property applies a 2D or 3D transformation to an element. This


property allows you to rotate, scale, move, skew, etc., elements.

 translate: moves the element along up to 3 axis (x,y and z)

 rotate: moves the element around a central point

 scale: resizes the element

 skew: distorts the element

Pseudo-classes?

A pseudo-class is used to define a special state of an element. (single-colon: )

Ex:

 Style an element when a user mousses over it (hover)

 Style visited and unvisited links differently (visited)

 Style an element when it gets focus (focus)

Syntax:
selector:pseudo-class {
property: value;
}
The :first-child pseudo-class matches a specified element that is the
first child of another element.

Pseudo-elements?

A CSS pseudo-element is used to style specified parts of an element. (double-


colon:: )

Ex:

 Style the first letter, or line, of an element

 Insert content before, or after, the content of an element

 Selects the portion of an element that is selected by a user (selection)


 The ::marker pseudo-element selects the markers of list items.
selector::pseudo-element {
property: value;
}

CSS Selectors?

CSS selectors are used to "find" (or select) the HTML elements you want to style.
 Simple selectors (select elements based on name, id, class)

 Combinator selectors (select elements based on a specific relationship


between them)

 Pseudo-class selectors (select elements based on a certain state)

 Pseudo-elements selectors (select and style a part of an element)

 Attribute selectors (select elements based on an attribute or attribute value)

Units?

CSS has several different units for expressing a length.

A whitespace cannot appear between the number and the unit. However, if the
value is 0, the unit can be omitted.

There are two types of length units: absolute and relative.

The absolute length units are fixed and a length expressed in any of these will
appear as exactly that size.

EX: cm, mm, in, px*, pt, pc

Absolute length units are not recommended for use on screen, because screen sizes
vary so much. However, they can be used if the output medium is known, such as
for print layout.

*** Pixels (px) are relative to the viewing device. For low-dpi devices, 1px is one
device pixel (dot) of the display. For printers and high resolution screens 1px
implies multiple device pixels.

Relative length units specify a length relative to another length property. Relative
length units scales better between different rendering mediums.

Unit Description

em Relative to the font-size of the element (2em means 2 times the size of
the current font)

ex Relative to the x-height of the current font (rarely used)

ch Relative to width of the "0" (zero)

rem Relative to font-size of the root element

vw Relative to 1% of the width of the viewport*

vh Relative to 1% of the height of the viewport*

vmin Relative to 1% of viewport's* smaller dimension

vmax Relative to 1% of viewport's* larger dimension

% Relative to the parent element


Tip: The em and rem units are practical in creating perfectly scalable layout!
* Viewport = the browser window size. If the viewport is 50cm wide, 1vw = 0.5cm.

Adaptive and Responsive?

Responsive Design lets designers show content based on the browser space
available. This allows consistency between what a site shows on a desktop and
what it shows on a handheld device. Responsive design is the “traditional” option
and remains the more popular approach to date.

Pros Cons

 Uniform & seamless = good  Less screen size design


UX. control.
 Abundance of templates to  Elements can move around
use.
 Advertisements lost on screen.
 SEO friendly.
 Longer mobile download
 Often easier to implement times.

Adaptive Design, developed in 2011, is more involved in that the designer has
several fixed layout sizes. It offers an alternative to the “one-size-stretches-to-all”
approach.

Pros Cons

 Labor-intensive to create – most


 Allows designers to build adaptive designs are retrofitting
the best UX for the traditional sites to make them
appropriate device. more accessible.
 Mobile devices can sense  Tablets and netbooks can have
their user’s environment. trouble with site configuration
tending to be smartphone- or
 Designers can optimize desktop-oriented.
advertisements based on
user data from smart  Challenging to SEO — Search
devices. engines have trouble appreciating
identical content on multiple sites.

Desktop first vs Mobile first?

The term Mobile-First means that when developing a website, we start writing the
CSS for smaller viewport sizes first, and then use CSS media queries to alter the
experience for larger ones (e.g: tablets or desktops).
On the other hand, when we day Desktop First, it’s the other way around.

Media Queries?

Media queries in CSS3 extended the CSS2 media types idea: Instead of looking for
a type of device, they look at the capability of the device.

Media queries can be used to check many things, such as:

 width and height of the viewport

 width and height of the device

 orientation (is the tablet/phone in landscape or portrait mode?)

 resolution

Types

Value Description

all Used for all media type devices

print Used for printers

screen Used for computer screens, tablets, smart-phones etc.

speech Used for screen-readers that "reads" the page out loud

Display?

Compared to display: inline, the major difference is that display: inline-


block allows to set a width and height on the element.

Also, with display: inline-block, the top and bottom margins/paddings are
respected, but with display: inline they are not.

Compared to display: block, the major difference is that display: inline-


block does not add a line-break after the element, so the element can sit next to
other elements.

Flexbox?

The Flexible Box Layout Module, makes it easier to design flexible responsive layout
structure without using float or positioning.

The flex container becomes flexible by setting the display property to flex:
The flex container properties are:

 flex-direction(column, row etc.)

 flex-wrap(wrap, nowrap, wrap-reverse)

 flex-flow(flex-direction + flex-wrap => flex-flow: row wrap)

 justify-content(center, flex-start, flex-end, space-around, space-between)

 align-items(center, flex-start, flex-end, stretch, baseline)

 align-content(space-between, space-around, stretch, center, flex-start, flex-


end

The flex item properties are:

 order(specifies the order of the flex items, ex: style=’order:3’)


 flex-grow(specifies how much a flex item will grow relative to the rest of the
flex items)
 flex-shrink(specifies how much a flex item will shrink relative to the rest of
the flex items)
 flex-basis(specifies the initial length of a flex item)
 flex(is a shorthand property for the flex-grow, flex-shrink, and flex-
basis properties)
 align-self(specifies the alignment for the selected item inside the flexible
container and overrides the default alignment set by the container's align-
items property)

JavaScript

How to connect script file to HTML?


To use an external script, put the name of the script file in the src (source) attribute
of a <script> tag:
<script src="myScript.js"></script>

Difference between Async and defer?

‘async’ and ‘defer’ are boolean attributes which we use along with script tags to
load external javascript libraries efficiently into our web page

When the web page is loaded, the web browser looks at the entire HTML document
and looks for any CSS, JavaScript and images that are referenced by that page.
This is what we refer as HTML Parsing.

The web browser starts parsing the HTML and it gets paused when the script tag is
reached (here I am strictly talking about external JS Files and not the inline
scripts). At that point, parsing of HTML is blocked and browser makes a request to
fetch/download the respective script file. Once the script is fetched, it gets executed
and then HTML parsing resumes again.

But this is not good as the JavaScript files are blocking the rendering of HTML. So
this is where we can introduce our two attributes ‘async’ and ‘defer’.

The HTML parsing continues until the browser fetches the script file over the
network so parsing and script fetching happens in parallel (as shown in the figure
below). Once the scripts are available in the browser, HTML parsing is paused and
scripts are executed. Once the execution is complete, HTML parsing continues.

<script async src=”myscript.js”></script>

The word ‘defer’ in English means to ‘hold back’. So with defer attribute mentioned
in the script tag, the script files are downloaded in parallel while the HTML parsing
continues. But the execution is deferred until the HTML parsing is done. In simple
words, the downloaded scripts are executed only when the browser finishes its
HTML parsing.

<script defer src=”myscript.js”></script>

When to use ‘async’ and when to use ‘defer’?


Well, you can use async attribute when your page does not depend on the script
files (for example analytics). Why? Because async cannot guarantee the order in
which your scripts files will be downloaded. So if there is any dependency amongst
your script files, it may break your code. In such cases you can use defer attribute.

Variables?

Variables are containers for storing data (storing data values)

4 Ways to Declare a JavaScript Variable:

 Using var (old version)

 Doesn’t have Block Scope => variables declared inside {} can be


accessed from outside the block
 Can be re-declared

 Using let (if value of variable can change)

 Has Block Scope


 Can’t be re-declared, or Re-declaring is allowed just in other block
 Must be declared before use
 Using const (value can’t be changed)

 Has Block Scope


 Can’t be re-declared
 Can’t be re-assigned
 Must be assigned a value when they are declared
 Use const when declare: A new array, a new object, a new function,
 Const defines a constant reference to value, not a constant value,
that’s why we can’t re-assign a constant value, array or object, but
we can change the elements of constant array and the properties of
constant object.

 Using nothing

JavaScript identifiers are case-sensitive.

The Assignment Operator = ASSIGN


The "equal to" operator == LOOSE EQUALITY
The "equal to" operator === STRICT EQUALITY

Data types?
String

Number(NaN)

Boolean
Symbol

Object (Array)

Undefined- non-existence of data

Null-used to indicate that smth may be expected, but its currently unavailable

Type conversion and coercion?


Conversion (explicit conversion) – manually typing the method or function name
before converting the values

The type conversion only used in three data types:

 String (toString(), string(), toExponential(), toFixed())


 Number(Number(), parseInt(), parseFloat())
 Boolean
 Boolean(‘123’) => true
 Boolean(1) => true
 Boolean(0) => false
 Boolean(‘’) => false
 Boolean(‘ ’) => true
 Boolean(null) =>false
 Boolean(undefined) => false
 Boolean(NaN) => false

Coercion (Implicit Coercion)-coercion is similar to type conversion, but coercion is


performed automatically or implicitly by the JS engine. EX: built-in alert()
method(when we pass value JS automatically converts to string.

 To String coercion – when a string is added with the number or non-string value
with (+) the output is always a string.
EX: console.log(‘12’ + undefined) // 12undefined.
console.log(1 + ‘12’ + true) // 112true

 To Number coercion – math operations (-, *, /, % ) performed with the string


then the output of the expression is converted into a number implicitly
Note: in number coercion (+) operator is not used
EX: console.log(‘12’ - 2); // 10
console.log(‘hello’ – ‘world’); // NaN
console.log(‘hello’ * 2); // NaN
Note: if any one of the string is non-numeric than the result is the NaN

 To Boolean coercion – the Boolean values such as true and false are converted
to a number
EX: console.log(true+1); // 2
console.log(false-1); //-1
console.log(true*undefined); //NaN
console.log(false/null); //NaN
Falsy Values in JS?
“A falsy value is a value that is considered false when encountered in
a Boolean context.”

 0

 the BigInt 0n

 null

 undefined

 false

 NaN

 the empty string "" (equivalent to '' or ``)

ex: null == undefined // true

NaN== NaN // false

Function types?

Function is a block of code that perform a particular task when “something” invokes
it (calls it)

When JS reaches a return statement, the function will stop executing.

 You can define code once and reuse it many times, with many different
arguments.
1. Function declaration (function on the global scope)
Syntax: function name(param) {
statement
}
2. Function expression

 Can be stored in variable and called by variable name


 The main difference between a function expression and a function
declaration is the function name, which can be omitted in function
expressions to create anonymous functions.
 A function expression can be used as an IIFE (Immediately Invoked
Function Expression) which runs as soon as it is defined
 Function expressions in JavaScript are not hoisted(using function or
variable before declaration), unlike function declarations. You can't use
function expressions before you create them

Syntax: const name =function (param) {

statement
}

3. Arrow function
 An arrow function is a compact alternative to function expression, but it
has some limitations
---it doesn’t have own bindings to this or super
---not suitable for call, apply or bind methods
---it can’t be used as a constructor

Syntax: let name = (param) => {statement}

Scope(lexical/global/local)?

Scope determines the accessibility (visibility) of variables

Global Scope when variable is declared outside of the function and accessible
inside any function

 With JS, the global scope is JS environment


 In HTML, the global scope is the window object
 In HTML, global variables defined with “var” will become window
variables, but with “let” can’t be widow variables

Local Scope when we declare the function it creates its own scope which is
limited to that function, so it’s called local scope and all the variables which are
declared inside the function are just locally accessible.

Lexical Scope(origin) – if the current scope doesn’t find the value then it
moves outside to that scope and tries to find the value there. This process
continues until it finds the value.

Higher order functions and callbacks, IIFE?

“Higher-order function” is a function that accepts functions as parameters


and/or returns a function

In JavaScript “functions” are the first-class objects, because:

 Functions can be passed as parameters(callbacks) to other functions or


returned from them
 Can be assigned to variables or pass them around etc.
 They have built-in properties(name) and methods(.toSting() .map())
 ***Callback function => is a function passed as an argument to another
function
// Return function from function
function iReturnFunction() {
return function() { return 42 };
}
const myFunc = iReturnFunction();
myFunc(); // => 42

In the previous examples, iUseFunction() is higher-order because it accepts a


function as an argument. Also iReturnFunction() is a higher-order function because
it returns another function.

On the other side, the functions that use only primitives or objects as arguments,
and only return primitives or objects are named first-order functions.

In the previous examples, hiFunction() is a first-order function since it simply


returns a number.

Immediately Invoked Function Expression(IIFE) or Self-invoking function

 It runs as soon as its defined


 Do not create unnecessary global variables and functions
 Functions and variables defined in IIFE do not conflict with other functions
& variables even if they have same name.
 Organize JavaScript code.
 Make JavaScript code maintainable.

Syntax: (function () {

statement

}) ();

Pure Function?

 Given the same input, always returns the same output


 SAME INPUT => SAME OUTPUT
 Produces no side effects.

Pure Functions = Consistent Results

The first example returns a value based on the given parameters, regardless of
where/when you call it.

If you pass 2 and 4, you’ll always get 6.

Nothing else affects the output.

Impure Functions = Inconsistent Results

The second example returns nothing. It relies on shared state to do its job by
incrementing a variable outside of its own scope.

This pattern is a developer’s nightmare fuel.

Shared state introduces a time dependency. You get different results depending on
when you called the function. The first time results in 6, next time is 10 and so on.

Ex1: const add = (x, y) => x + y;


add(2, 4); // 6
Ex2: let x = 2;
const add = (y) => {
x += y;
};
add(4); // x === 6 (the first time)

Side Effects?

Any operation that not directly related to the final output (anything other than
return value) of the function is called the Side effect. Function with side effects is
an impure function

Example cases for side effects:

--Mutating(changing) the input itself

--Querying/Updating DOM

--Logging (even in the console)

--Making an XHR/fetch call

Note: reducing side effects as much as possible will improves program’s readability,
debuggability and testability

Closure?

Closure means that an inner function always has access to the vars and parameters
of its outer function, even after the outer function is returned

to be continued

Recursion?

Recursion is the process of calling itself.


The function that calls itself is called a recursive function
A recursive function must have a condition (like if…else) to stop calling itself, once
the condition is met, the function stops calling itself.

Syntax: Function recurse() {

//function code
recurse()

recurse();

example:

function countDown(fromNumber) {

console.log(fromNumber);
let nextNumber = fromNumber - 1;

if (nextNumber > 0) {

countDown(nextNumber);

countDown(3);

example: some of numbers with recursion

function sum(num){
if(num>0) {
return num + sum(num-1)
}else {return num}
}

console.log(sum(5)) //15

Array?

Array is a special variable, which can hold more than one value

Array mostly is declared with const, but it doesn’t define constant array, it defines
constant reference to array. So we can’t re-assign it but still can change the
elements of array.

 We access array element referring to the index number

Ex: const cars = [‘BMW’, ‘Saab’, ‘Volvo’]


cars[0] = ‘Opel’;
console.log(cars) // Opel Saab Volvo
 Arrays are a special type of objects (typeof is object)
 We can have objects, functions and arrays in Array!
 Array has the property length which returns the length of an array (number
of element)
Ex: accessing the last element => fruits[fruits.length -1]
 Array.isArray() => method to check if its array or not, ‘typeof’ returns just
object

Array Methods? (arrayName.method())

 toString() => converts an array to a string of(coma separated) array values


note JS automatically converts the array output with coma separated when
value is primitive
 join(‘ * ’) => joins all array elements into a string(same as toString,
separator can be specified instead of normal coma
 pop() => removes the last element from an array (this method returns value
as well: let lastFruit = fruits.pop())
 push() => method adds new element to an array at the end.
 shift() => removes the first array element(also returns shifted value)
 unshift() => adds a new element at the beginning
 delete fruits[0] => using delete leaves undefined holes in the array, better to
use pop() or shift(). Ex: fruits.length = 4; delete fruits[2]; fruits.length =4;
fruits[2]=undefined
 concat() creates new array by merging existing arrays, so it doesn’t change
existing arrays just returns new array. Also can add string values to array.
Ex: const myChildren = myGirls.concat(myBoys);
MyChildren=myGirls.concat(‘Jane’);
 splice() => adds new items to an array:
first parameter(2) defines the position where element should be added
second parameter(1) defines how many elements should be removed
Ex: const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 1, "Lemon", "Kiwi");//
//Banana, Orange, Lemon, Kiwi, Mango
 slice() => slices out a piece of an array into a new array.
So it doesn’t remove any elements from the source array, just creates a new
array.
slice(1) means starting from that element
or can take two arguments slice(1,3) starting from till(not included)

Ex: const fruits = [“banana”, “apple”, “peach”]


const citrus = fruits.slice(1)
// banana apple peach apple peach
 Sorting an array
 sort() => sorts an array alphabetically
 reverse() =>reverses the elements in an array
 Sorting the numbers => sort(function(a, b){return a-b})
=> sort(function(a, b){return b-a}) for descending
 The Fisher Yates method => sorting an array in random order
 Math.max.apply() => finding the highest number in an array
 Math.min.apply() => finding the lowest number in an array

 Array iteration
 forEach(myFunc(value, index, arrayItself) {}) => calls callback function once
for each array element, and doesn’t return anything
Ex: const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);

function myFunction(value) {
txt += value + "<br>";
}
 map() => creates a new array by calling function on each array element
=> doesn’t execute the function without values
=> doesn’t change the original array

forEach() vs map()

 Just about anything you can do with forEach() you can do with map(), and vise
versa.

 map() allocates memory and stores return values. forEach() throws away

return values and always returns undefined.

 forEach() will allow a callback function to mutate the current array. map() will

instead return a new array.

 filter() => creates a new array with array elements that passes a test
Ex: const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter(myFunction);

function myFunction(value, index, array) {


return value > 18;
}
 reduce() => runs a function on each array element to produce(reduce it to)
a single value
=> works from left-to-right in the array
=> doesn’t reduce the original array

Ex: const numbers = [45, 4, 9, 16, 25];

let sum = numbers.reduce(myFunction, 100); //output => 199

function myFunction(total, value, index, array) {

return total + value;

 reduceRight() => same as reduce() just starts from right side

 every() => check if all array values pass a test

Ex: const numbers = [45, 4, 9, 16, 25];


let allOver18 = numbers.every(myFunction); //output => false
function myFunction(value, index, array) {
return value > 18;
}

 some() => check if some array values pass a test


Ex: const numbers = [45, 4, 9, 16, 25];
let someOver18 = numbers.some(myFunction);//output=>true
function myFunction(value, index, array) {
return value > 18;
}
 indexOf() => searches an array for an element value and returns its position
=> if item not found returns -1
=> if the item is present more than once, returns first’s position

Ex: const fruits = ["Apple", "Orange", "Apple", "Mango"];


let position = fruits.indexOf("Apple") // output => 0
 lastIndexOf() => same as indexOf() just returns position of the last
occurrence
 find() => returns the value of the first array element that passes a test
function
Ex: const numbers = [4, 9, 16, 25, 29];
let first = numbers.find(myFunction); // output=> 25

function myFunction(value, index, array) {


return value > 18;
}
 findIndex() => returns the index of the first array element that passes a
test function.
 Array.from() => returns an Array object from any object with a length
property or any iterable object
Ex: Array.from("ABCDEFG");// output => A,B,C,D,E,F,G
 Array.keys() => returns an Array Iterator object with the keys of an array
Ex: const fruits = ["Banana", "Orange", "Apple", "Mango"];
const keys = fruits.keys();// output=> 0 1 2 3

for (let x of keys) {


text += x + "<br>";
}
 Array.entries() => Create an Array Iterator, and then iterate over the
key/value pairs
=> does not change the original array
=> returns an Array Iterator object with key/value pairs
Ex: const fruits = ["Banana", "Orange"];
const f = fruits.entries();

for (let x of f) {
document.getElementById("demo").innerHTML += x;
}
Output: [0, "Banana"]
[1, "Orange"]
 includes() => checks if an element is present in an array(including NaN,
unlike indexOf)
Ex: const fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.includes("Mango"); // is true
Objects vs Primitives?

JS has 8 data types, 7 of them are primitive and 1 is objects

 primitive values and object references are stored in JS programs in different


ways
=> when primitive values assigned to variables, the variable is set to that
value directly
=> when variable assigned with an object, the variable contains a
reference to, not a value directly
=> primitive values are immutable (not changeable)
=> object references are mutable

Context ‘this’?

 In JS, the ‘this’ keyword refers to an object


 ‘Which’ object depends on how ‘this’ is being invoked (used or called)
 This is not a variable. It is a keyword. We can’t change the value of this
 ‘This’ keyword refers to different objects depending on how it is used
=> In an object method, this refers to the object
Ex: const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
}; //output=> John Doe
=> Alone, this refers to the global object (even with strict mode)
Ex: let x = this;// output=> [object window]
=> In a function, this refers to the global object
Ex: function myFunction() {
return this;// output=> [object window]
}
=> In a function, in strict mode, this is undefined
Ex: "use strict";
function myFunction() {
return this; // output=> undefined
}
=> In an event, this refers to the element that received that event
Ex: <button onclick="this.style.display='none'">
Click to Remove Me!
</button>
=>Methods like call(), apply(), and bind() can refer this to any object

Context is the value of the ‘this’ keyword, which is a reference to the object that
‘owns’ the currently executing code or the function where it’s looked at.

Ex: window is the global object in the browser so if we type ‘this’ in the console it
will return window object

In JavaScript, the this keyword allows us to:


 Reuse functions in different execution contexts. It means, a function once
defined can be invoked for different objects using ‘this’ keyword.

Ex: let user = {name: ‘user’}

let admin = {name: ‘admin’}

function myName() {

console.log(`my name is ${this.name}`)

user.func = myName;

admin.func =myName;

user.func()// output=> my name is user;

admin.func()// output=> my name is admin;

 Identifying the object in the current execution context when we invoke a


method.

Object methods, entries, values, for of loop, for in loop?

 Method is just a function which is created inside the object


 All objects in JS descend from the parent Object constructor and Object has
many built-in methods.
Ex:
 Object.create()
 used to create a new object and link it to the prototype of
an existing object
 We can create a job object instance, and extend it to a
more specific object

Ex: // Initialize an object with properties and methods


const job = {
position: 'cashier',
type: 'hourly',
isAvailable: true,
showDetails() {
const accepting = this.isAvailable ? 'is accepting applications' : "is not currently accepting
applications";

console.log(`The ${this.position} position is ${this.type} and ${accepting}.`);


}
};

// Use Object.create to pass properties


const barista = Object.create(job);

barista.position = "barista";
barista.showDetails();

 Object.keys()
 creates an array containing the keys of an object

Ex: // Initialize an object


const employees = {
boss: 'Michael',
secretary: 'Pam',
sales: 'Jim',
accountant: 'Oscar'
};

// Get the keys of the object


const keys = Object.keys(employees);

console.log(keys);

Output

["boss", "secretary", "sales", "accountant"]

 Object.values()
 Creates an array containing the values of an object

Ex: // Initialize an object


const session = {
id: 1,
time: `26-July-2018`,
device: 'mobile',
browser: 'Chrome'
};

// Get all values of the object


const values = Object.values(session);

console.log(values);

Output

[1, "26-July-2018", "mobile", "Chrome"]

 Object.entries()
 Creates a nested array of the key/value pairs of an object
Ex: // Initialize an object
const operatingSystem = {
name: 'Ubuntu',
version: 18.04,
license: 'Open Source'
};

// Get the object key/value pairs


const entries = Object.entries(operatingSystem);

console.log(entries);

Output

["name", "Ubuntu"]

["version", 18.04]

["license", "Open Source"]

 Object.assign()
 Is used to copy values from one object to another
 We can create two objects and merge them as well
 Note: spread operator also can be used instead of assign()

Ex: // Initialize an object


const name = {
firstName: 'Philip',
lastName: 'Fry'
};

// Initialize another object


const details = {
job: 'Delivery Boy',
employer: 'Planet Express'
};

// Merge the objects


const character = Object.assign(name, details);

console.log(character);
Output

{firstName: "Philip", lastName: "Fry", job: "Delivery Boy", employer: "Planet Express"}

 Object.freeze()
 prevents modification to properties and values of an object,
and prevents properties from being added or removed from
an object.
 Object.seal()
 prevents new properties from being added to an object, but
allows the modification of existing properties. This method
is similar to Object.freeze().
 Object.getPrototypeOf()
 is used to get the internal hidden [[Prototype]] of an object,
also accessible through the __proto__ property.

Loops (executing a block of code a number of times)

 for – loops through a block of code a number of times


 for (statement1; statement 2; statement 3) {//code block}

Statement 1 sets a variable before the loop starts (let i = 0).

Statement 2 defines the condition for the loop to run (i must be less than 5).

Statement 3 increases a value (i++) each time the code block in the loop has
been executed.

for (let i = 0; i < 5; i++) {


text += "The number is " + i + "<br>";
}

 for/in – loops through the properties(key) of an object


 for (key in object) {//code block}

Ex: const person = {fname:"John", lname:"Doe", age:25};

let text = "";


for (let x in person) {
text += person[x]; //output=> John Doe 25
}

Example Explained

 The for in loop iterates over a person object


 Each iteration returns a key (x)
 The key is used to access the value of the key
 The value of the key is person[x]
 for/of – loops through the values of an iterable object
 It lets you loop over iterable data structures such as Arrays,
Strings, Maps, NodeLists, and more
 for (variable of iterable) {//code block}
Ex: const cars = ["BMW", "Volvo", "Mini"];

let text = "";


for (let x of cars) {
text += x; // output=> BMW
Volvo
Mini
}
 while – loops through a block of code while a specified condition is true
Ex: while (i < 10) {
text += "The number is " + i;
i++;
}
 do/while – also loops through a block of code while a specified condition is
true
 will execute code block once, before checking if the condition
is true, then it will repeat the loop as long as the condition is
true

Ex: do {
text += "The number is " + i;
i++;
}
while (i < 10);

Date object?

By default, JS will use the browser’s time zone and display a date as a full text
string

 date objects are created with the new Date() constructor


 new Date() creates a new date object with the current date and time
 JS counts month from 0 to 11, if month specified higher than 11, it will just
overflow to the next year
 new Date(year, month, day, hour, minute, second, millisecond) creates a new
date object with a specified date and time.
Ex: const d = new Date(2018, 11, 24, 10, 33, 30, 0);
//output=> Mon Dec 24 2018 10:33:30 GMT+0600 (GMT+06:00)
 We can’t omit month. Coz only one parameter it will be treated as
milliseconds.
 ISO 8601 is the international standard for the representation of dates and
times and follows a strict standard in JavaScript. Syntax: (YYYY-MM-DD)
Ex: const d = new Date("2015-03-25");
const d = new Date("2015-03");// without day also can be written
 Date.parse() method converts a valid date string to milliseconds
 Then, it returns the number of milliseconds between the date & January 1,
1970
 We can then use the number of milliseconds to convert it to a date object:
Ex: let msec = Date.parse("March 21, 2012");
const d = new Date(msec);
Date Get Methods

Can be used for getting information from a date object

Ex: const d = new Date();


d.getFullYear(); d.getDate();

d.getMonth(); d.getHours();

Date Set Methods

Can be used to set date values (years, months, days, hours, minutes,
seconds, milliseconds) for a Date Object
Ex: const d = new Date();
d.setFullYear(2020); d.setFullYear(2020, 11, 3);
d.setMonth(11); d.setDate(15);

Regular Expressions?

 It is a sequence of characters that forms a search pattern


 The search pattern can be used for text search and text replace operations
 Syntax: /pattern/modifiers(flags);
 String methods:
search() => it uses an expression to search for a match, and returns
the position of the match
replace()=> returns a modified string where the pattern is replaced
match()=> Returns an array containing all of the matches, including
capturing groups, or null if no match is found.
split()
 RegExp methods:
exec()=>Executes a search for a match in a string. It returns an
array of information or null on a mismatch.
test() =>Tests for a match in a string. It returns true or false.
 Can be constructed in 2 ways:
=> using a regular expression literal
-when regular expression remains constant better to use this
Ex: const re = /ab+c/flags
=> calling the constructor function of the RegExp object:
-use this when regular expression pattern will be changing, like user input
Ex: const re = RegExp(‘ab+c’, ‘flags’)

Arrow function, Rest operator, Spread Operator, array de-structuring?

Arrow function:

 It allows shorter function syntax => hello = () => {return ‘hello’}


 Unlike regular functions, arrow functions do not have their own this. The
value of this inside an arrow function remains the same throughout the
lifecycle of the function and is always bound to the value of this in the closest
non-arrow parent function.
 The arrow functions are only callable and not constructible, i.e arrow
functions can never be used as constructor functions. Hence, they can never
be invoked with the new keyword.
 No duplicate named parameters regardless strict or non-strict, like (x,x) =>
{}// it won’t be working
 Arrow functions don’t have an arguments binding

Rest operator vs Spread operator:

 The main difference is that the rest operator puts the rest of some specific
user-supplied values into a JS array. But the spread operator expends
iterables into individual elements.
 (…rest) => rest parameter:
 It creates a single resulting array from all elements in each
iteration of the loop
 It allows to handle a variety of inputs as arguments in a
function easily, so can supply an array with an endless
number of parameters
Ex: variable const [name, lastName, ...otherval] = [
"Writer", "Developer", "Designer", "UI/UX", "Tech Lead"
];
console.log(otherval);// It will return
['Designer', 'UI/UX', 'Tech Lead']
 (…spread) =>spread operator:
 It loops through an array, pushing each item from the
current array into a new one
 Spread is mainly used with arrays, but can be applied to
objects
 It breaks it up into individual variables of the same name,
or- merges a list of variables into a single statement, or –
converts an object to an array.
Ex: const info = ["My", "Name", "is"];
const info2 = ["Hello,", ...info, "Harshil."];

console.log(info2);
//returns - > ['Hello,', 'My', 'Name', 'is', 'Harshil.']
 Converting a String into Individual Array Items Using Spread
Ex: const name = "Harshil Patel";
console.log([...name]);
//returns - > ['H', 'a', 'r', 's', 'h', 'i', 'l', ' ', 'P', 'a', 't', 'e', 'l']
 Copying arrays
Ex: const arr1 = [1, 2, 3];
const arr2 = [...arr1];
console.log(arr2);
 Using Spread in a Function Call => passing array as an argument
Ex: function sum(a, b, c, d) {
return a + b + c + d ;
}
const args = [1, 2, 3, 4];
console.log(sum(...args));
//returns - > 10
Arguments Object => is an Array-like object accessible inside functions that
contains the values of the arguments passed to that function.

 We can refer to a function’s argument inside that function by using


‘arguments[i]’
 Except ‘Arrow Function’ all functions have arguments object
 Its ‘Array-like’ but not an array, it has just property ‘length’.
 Other array’s built-in methods are not available

Ex: function func1(a, b, c) {

console.log(arguments[0]); // expected output: 1

func1(1, 2, 3);

Array destructuring: allows to extract an array’s value into new variables

Ex: const profile = [‘Jey’, ‘Sofi’, ‘codeers.com’];

const [firstName, lastName, website] = profile;

console.log(firstName); //Jey

Ex: direct array destructuring

const [firstName, lastName, website] = [

"Oluwatobi",

"Sofela",

"codesweetly.com"

];

 JavaScript allows you to use the rest operator within a destructuring array to
assign the rest of a regular array to a variable.
Ex: const [firstName, ...otherInfo] = ["Oluwatobi", "Sofela","codesweetly.com"];

console.log(firstName); // "Oluwatobi"
console.log(otherInfo); // ["Sofela", "codesweetly.com"]

Above what if we want extract “codesweetly.com”?


Ex: const [, , website] = ["Oluwatobi", "Sofela", "codesweetly.com"];

console.log(website); // "codesweetly.com"

 Extracting values from an Array to a Function’s Parameters (destructuring


parameter)
Ex: // Define an array with two items:
const profile = ["Oluwatobi", "Sofela"];
// Define a function with one destructuring array containing two parameters:
function getUserBio([firstName, lastName]) {
return `My name is ${firstName} ${lastName}.`;
}

// Invoke getUserBio while passing the profile array as an argument:


getUserBio(profile);

// The invocation above will return:


" My name is Oluwatobi Sofela."

Object destructuring? Map, Set

Ex: const profile = {

firstName: "Oluwatobi",

lastName: "Sofela",

website: "codesweetly.com"

};

const {firstName: firstName, lastName: lastName, website: website} = profile;

Note: firstName(key reference to the profile objects firstName key): firstName(this value represents the new value)

Below is shorthand syntax:

const profile = {

firstName: "Oluwatobi",

lastName: "Sofela",

website: "codesweetly.com"

};

const {firstName, lastName, website} = profile;

 Direct object destructuring:


Ex: const { firstName, lastName, website } = {
firstName: "Oluwatobi",
lastName: "Sofela",
website: "codesweetly.com"
};

 Rest operator:
Ex: const { firstName, ...otherInfo } = {
firstName: "Oluwatobi",
lastName: "Sofela",
website: "codesweetly.com"
};
console.log(firstName); // "Oluwatobi"
console.log(otherInfo); // {lastName: "Sofela", website:"codesweetly.com"}
 Extracting values from Properties to a Function’s Parameter
Ex:
// Define an object with two properties:
const profile = {
firstName: "Oluwatobi",
lastName: "Sofela",
};

// Define a function with one destructuring object containing two parameters:


function getUserBio({ firstName, lastName }) {
return `My name is ${firstName} ${lastName}.`;
}

// Invoke getUserBio while passing the profile object as an argument:


getUserBio(profile);

// The invocation above will return:


"My name is Oluwatobi Sofela."

Map
Map is a collection of keyed data items, just like an Object. But the main
difference is that Map allows keys of any type.
o Unlike objects, keys are not converted to strings. Any type of key is
possible.
o Map is iterable unlike plain object
o Map can also use objects as keys.
o Even NaN can be used as a key, coz in Map NaN is considered equal to
NaN
 new Map() – creates the map.
 map.set(key, value) – stores the value by the key.
 map.get(key) – returns the value by the key, undefined if key doesn’t exist
in map.
 map.has(key) – returns true if the key exists, false otherwise.
 map.delete(key) – removes the value by the key.
 map.clear() – removes everything from the map.
 map.size – returns the current element count.

Ex: let map = new Map();

map.set('1', 'str1'); // a string key

map.set(1, 'num1'); // a numeric key

map.set(true, 'bool1'); // a boolean key

// remember the regular Object? it would convert keys to string

// Map keeps the type, so these two are different:

alert( map.get(1) ); // 'num1'

alert( map.get('1') ); // 'str1'


alert( map.size ); // 3

Iteration over Map

1) map.keys() – returns an iterable for keys,

2) map.values() – returns an iterable for values,

3) map.entries() – returns an iterable for entries [key, value], it’s used by default
in for…of

Ex: let recipeMap = new Map([

['cucumber', 500],

['tomatoes', 350],

['onion', 50]

]);

// iterate over keys (vegetables)

for (let vegetable of recipeMap.keys()) {

alert(vegetable); // cucumber, tomatoes, onion

// iterate over values (amounts)

for (let amount of recipeMap.values()) {

alert(amount); // 500, 350, 50

// iterate over [key, value] entries

for (let entry of recipeMap) { // the same as of recipeMap.entries()

alert(entry); // cucumber,500 (and so on)

Map has a built-in forEach method, similar to array:

Ex: recipeMap.forEach( (value, key, map) => {

alert(`${key}: ${value}`); // cucumber: 500 etc

});

Creating a Map from a plane object with built-in method


Object.entries(obj)

Ex: let obj = {

name: "John",
age: 30

};

let map = new Map(Object.entries(obj));

alert( map.get('name') ); // John

Object.entries returns the array of key/value pairs: [ ["name","John"],


["age", 30] ]

Object.fromEntries does the reverse: so we can get plain object from Map

Set?

A set is a special type of collection – “set of values”(without keys), where each


value may occur only a once.

Methods of Set:

 new Set (iterable) – creates the set, and if an iterable object is provided(usually
an array), copies the values from it into the set
 set.add(value) – adds a value , returns the set itself
 set.delete (value) – removes the value, returns true if value existed at the
moment of the call, otherwise false
 set.has(value) – returns true if the value exists in the set, otherwise false
 set.clear() – removes everything from the set
 set.size – is the elements count

Note: set.add(value) with the same value don’t do anything, coz each value should
appear only once

For example, we have visitors coming, and we would like to remember everyone.
But repeated shouldn’t lead to duplicates. Visitor should be counted only once

Ex: let set = new Set();

let john = { name: "John" };

let pete = { name: "Pete" };

let mary = { name: "Mary" };

// visits, some users come multiple times

set.add(john);

set.add(pete);

set.add(mary);

set.add(john);

set.add(mary);

// set keeps only unique values


alert( set.size ); // 3

for (let user of set) {

alert(user.name); // John (then Pete and Mary)

Iteration over Set

Both can be used for loop: for…of and forEach

Ex: let set = new Set(["oranges", "apples", "bananas"]);

for (let value of set) alert(value);

// the same with forEach:

set.forEach((value, valueAgain, set) => {

alert(value);

});
Note:The callback function passed in forEach has 3 arguments: a value, then the same
value valueAgain, and then the target object. Indeed, the same value appears in the arguments twice.

That’s for compatibility with Map where the callback passed forEach has three arguments(key, value,
map). Looks a bit strange, for sure. But may help to replace Map with Set in certain cases with ease,
and vice versa.

The same methods Map has for iterators are also supported:

 set.keys() – returns an iterable object for values,

 set.values() – same as set.keys(), for compatibility with Map,

 set.entries() – returns an iterable object for entries [value, value], exists for
compatibility with Map.

OOP?
OOP is a programming paradigm (style of programming) or model centered
around objects rather than functions

Ex: programming languages that support OOP: C#, Java, Ruby, Python, JavaScript

4 pillars of OOP:

 Encapsulation
In OOP we combine group of related variables(properties) and
functions(methods) into a unit (object)
Ex: Local Storage is an object with properties and methods

Ex:
Procedural programming:
let baseSalary = 3000;
let overtime = 10;
let rate = 20;
function getWage (baseSalary, overtime, rate) {
return baseSalary + (overtime * rate);
}
Object-oriented programming:
let employee = {
baseSalary: 3000,
overtime: 10,
rate: 20,
getWage: function() {
return this.baseSalary + (this.overtime * this.rate);
}
}

“The best functions are those with no parameters!”

 Abstraction
Hiding some of the methods and properties from the outside, which means:
- Simpler Interface
- Reduce the impact of change
- By declaring local variable we can hide certain members
from outside

 Inheritance
Inheritance is a mechanism that allows us to eliminate
redundant(unnecessary) code
Ex: let’s say that we have 3 HTML elements: Textbox, Select, CheckBox
So, all these elements have a few things in common like
Properties: --hidden
--innerHTML
Methods: --click()
--focus()
Instead of redefining all these properties and methods for every HTML
element, we can define them once in a generic object called HTMLElement
and help other objects inherit these properties and methods

 Polymorphism
Poly means => many morphism means=> form
In OOP polymorphism is technique that allows us to get rid of long if/else or
switch/case statements

Briefly:

Encapsulation => Reduce complexity + increase reusability

Abstraction => Reduce complexity + isolate impacts of changes

Inheritance => Eliminate redundant code

Polymorphism=> Refactor ugly switch/case statements

 Every object in JS has a property called “constructor” and that reference


JavaScript is a prototype-based language

Ex: let names = {

fname: "Dillion",

lname: "Megida"

console.log(names.fname);

console.log(names.hasOwnProperty("mname")); => from Object prototype

// Expected Output

// Dillion

// false

The _ _proto_ _ property


 This points to the object which is used as a prototype
 Object.create() => uses the argument passed to it to become the prototype
 “new” keyword approach does the same thing as Object.create(), but it’s
much simple
 Every object in JS has access to the Object’s prototype property by default
 In ECMAScript 2015 introduced “class” keyword, it makes JS seem like an
OOP language. But it is just syntactic sugar over the existing prototyping
technique.

Ex: Using just “new” keyword approach


function Animals(name, specie) {
this.name = name;
this.specie = specie;
}
Animals.prototype.sing = function(){
return `${this.name} can sing`;
}
Animals.prototype.dance = function() {
return `${this.name} can dance`;
}
let Bingo = new Animals("Bingo", "Hairy");
Ex: Translating it to “class” usage in JS
class Animals {
constructor(name, specie) {
this.name = name;
this.specie = specie;
}
sing() {
return `${this.name} can sing`;
}
dance() {
return `${this.name} can dance`;
}
}
let bingo = new Animals("Bingo", "Hairy");
console.log(bingo);

Subclassing

Ex: class Animals {


constructor(name, age) {
this.name = name;
this.age = age;
}
sing() {
return `${this.name} can sing`;
}
dance() {
return `${this.name} can dance`;
}
}
class Cats extends Animals {
constructor(name, age, whiskerColor) {
super(name, age);
this.whiskerColor = whiskerColor;
}
whiskers() {
return `I have ${this.whiskerColor} whiskers`;
}
}
let clara = new Cats("Clara", 33, "indigo");

Classes, constructor()
 Classes are a template for creating objects.
 Constructor() is a special method for creating and initializing objects
created within a class
 Class keywords: => extends – extends a class(inherit)
=> static – defines a static method for a class
=> super – refers to the parent class

Ex: class Car {


constructor(brand) {
this.carname = brand;
}
present() {
return 'I have a ' + this.carname;
}
}

class Model extends Car {


constructor(brand, mod) {
super(brand);
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model;
}
}

mycar = new Model("Ford", "Mustang");


document.getElementById("demo").innerHTML = mycar.show();

Keyword “new”
- It generates an empty object
- Adds a property to the new object (_proto_) that links to
the constructor function’s prototype object
- Binds the newly created object instance as the ‘this’
context
- Returns ‘this’ if the function doesn’t return an object
Ex: function Foo(bar1, bar2) {
this.bar1 = bar1;
this.bar2 = bar2;
}
var myFoo = new Foo('Bar 1', 2021);

Inheritance
JS is prototype-based language not class-based. The ‘class’ keyword is
introduced in ES2015, but is “syntactical sugar”.
 JS only has one construct: objects
 Each object has a private property which holds a link to another
object called its “prototype”.
 Null has no prototype, and acts as the final link in this “prototype
chain”
 All objects in JS are instances of Object, which has null as its
prototype

Ex: const o = {
a: 2,
m: function() {
return this.a + 1;
}
};

console.log(o.m()); // 3
// When calling o.m in this case, 'this' refers to o

const p = Object.create(o);
// p is an object that inherits from o

p.a = 4; // assign the value 4 to the property 'a' on p (Property


Shadowing)
console.log(p.m()); // 5
// when p.m is called, 'this' refers to p.
// So when p inherits the function m of o,
// 'this.a' means p.a, the property 'a' of p

[[Prototype]] vs __proto__
[[Prototype]] => is a hidden property that references an object’s prototype.
__proto__ => is a method that exposes the hidden [[Prototype]] property and
allows you to modify it. (like getter and setter)
Object.getPrototypeOf() and Object.setPrototypeOf() are the modern ways of
getting access to and setting an object’s prototype.
.prototype=> is a special property that all functions have that contains a
reference to an object (arrow functions doesn’t have)

Class Instance

Use Strict
=> makes it easier to write “secure” JavaScript
EX: can’t use undeclared variables, some keywords not allowed to be the
name of variables, objects or functions can’t be deleted etc.

SetTimeout
=> is a method that calls a function after a number of milliseconds
Syntax: myTimeout = setTimeout(function, milliseconds);
 Its executed only once. If you need repeated execution use
setInterval()
 clearTimeout() method prevents the function from starting

Browser
Browser APIs
API – Application Programming Interface => a set of protocols and
definitions that allows communication between two software.
Browser APIs => are APIs that are built into the browser and provide native
features that can be also be used in a web app. These can be called also web
APIs.
 Making network requests
 Managing client-side storage
 Retrieving device media streams, etc
Categories of browser APIs:
 Fetch API
 APIs for manipulating document structure
 Device APIs
 APIs for drawing graphics
 Storage APIs
 Audio and Video APIs etc.

What is DOM?
DOM => Document Object Model

 Created by browser when a web page is loaded


 In graphical form, it looks like a tree of element/nodes
 Programmatically, we can use JS to read or change the DOM
 With the HTML DOM, JavaScript can access and change all the elements
of an HTML document

What is BOM?
BOM => Browser Object Model

 It allows to JS “talk to” the browser


 BOM includes the properties (global variables) and methods (global
functions) for JS to interact with the web browser.
 BOM provides you with a window objects
 Window object is supported by all browsers and it represents the
browser’s window
 All global JS objects functions and variables automatically become
members of the window object
 Window object Properties: Navigator, screen, location, history,
document etc.
 Window object Methods: alert(), prompt(), scroll() setTimeout() etc.

BOM DOM

Is Browser Object Model Is Document Object Model

Used for access and manipulation of the browser window Used to manipulate the HTML document.

No standard set of rules, each browser has its own Has a set standard of rules to be used
standards for implementing BOM across documents.

Global Variables in Browser


JS global variable => is declared outside the function or declared with window
object. It can be accessed from any function

Window Object => is a global object and represents an open window in the
browser

In the browser, your global variables are automatically assigned as a


property of the window object.
Ex: var username = "Jack";
console.log(`window.username: ${window.username}`);
You can access the username variable using username or window.username as in
the following example.

 But this kind of behavior is only triggered when you create a variable using
the var keyword. Variables created with either let or const keyword won’t
be assigned as a property of the window object.
 Global variables are good only when it’s built into the JavaScript engine

History, Location, Navigator


History => returns the History object for the window

=> contains the URLs visited by user (in the browser window)

=> accessed with window.history or just history

Location => returns the Location object for the window


=> contains information about the current URL

=> accessed with window.location or just location

Navigator => returns Navigator object for the window

=> contains information about the browser ex: language, geolocation

What is Event?
JavaScript’s interaction with HTML is handled through events that occur when the user or the
browser manipulates a page.

Ex: when the page loads, it is called an event; when the user clicks a button, that
click too is an event

What are the phases of Event?


There are 3 phases in a JS event: Lifecycle of JS event

 Capture phase => event propagates starting from ancestors towards the
parent of the target. Propagation starts from Window Object
 Target phase => The event reaches the target element or the element which
started the event
 Bubble phase => this is the reverse of capture. Event is propagated towards
ancestors until Window Object.

Capturing Phase is when event goes down to the element. (root-> target)

Target phase is when event reach the element and

Bubbling phase is when the event bubbles up from the element.(target-> root)

What does preventDefault?


The preventDefault() method cancels the event if it is cancelable, meaning that
the default action that belongs to the event will not occur

Ex:

 Clicking on a "Submit" button, prevent it from submitting a form

 Clicking on a link, prevent the link from following the URL

Note: Not all events are cancelable. Can be checked by


event.cancelable //returns true or false.

If event is not cancelable in that case should be used stopPropogation() method.

What is Event Propagation?


Propagation is the process of how events travel through the DOM tree.
Capturing and Bubbling are the phases of propagation

stopPropogation() => prevents any parent handlers from being executed

stopImmediatePropogation() => prevents any parent handlers and also other


handlers (in the same element) from executing.

localStorage vs sessionStorage vs cookie?


=> localStorage: the data is persisted until the user manually clears the
browser cache or until your web app clears the data.
Accessible from any window.
Storage location: browser only.

=> sessionStorage: the data is persisted only until the window or tab is
closed.
Accessible from the same tab.
Storage location: browser only.

Note: localStorage and sessionStorage are almost identical and have the
same API

=> cookie: expiration date is set manually.


Accessible from any window.
Storage location: browser and server.

Example cases of using Browser storage:


 Personalizing site preferences

 Persisting site activities

 Storing the login state

 Saving data locally so that the website will be quicker to download or


use without a network connection

 Improving website performance

 Reducing back-end server requests

What is indexedDB?
IndexedDB is a database that is built into a browser, much more powerful than
localStorage. LocalStorage is useful for storing smaller amounts of data. But
indexedDB allows to store significant amounts of structured data.

Async JS?

You might also like