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

Javascript Short Notes -beginner

The document outlines various JavaScript concepts including expressions, conditionals, loops, functions, strings, and arrays. It provides syntax examples and explanations for operators, conditional statements, loop types, and array methods, as well as how to utilize JavaScript in a browser environment. Additionally, it covers the use of developer tools and console methods for debugging and interaction.

Uploaded by

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

Javascript Short Notes -beginner

The document outlines various JavaScript concepts including expressions, conditionals, loops, functions, strings, and arrays. It provides syntax examples and explanations for operators, conditional statements, loop types, and array methods, as well as how to utilize JavaScript in a browser environment. Additionally, it covers the use of developer tools and console methods for debugging and interaction.

Uploaded by

ok not
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Table of Contents

Chapter 2 - Expressions & Conditionals.................2


Chapter 3 - Loops & Functions...............................4
Chapter 4 - Strings...................................................6
Chapter 5 - Arrays...................................................8
Chapter 6 - JavaScript in the browser....................11
Chapter 7: Walking the DOM................................13
Chapter 8 - Events & other DOM properties.........16
Chapter 9 - Callbacks, promises & async/await....20
Chapter 11 - Object Oriented Programming..........25
Chapter -12: Advanced Javascript.........................28
Questions/ Assignments:.......................................29
- += : x = x + y
- -= : x = x - y
- \= : x = x y
- /= : x = x / y
- %= : x = x % y
- \\= : x = x y

3. Comparison Operators
- `==` : equal to
- `!=` : not equal
- `===` : equal value and type
- `!==` : not equal value or not equal type
- `>` : greater than
- `<` : less than
Chapter 2 - Expressions & - `>=` : greater than or equal to
Conditionals - `<=` : less than or equal to
- `?` : ternary operator
A fragment of code that produces a value is called
an expression. Every value written literally is an
expression. For example, 77 or "Harry."
4. Logical Operators
- `&&` : logical and
Operators in JavaScript
- `||` : logical or
- `!` : logical not
1. Arithmetic Operators
- + : Addition
Apart from these, we also have type and bitwise
- - : Subtraction operators. Bitwise operators perform bit by bit
operations on numbers.
- : Multiplication
Example:
- \\ : Exponentiation
7 + 8 = 15
- / : Division
- % : Modulus
Comments in JavaScript
- ++ : Increment
Sometimes we want our programs to contain text
- -- : Decrement
which is not executed by the JS Engine.

2. Assignment Operators
Conditional Statements
-=:x=y
if-else if statement
Sometimes we might have to execute a block of
code based off some condition.
Sometimes we might want to keep checking a set
For example, a prompt might ask for the age of the of conditions one by one until one matches. We use
user and if it's greater than 18, display a special `if-else if` for achieving this.
message!

Syntax of if...else if looks like this


In Javascript we have three forms of if ... else
statement:
if (age > 0) {
1. `if ...` statement
console.log("A valid age");
2. `if ... else` statement
} else if (age >= 10 && age <= 15) {
3. `if ... else if ... else` statement
console.log("but you are a kid");
} else if (age >= 18) {
If statement
console.log("not a kid");
The `if` statement in JavaScript looks like this:
} else {
if (condition) {
console.log("Invalid Age");
// execute this code
}
}

JavaScript Ternary Operator


The `if` statement evaluates the condition inside the
parentheses. If the condition evaluates to `true`, the Evaluates a condition and executes a block of code
code inside the body of `if` is executed; otherwise, based on the condition.
the code is not executed.
condition ? exp1 : exp2

if-else statement
Example:
The `if` statement can have an optional `else`
clause. The syntax looks like this:
(marks > 10) ? "yes" : "no"

if (condition) {
// block of code if condition true If marks are greater than 10, you pass; otherwise,
you do not.
} else {
// block of code if condition false
}
If the condition is `true`, the code inside the `if`
block is executed; otherwise, the code inside the
`else` block is executed.
// code to be executed
}

- Statement 1 is executed one time


- Statement 2 is the condition based on which the
loop runs (loop body is executed)
- Statement 3 is executed every time the loop body
is executed

Quick Quiz: Write a sample for loop of your choice.


The for-in loop
The syntax of for-in loop looks like this:

Chapter 3 - Loops & Functions for (key in object) {


// code to be executed
We use loops to perform repeated actions. For }
example, if you are assigned a task of printing
numbers from 1 to 100, it will be very hectic to do it
manually. Loops help us automate such tasks.

Quick Quiz: Write a sample program demonstrating


Types of loops in JavaScript for-in loop

- for loop -> loops a block of code n number of Note: For-in loop also works with arrays which will
times be discussed in later videos.

- for in loop -> loops through the keys of an Object


- for of loop -> loops through the values of an The for-of loop
Object
The syntax of for-of loop looks like this:
- do while loop -> loops a block based on a specific
condition
for (variable of iterable) {
- do while loop -> while loop variant which runs at
least once // code to be executed
}
The for loop

Quick Quiz: Write a sample program demonstrating


for-of loop
The syntax of a for loop looks something like this:

The while loop


for (Initialization; Condition; Code Completion ) {
The syntax of while loop looks like this: }

while (condition) { function bindFunc(parameter1, parameter2) {


// code to be executed // code
} }

Note: If the condition never becomes false, the loop Function with parameters
will never end, and this might crash the runtime.

- Here the parameters behave as local variables

Quick Quiz: Write a sample program demonstrating


bindFunc (7, 8) -> Function Invocation
while loop.

Function invocation is a way to use the code inside


The do-while loop
the function.

The do-while loop's syntax looks like this:


A function can also return a value. The value is
"returned" back to the caller.
do {
// code to be executed const sum = (a, b) => {
} while (condition) let c = a + b;
return c; // Returns the Sum
- Executed at least once }

Quick Quiz: Write a sample program demonstrating Another way to create & use the function:
do-while loop

let y = sum(1, 3);


Functions in JavaScript
console.log(y); // Prints 4

A JavaScript function is a block of code designed to


perform a particular task.

Syntax of a function looks something like this:

function myFunc() {
// code
Chapter 4 - Strings
let name = 'Adam D'Angelo'
Strings are used to store and manipulate text.
Strings can be created using the following syntax:
We can use a single quote escape sequence to
solve the problem:
let name = "Harry" -> Creates a string
name.length let name = 'Adam D\'Angelo'
-> This property prints length of the string

Similarly, we can use `\"` inside a string with double


Strings can also be created using single quotes quotes.

let name = 'Harry' Other escape sequence characters are as follows:

Template Literals - `\n` → Newline

Template literals use backticks instead of quotes to - `\t` → Tab


define a string - `\r` → Carriage Return

let name = `Harry` String Properties and Methods

With template literals, it is possible to use both let name = "Harry"


single as well as double quotes inside a string
name.length → prints 5

let sentence = `The name is 'Harry'` -> single quote


let name = "Harry"
name.toUpperCase() → prints HARRY
We can insert variables directly in template literal.
This is called string interpolation
let name = "Harry"

let a = `This is ${name}` -> Prints This is Harry name.toLowerCase() → prints harry

Note: The handwritten note in red ink says, "Don't


forget the 's' letter". String Methods in JavaScript

Escape Sequence Characters // Slice method examples


If you try to print the following string, JavaScript will let name = "Harry";
misunderstand it:
name.slice(2, 4); // prints "rr" (from index 2 to 4, 4
not included)

let name = "Harry";


name.slice(2); // prints "rry" (from index 2 to end)

// Replace method example


let name = "Harry Bhai";
let newName = name.replace("Bhai", "Bhau");
// Replaces "Bhai" with "Bhau"

// Concat method example


let name1 = "Harry";
let name2 = "Naman";
let name3 = name1.concat(name2, " Yes");
// We can even use `+` operator for concatenation

// Trim method example


let name = " Harry ";
let newName = name.trim();
// Removes whitespaces from both ends

String Immutability and Character Access

Strings are immutable. In order to access the


characters at an index, we use the following syntax:

let name = "Harry";


name[0]; // Prints "H"
name[1]; // Prints "a"
Chapter 5 - Arrays Array methods
Arrays are variables which can hold more than one There are some important array methods in
value. JavaScript. Some of them are as follows:

const fruits = ["banana", "apple", "grapes"] 1. toString() → Converts an array to a string of


const a1 = [7, "Harry", false] comma-separated values

// can be different types let n = [1, 7, 9]


n.toString() → "1,7,9"

Accessing values
let numbers = [1, 2, 7, 9] 2. join() → Joins all the array elements using a
separator
numbers[0] = 1
let n = [7, 9, 13]
numbers[1] = 2
n.join(" - ") → "7-9-13"

Finding the length


let numbers = [1, 7, 9, 21]
3. pop() → Removes the last element from the
numbers[0] = 1 array
numbers.length = 4 let n = [1, 2, 4]
n.pop() → updates the original array, returns the
popped value
Changing the values
let numbers = [7, 2, 40, 9]
4. push() → Adds a new element at the end of the
numbers[2] = 8
array
➡️"numbers" now becomes [7, 2, 8, 9]
➡️Arrays are mutable
let a = [7, 1, 2, 8]
➡️Arrays can be changed
a.push(9) → modifies the original array
→ returns the new array length
In JavaScript, arrays are objects. The `typeof`
operator on arrays returns object
5. shift() → Removes the first element and returns it

const n = [1, 7, 9]
6. unshift() → Adds an element to the beginning.
typeof n → returns "object"
Returns new array length

Arrays can hold many values under a single name.


7. delete → Array elements can be deleted using
the `delete` operator
let d = [7, 8, 9, 10]
delete d[1] → delete is an operator - Returns deleted items, modifies the array
- position to add | no. of elements to remove |
elements to be added
8. concat() → Used to join arrays to the given array

11. slice() → Slices out a piece from an array. It


let a1 = [1, 2, 3]
creates a new array.
let a2 = [4, 5, 6]
let a3 = [9, 0, 7]
const num = [1, 2, 3, 4]
num.slice(2) → [3, 4]
a1.concat(a2, a3) → Returns [1, 2, 3, 4, 5, 6, 9, 0,
num.slice(1, 3) → [2, 3]
7]

12. reverse() -> Reverses the elements in the


→ Returns a new array
source array.
→ Does not change existing arrays

Looping through Arrays


9. Sort() → `sort()` method is used to sort an array
Arrays can be looped through using the classical
alphabetically.
JavaScript for loop or through some other methods
discussed below.

let a = [7, 9, 8]
a.sort() 1. forEach loop -> Calls a function once for each
array element.

→ `a` changes to `[7, 8, 9]`


const a = [1, 2, 3];
→ [modifies the original array]
a.forEach((value, index, array) => {
// function logic
`sort()` takes an optional compare function. If this
function is provided as the first argument, the });
`sort()` function will consider these values (the
values returned from the compare function) as the
basis of sorting. 2. map() -> Creates a new array by performing
some operation on each array element.

10. splice() → `splice` can be used to add new


items to an array const a = [1, 2, 3];
a.map((value, index, array) => {
return value + value;
const numbers = [1, 2, 3, 4, 5] });
numbers.splice(2, 1, 23, 24)
3. filter() -> Filters an array with values that pass a
test. Creates a new array.

const a = [1, 2, 3, 4, 5];


a.filter(greater-than-5);

4. reduce method -> Reduces an array to a single


value.
const numbers = [1, 8, 7, 1];
let sum = numbers.reduce(add);
// Result: 1 + 8 + 7 + 1 = 17

5. Array.from -> Used to create an array from any


other object.

Array.from("Harry");

6. for...of -> For-of loop can be used to get the


values from an array.

for (const value of array) {


// loop logic
}

7. for...in -> For-in loop can be used to get the keys


from an array.
for (const key in array) {
// loop logic
}
Chapter 6 - JavaScript in the
browser <script src="/js/myscript.js"></script>

JavaScript was initially created to make web pages


The benefit of a separate JavaScript file is that the
alive. JS can be written right in a web page's HTML
browser will download it and store it in its cache.
to make it interactive.
The browser has an embedded engine called the
JavaScript engine or the JavaScript runtime. Console object methods
The console object has several methods, log being
one of them. Some of them are as follows:
JavaScript's ability in the browser is very limited to
protect the user's safety. For example, a webpage
on http://google.com cannot access
http://codesweet.com and steal information from assert() → Used to assert a condition
there. clear() → Clears the console
log() → Outputs a message to the console
Developer tools table() → Displays tabular data
Every browser has some developer tools which warn() → Used for warnings
makes a developer's life a lot easier.
error() → Used for errors
F12 on chrome opens Dev tools
info() → Used for special information
| Elements | Console | Network |
| All HTML elements | All the errors & logs | All
network requests | You will naturally remember some or all of these
with time. A comprehensive list can be looked up
on MDN.
We can also write JavaScript commands in the
console.
Interaction: alert, prompt and confirm

The script tag


alert: Used to invoke a mini window with a
The script tag is used to insert JavaScript into an message.
HTML page.
alert("hello")
The script tag can be used to insert external or
internal scripts
prompt: Used to take user input as a string.

<script> inp = prompt("Hi", "No")

alert("Hello") ^ optional default value

</script>
confirm: Shows a message and waits for the user
to press OK or Cancel. Returns `true` for OK and
Or html `false` for Cancel.
The exact location & look is determined by the
browser, which is a limitation.

Window object BOM & DOM

We have the following when JavaScript runs in a


browser:

Window
|-- DOM
|-- BOM
|-- JavaScript Core

Window object represents the browser window and


provides methods to control it. It is a global object.

Document Object Model (DOM)

DOM represents the page content as HTML

`document.body` → Page body as a JS object


`document.body.style.background = "green"` →
changes page background to green

Browser Object Model (BOM)

The Browser Object Model (BOM) represents


additional objects provided by the browser (host
environment) for working with everything except the
document.

The functions `alert`, `confirm`, and `prompt` are


also a part of the BOM
`location.href = "https://codewithharry.com"` →
Redirects to another URL
Chapter 7: Walking the DOM
Children of an element
DOM tree refers to the HTML page where all nodes Direct as well as deeply nested elements of an
are objects. There can be 3 main types of nodes in element are called its children.
the DOM tree:
1. text nodes
Child nodes -> Elements that are direct children.
2. element nodes For example head & body are children of <html>.
3. comment nodes

Descendant nodes -> All nested elements,


In an HTML page, `<html>` is at the root and children, their children and so on...
`<head>` and `<body>` are its children, etc.

firstChild, lastChild & childNodes


A text node is always a leaf of the tree.

.firstChild -> first child node


Auto Correction .lastChild -> last child node
If an erroneous HTML is encountered by the .childNodes -> All child nodes
browser, it tends to correct it. For example, if we
put something after the body, it is automatically
moved inside the body. Another example is Following is always true:
`<table>` tag which must contain `<tbody>`.

.childNodes[0] === elem.firstChild


Walking the DOM
.childNodes[elem.childNodes.length - 1]
<html> === .lastChild
<head>
<title>hello</title> There is also a method .hasChildNodes() to check
</head> whether there are any child nodes.

<body>
</body> Note: childNodes looks like an array. But it is not
actually an array but a collection. We can use
</html> Array.from(Collection) to convert it into an Array.
Array methods won't work.

`document.body` -> Page Body tag


`document` -> `document.documentElement` Notes on DOM collections

`document.head` -> more children -> Page HTML - They are read-only
tag - They are live: `.childNodes` variable (reference)
Note: document.body can sometimes be null if the will automatically update if childNodes of elem is
JavaScript is written before the body tag. changed.
- They are iterable using `for...of` loop Table links

Siblings and the parent Certain DOM elements may provide additional
properties specific to their type for convenience.
Siblings are nodes that are children of the same
Table element supports the following properties:
parent.

table.rows → collection of <tr> elements


→ For example `<head>` and `<body>` are
siblings. Siblings have the same parent. In the
above example it's `<html>`.
table.caption → reference to <caption>

→ `<body>` is said to be the "next" or "right" sibling


table.tHead → reference to <thead>
of `<head>`. `<head>` is said to be the "previous"
or "left" sibling of `<body>`.

table.tFoot → reference to <tfoot>


→ The next sibling is in `nextSibling` property, and
the previous one in `previousSibling`.
table.tBodies → collection of <tbody> elements
The parent is available as `parentNode`.

tbody.rows → collection of <tr> inside


alert(document.documentElement.parentNode); //
document
alert(document.documentElement.parentElement); tr.cells → collection of <td> and <th>
// null

tr.sectionRowIndex → index of <tr> inside


Element Only Navigation enclosing element

Sometimes, we don't want text or comment nodes.


Some links only take Element nodes into account. tr.rowIndex → row number starting from 0
For example:

td.cellIndex → number of cells inside enclosing <tr>


document.previousElementSibling // Previous
sibling which is an Element
Quick Quiz: Print typeof document and typeof
window in the console & see what it prints
document.nextElementSibling → next sibling
(Element)
Searching the DOM - Navigation

document.firstElementChild → first Element child


DOM navigation properties are helpful when the
elements are close to each other. If they are not
document.lastElementChild → last Element child close to each other, we have some more methods
to search the DOM.
→ document.getElementById Matches, Closest & Contains methods
This method is used to get the element with a given
"id" attribute.
elem.matches(css)
let span = document.getElementById("span");
To check if an element matches the given CSS
span.style.color = "red"; selector.

Returns HTML Element or Null elem.closest(css)


To look for the nearest ancestor that matches the
given CSS selector. The element itself is also
→ document.querySelectorAll
checked.
Returns all elements inside an element matching
the given CSS selector.
elemA.contains(elemB)
Returns true if `elemB` is inside `elemA` (a
Returns HTML collection /// NO returns sort of array
descendant of `elemA`) or when `elemA == elemB`.
with all elements matching that close ntoe one
element which can be accessed
When HTML collection is returned, it is not an
object or an array, rather it much behaves like an
→ document.querySelector
array. You will need to store this reference in a
Returns the first element for the given CSS variable separately to access the index of
selector. A more efficient version of collection.
elem.querySelectorAll(CSS)[0]

const name = document.getElementbyId(“h4)


Returns HTML Element or Null
name[0].style.title/(properties of document (object)
in the browser.

→ document.getElementsByTagName
Returns elements with the given tag name.

→ document.getElementsByClassName
Returns elements that have the given CSS class.

Note: There is a handwritten note in red ink next to


`document.getElementsByName` that says, "Don't
forget the 's' letter".

→ document.getElementsByName
Searches elements by the name attribute.
Chapter 8 - Events & other <script>

DOM properties. element.hidden = true;


</script>
Console: `dir` function
- `console.log` shows the element DOM tree.
Attribute methods
- `console.dir` shows the element as an object with
its properties.
1. .hasAttribute(name) -> Method to check for
existence of an attribute
`tagName` / `nodeName`
- Used to read the tag name of an element.
2..getAttribute(name) -> Method used to get the
- `tagName` -> Only exists for Element nodes. value of an attribute

- `nodeName` -> Defined for any node (text,


comment, etc.).
3..setAttribute(name, value) -> Method used to set
the value of an attribute

`innerHTML` and `outerHTML`


- The `innerHTML` property allows getting the 4..removeAttribute(name) -> Method to remove the
HTML inside the element as a string. attribute from elem

- Valid for element nodes only.


- The `outerHTML` property contains the full HTML: 5..attributes -> Method to get the collection of all
`innerHTML` + the element itself. attributes

- `innerHTML` is valid only for element nodes; for


other node types, we can use `nodeValue` or
Data- Attributes
`data`.

We can always create custom attributes but the


`textContent`
ones starting with data- are reserved for
- Provides access to the text inside the element— programmers use. They are available in a property
only text, minus all tags. named dataset.

The `hidden` property If an element has an attribute named "data-on", it's


available as element.dataset.one
- The `"hidden"` attribute and the DOM property
specify whether the element is visible or not.
Insertion methods

<div hidden> I am hidden </div>


We looked at some ways to insert elements in the
DOM. Here is another way:
<div id="element"> I can be hidden </div>
let div = document.createElement('div') // create <div id="div"></div>
<script>
div.className = "alert" // set class div.insertAdjacentHTML("beforebegin", "<p> Hello
</p>");
div.insertAdjacentHTML("afterend", "<p> Bye
div.innerHTML = "<span>hello</span>"
</p>");
</script>
document.body.append(div)

The output:
Here are some more insertion methods:
<p> Hello </p>
<div id="div"></div>
1. node.append(e) -> append at the end of node
<p> Bye </p>
2. node.prepend(e) -> insert at the beginning of
node
Node removal
3. node.before(e) -> insert before node
4. node.after(e) -> insert after node
To remove a node, there's a method node.remove()
5. node.replaceWith(e) -> replaces node with the
given node
let id1 = document.getElementById("id1")
Quick Quiz: Try out all these methods with your
own webpage.
id1.remove()

Insert Adjacent HTML/Text or Elements


ClassName and ClassList

This method has two parameters:


If we assign something to elem.className, it
1. position - Four possible values: replaces the whole string of classes.
"beforebegin" - insert HTML immediately before
the element.
Often we want to add/remove/toggle a single class.
"afterbegin" - insert HTML into the element, at
the beginning.
1. elem.classList.add/remove("class") -
"beforeend" - insert HTML into the element, at
Adds/removes a class
the end.
"afterend" - insert HTML immediately after the
element. 2. elem.classList.toggle("class") - Adds the class if
it doesn't exist, otherwise removes it
2. HTML string

Example:
3. elem.classList.contains("class") - Checks for the An event is a signal that something has happened.
given class, returns true/false All the DOM nodes generate such signals.

SetTimeout and setInterval Some important DOM events are:

SetTimeout allows us to run a function once after Mouse events: click, contextmenu (right click),
the interval of time. mouseover, mouseout, mousedown/mouseup,
mousemove
Syntax of setTimeout is as follows:

Keyboard events: keydown and keyup


let timerId = setTimeout(function, <delay>, <arg1>,
<arg2>) form element events: Submit, focus etc.
- returns a timerId
- in ms/ sec e.g 1 and that can be saved in variable Document events: DOMContentLoaded
such as timerId above. And then used in
clearTimeout(timerID)
Handling Events

clearTimeout is used to cancel the execution


(incase we change our mind). For example: Events can be handled through HTML attributes

let timerId = setTimeout(() => alert("never"), 1000); <input value = "Hey" onclick = "alert('Hey')" type =
"button">

clearTimeout(timerId); // cancel the execution


can be another JS function

setInterval method has a similar syntax as


setTimeout: Events can also be handled through the onclick
property

let timerId = setInterval(function <delay> <any


arguments>); elem.onclick = function() {
alert("yes")
All arguments have the same meaning. But unlike }
setTimeout, it runs the function not only once, but
regularly after the given interval of time.
Note: Adding a handler with JavaScript overwrites
the existing handler
To stop further calls, we can use
clearInterval(timerId);
addEventListener and removeEventListener

Browser Events
addEventListener is used to assign multiple
handlers to an event.

element.addEventListener(event, handler)

element.removeEventListener(event, handler)

handler must be the same function object for this to


work

The Event Object

When an event happens, the browser creates an


event object, puts details into it and passes it as an
argument to the handler.

elem.onclick = function (event) {


...
}

event.type : Event type


event.currentTarget : Element that handled the
event
event.clientX / event.clientY : Coordinates of the
cursor
Chapter 9 - Callbacks, loadScript((...) =>

promises & async/await loadScript(...) =>


loadScript(...) =>
Asynchronous actions are the actions that we
loadScript(...) =>
initiate now and they finish later. eg. setTimeout
loadScript(...)
Synchronous actions are the actions that initiate
and finish one-by-one.

As calls become more nested, the code becomes


deeper and increasingly more difficult to manage,
Callback functions
especially if we have real code instead of "...". This
A callback function is a function passed into is sometimes called "callback hell" or "pyramid of
another function as an argument which is then doom."
invoked inside the outer function to complete an
action.
The 'pyramid' of these calls grows towards the right
with every asynchronous action. Soon it spirals out
Here is an example of a callback: of control. So this way of coding isn't very good!

function loadScript(src, callback) { Introduction to Promises

let script = document.createElement('script');


script.src = src; The solution to the callback hell is promises. A
promise is a "promise of code execution." The code
script.onload = () => callback(script); either executes or fails; in both cases, the
document.head.append(script); subscriber will be notified.

}
The syntax of a Promise looks like this:

Now we can do something like this: let promise = new Promise (function (resolve,
reject) {
// executor
loadScript('https://cdn.harry.com', (script) => {
});
alert('Script is loaded');
alert(script.src);
resolve and reject are two callbacks provided by
}); JavaScript itself. They are called like this:
resolve (value) -> If the job is finished successfully
Pyramid of Doom reject (error) -> If the job fails

When we have callback inside callbacks, the code The promise object returned by the new Promise
gets difficult to manage: constructor has these properties:
1. state: Initially pending then changes to either Promises Chaining
"fulfilled" when resolve is called or "rejected" when
We can chain promises and make them pass the
reject is called
resolved values to one another like this:

2. result: Initially undefined then changes to value if


p.then (function (result) => {
resolved or error when rejected
alert (result); return 2;
}).then ...
Consumers: then & catch
The consuming code can receive the final result of
a promise through then & catch. The idea is to pass the result through the chain
of .then handlers.

The most fundamental one is then


Here is the flow of execution
promise.then (function (result) { / handle / },
function (error) { / handle error / });

1. The initial promise resolves in 1 second


(Assumption). The next .then() handler is then
If we are interested only in successful completions,
called, which returns a new promise (resolved with
we can provide only one function argument to
a value).
`.then()`:
2. The next .then() gets the result of previous one
and this keeps on going.
let promise = new Promise (resolve => {
setTimeout (() => resolve (\"done\"), 1000);
Every call to .then() returns a new promise whose
}); value is passed to the next one and so on. We can
even create custom promises inside .then().

promise.then (alert);
Attaching multiple handlers

If we are interested only in errors, we can use `null`


as the first argument: `.then(null, f)` or we can use We can attach multiple handlers to one promise.
`.catch()`: They don't pass the result to each other; instead
they process it independently.

promise.catch (alert);
let p is a promise

`promise.finally (() => {...})` is used to perform


general cleanups. p.then(handler1)
p.then(handler2) -> Runs Independently
Quick Quiz: Rewrite the `loadScript` function we p.then(handler3)
wrote in the beginning of this chapter using
promises.
There are 6 static methods of Promise class: }

1. Promise.all(promises) -> Waits for all promises An async function always returns a promise. Other
to resolve and returns the array of their results. If values are wrapped in a promise automatically.
any one fails, it becomes the error & all other
results are ignored.
We can do something like this:

2. Promise.allSettled(promises) -> Waits for all the


promises to settle and returns their results as an harry().then(alert)
array of objects with status and value.

So, async ensures that the function returns a


3. Promise.race(promises) -> Waits for the first promise and wraps non promises in it.
promise to settle and its result/error becomes the
outcome.
The Await Keyword

4. Promise.any(promises) -> Waits for the first


promise to fulfill (not rejected), and its result There is another keyword called await that works
becomes the outcome. Throws Aggregate Error if only inside async functions
all the promises are rejected.

let value = await promise;


5. Promise.resolve(value) -> Makes a resolved
promise with the given value.
The await keyword makes Javascript wait until the
promise settles and returns its value.
6. Promise.reject(error) -> Makes a rejected
promise with the given error.
Its just a more elegant syntax of getting the promise
result than promise.then + its easier to read & write
Quick Quiz: Try all these promise APIs on your
custom promises.
Error Handling

Async/Await
We all make mistakes. Also sometimes our script
can have errors. Usually a program halts when an
There is a special syntax to work with promises in error occurs.
Javascript

The try...catch syntax allows us to catch errors so


A function can be made async by using async that the script instead of dying can do something
keyword like this: more reasonable

async function harry() { The try...catch syntax


return 7;
the try...catch construct.
The try...catch syntax has two main blocks: try and
then catch
The Error Object
For all the built in errors, the error object has
try {
two main properties:
// try the code
}
try {
hey!! error variable not defined
catch (err) {
} catch (err) {
// error handling
alert(err.name)
}
alert(err.message)
alert(err.stack)
=> The err variable contains an error object
}

It works like this


Throwing Custom Error
1. First the code in try is executed
We can throw our own error by using the throw
2. If there is no error, catch is ignored else is syntax
executed

if (age > 180) & throw new Error ("Invalid Age")


try...catch works synchronously.
...
If an exception happens in scheduled code,
like in setTimeout, then try...catch won't
We can also throw a particular error by using the
catch it. built-in constructor for standard errors:

try { let error = new SyntaxError (message) or new


ReferenceError (message)
setTimeout(function() {
// error code -> script dies and
The finally clause
}); catch won't work
} catch (e) {
The try...catch construct may have one more code
...
clause: finally
}

If it exists it runs in all cases:


That's because the function itself is executed
after try if there were no errors after catch if there
later, when the engine has already left were errors
If there is a return in try, finally is executed just
before the control returns to the outer code.
Chapter 11 - Object Oriented
Programming Classes and Objects
In object-oriented programming, a class is an
In programming we often take something and then extensible program-code template for creating
extend it. For example, we might want to create a objects, providing initial values for state (member
user object and "admin" and "guest" will be slightly variables), and implementation of behavior
modified variants of it. (member functions).

Prototype The basic syntax for writing a class is:

JavaScript objects have a special property called Class MyClass {


prototype that is either null or references another
// class methods
object.
constructor() { ... }
method1() { ... }
[Diagram]
method2() { ... }
}
prototype object

We can then use new MyClass() to create a new
[[Prototype]]
object with all the listed methods.

Object
The Constructor Method
The constructor() method is called automatically by
When we try to read a property from a prototype new, so we can initialize the object there.
and it's missing, JavaScript automatically takes it
from the prototype. This is called "prototypal
inheritance". Quick Quiz: Create a class user and create a few
methods along with a constructor.

Setting Prototype
Class myClass {
Constructor (){}
We can set prototype by setting __proto__. Now if
we read a property from the object which is not in }
the object and is present in the prototype,
JavaScript will take it from the prototype.
Class Inheritance

If we have a method in the object it will be called Class inheritance is a way for one class to extend
from the object. If it's missing in the object and another class. This is done by using the extends
present in the prototype, it's called from the keyword.
prototype.
The Extends keyword
run() {
The extends keyword is used to extend another super.run()
class.
this.hide()
}
Class Lion extends Animal {}

Overriding Constructor
Class Child extends Parent
With a constructor, things are a bit tricky/different.
According to the specifications, if a class extends
another class and has no constructor, then the
We can create a class Monkey that inherits from
following empty constructor is generated.
Animal

Class Monkey extends Animal {


Class Monkey extends Animal {
// auto generated
hide() {
Constructor(...args) {
alert(`${this.name} hides!`);
super(...args)
}
}
}
}

let monkey = new Monkey("Monu")


=> Happens if we don't write our own constructor
monkey.run(2); // from Animal
monkey.hide();
Constructors in inheriting classes must call
super(...) and do it before using this.
Method Overriding

We can also use super.method() in a Child method


If we create our own implementation of run, it will to call Parent Method
not be taken from the Animal class. This is called
Method Overriding.
Static Method
Static methods are used to implement functions
Super Keyword
that belong to a class as a whole and not to any
particular object.

When we override a method, we don't want the


method of the previous class to go in vain. We can
We can assign a static method as follows:
execute it using super keyword.

Class Employee {
Super(a, b) -> call parent constructor
static sMethod() {
alert("Hey");
}
}

Employee.sMethod();

Static methods aren't available for individual


objects.

Getters and Setters


Classes may include getters and setters to get &
set the computed properties.

Example:

Class Person {
get (name) {
return this._name;
}

set name(newName) {
this._name = newName;
}
}

instanceof Operator
The instanceof operator allows to check whether an
object belongs to a certain class.

The syntax is:

<obj> instanceof <class>

It returns true if obj belongs to the class or any


other class inheriting from it.
Chapter -12: Advanced Spread syntax allows an iterable such as an array or
string to be expanded in places where zero or more
Javascript arguments are expected. In an object literal, the
spread syntax enumerates the properties of an object
There are some JavaScript concepts which make the and adds the key-value pairs to the object being
life of a developer extremely simple. We will created.
discuss some of these in this chapter.
Example:
IIFE
IIFE is a JavaScript function that runs as soon as it javascript
is defined. const arr = [1, 7, 11];
const obj = { ...arr }; // { 0: 1, 1: 7, 2: 11 }
javascript
(function () { const nums = [1, 2, 7];
... console.log(sum(...nums)); // 10
})();

Other examples can be found on MDN docs.


IIFE Syntax
Quick Quiz: Output of the following:
It is used to avoid polluting the global namespace, javascript
execute an asyncawait, etc. const a = "hi", b = "no";
const c = {a, b};
Destructuring console.log(c); // { a: "hi", b: "no" }
Destructuring assignment is used to unpack values
from an array or properties from objects into Local, Global & Block Scopes
distinct variables.
JavaScript has three types of scopes:
javascript
let [x, y] = [7, 20] 1. Block Scope
2. Function Scope
x will be assigned 7 and y, 20 3. Global Scope
[10, x, ...rest] = [10, 80, 7, 11, 21, 88] let & const provide blocklevel scope, which means
that the variables declared inside {} cannot be
x will be 80 rest will be [7, 11, 21, 88] accessed from outside the block:
Similarly, we can destructure objects on the left- javascript
hand side of the assignment. {
let a = 27;
javascript }
const obj = { a: 1, b: 2 }; // a is not available here
const {a, b} = obj;

Variables declared within a JavaScript function


Some more examples can be found on the MDN become local to the function. A variable declared
docs. outside a function becomes global.
Spread Syntax Hoisting
Hoisting refers to the process whereby the
interpreter appears to move the declarations to the
top of the code before execution. This means
variables can be referenced before they are declared
in JavaScript. Questions/ Assignments:
hello("Harry")
Exercise 1 - Guess the Number
function hello_name() {
... Write a JavaScript program to generate a random
} number and store it in a variable. The program then
takes an input from the user to tell them whether the
Important Note: JavaScript only hoists guess was correct, greater or lesser than the original
declarations, not initializations. The variable will be number.
undefined until the line where it is initialized is 100 - 2 (no of guesses) is the score of the user.
reached. The program is expected to terminate once the
number is guessed.
Hoisting with let and var: Number should be between 1 - 100.

With let and var hoisting is different Exercise 2 - Snake Water Gun

console.log(num) => Error if let or const Use JavaScript to create a game of Snake Water &
let num = 6; => With var undefined is printed Gun. The game should ask you to enter S, W or G.
The computer should be able to randomly generate
Function expressions and class expressions are not S, W or G and declare win or loss using alert. Use
hoisted. confirm and prompt wherever required.

Exercise 3 - Tell me a Joke

elem.innerHTML is used to populate a div with


HTML. Search online about this method and create
a website with a div tag containing a random joke
given an array of jokes. Use Math.random (and
fetch jokes from the internet (use any website to
create the array)). Your website should show a
random joke on every reload. Min length of your
jokes array should be 10.

Exercise 4 - Digital Clock

Create a Digital Seconds clock using setInterval and


Date object in JavaScript.
The Date object can be used to get the date, time,
hours, and seconds which can then be updated using
setInterval.
Try to keep the UI good looking.

Exercise 5 - Hackermon
Write a JavaScript program to pretend to look like a
hacker. Write an async function which will simply
display the following output:

Initializing Hack program . . .


Hacking Ashish's username . . .
Username found aashish17 . . .
Connecting to Facebook . . .

Try to use HTML & styling if possible.

Exercise 6 - TODO List

Create a TODO List app capable of storing your


TODOs in localStorage. Add an option to create,
delete, and access all the TODOs.

Try to make UI as good as possible.

Exercise 7 - Password Generator

Create a JavaScript program capable of generating a


password which contains at least one lowercase
letter, one uppercase letter, and one special
character. Create a Password class to achieve the
same.

Exercise 8 - Alarm Clock

The HTML AudioElement interface can be used to


play audio in the browser. Create an alarm clock
that displays time and plays sound at a user-
specified time.

You might also like