JavaScript Notes
JavaScript Notes
Automatically
Using const
x = 5;
var x = 5;
let x = 5;
const x = 5;
Don't use underscores at the start of variable names — this is used in certain
JavaScript constructs to mean specific things, so may get confusing.
Don't use numbers at the start of variables. This isn't allowed and causes an error.
JavaScript 1
One last point: you also need to avoid using JavaScript reserved words as your
variable names — by this, we mean the words that make up the actual syntax of
JavaScript! So, you can't use words like var , function , let , and for as variable names.
Browsers recognize them as different code items, and so you'll get errors.
let x = 5;
console.log(typeof x);
All primitive types, except null , can be tested by the typeof operator. typeof
null returns "object" , so one has to use === null to test for null .
JavaScript 2
- Subtraction += x += y x=x+y
* Multiplication -= x -= y x=x-y
/ Division /= x /= y x=x/y
-- Decrement
? ternary operator
Ternary Operators
If else conditionals
The "if" statement in JavaScript is used to execute a block of code if a certain condition is
met. The "else" clause is used to execute a block of code if the condition is not met.
if (condition) {
// code to be executed if condition is true
} else {
JavaScript 3
// code to be executed if condition is false
}
For-in loop
The for-in loop is used to iterate over the properties of an object. It has the following
syntax:
The variable is assigned the name of each property in the object as the loop iterates over
them.
Here's an example of a for-in loop that iterates over the properties of an object:
let person = {
name: "John",
age: 30,
job: "developer"
};
JavaScript 4
console.log(key + ": " + person[key]);
}
name: John
age: 30
job: developer
For-of loop
The for-of loop is used to iterate over the values of an iterable object, such as an array or a
string. It has the following syntax:
The variable is assigned the value of each element in the object as the loop iterates over
them.
Here's an example of a for-of loop that iterates over the elements of an array:
function greet() {
console.log("Hello World!");
}
JavaScript 5
Function Call
greet();
Note: Arrow functions were introduced in ES6. Some browsers may not support the use of
arrow functions.
arrow function with parameters .
JavaScript 6
Chapter 4 - Strings & its Methods
A JavaScript string is zero or more characters written inside quotes.
Template Strings
Templates were introduced with ES6 (JavaScript 2016).
Templates are strings enclosed in backticks (`This is a template string`).
Escape Characters
Because strings must be written within quotes, JavaScript will misunderstand this string:
let text = "We are the so-called "Vikings" from the north.";
\\ \ Backslash
JavaScript 7
Methods
The length property returns the length of a string:
The at() method returns the character at a specified index (position) in a string.
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: start position, and end position (end not included).
split() take an argument and give us two strings one from the left of argument , and one
from the right of argument . we can use 0 for choosing the left string , and 1 for choosing
the right part .
// slice
let text = "Apple, Banana, Kiwi";
let part = text.slice(7, 13);
// split
let a "let_her_go-song";
let b = a.split("-")[0];
// output - let_her_go
let c = a.split("-")[1];
// output - song
JavaScript 8
concat() joins two or more strings:
The replace() method replaces a specified value with another value in a string:
the replaceAll() method replace all values with another value , its syntax is same as
replace .
JavaScript 9
let courses = ["HTML", "CSS", "Javascript", "React"];
courses[1]= "Bootstrap";
Array Length
Get the length of an array using the length property.
JavaScript 10
let courses = ["HTML", "CSS", "Javascript", "React", "Node.js"];
let len = courses.length;
Array Concatenation
Combine two or more arrays using the concat() method. Ir returns new array conaining
joined arrays elements.
It behaves just like toString() , but in addition you can specify the separator:
sorting an Array
JavaScript 11
The sort() method sorts an array alphabetically:
Reversing an Array
The reverse() method reverses the elements in an array:
JavaScript 12
The filter() method creates a new array with array elements that pass a test.
This example creates a new array from elements with a value larger than 2:
JavaScript Array.from()
The Array.from() method returns an Array object from any object with a length property or
any iterable object.
JavaScript 13
Chapter 7 - DOM & User Interaction
DOM Nodes
According to the W3C HTML DOM standard, everything in an HTML document is a node:
With the HTML DOM, all nodes in the node tree can be accessed by JavaScript.
New nodes can be created, and all nodes can be modified or deleted.
Node Relationships
The nodes in the node tree have a hierarchical relationship to each other.
The terms parent, child, and sibling are used to describe the relationships.
In a node tree, the top node is called the root (or root node)
Every node has exactly one parent, except the root (which has no parent)
parentNode
JavaScript 14
childNodes[ nodenumber ]
firstChild
lastChild
nextSibling
previousSibling
alert('HI there');
The text is basically what you want to show the user and the default value argument is
optional though it acts like a placeholder inside a text field. It is the most used interface as
with it you can ask the user to input something and then use that input to build something.
JavaScript 15
The confirm function basically outputs a modal window with a question and two buttons
‘OK’ and ‘CANCEL’.
<div id="myDiv">
<p>This is my paragraph</p>
<p>This is my paragraph</p>
</div>
outerHTML
The outerHTML property is a part of the JavaScript HTMLElement object and it allows
developers to access and manipulate the entire HTML of an element, including the
element's own tags.
The main difference between outerHTML and innerHTML is that outerHTML allows you to
change the entire element, including its own tags, whereas innerHTML only allows you to
change the content within the element .The outerHTML property returns the entire HTML of
an element, as a string of HTML .
For example, consider the following HTML code:
JavaScript 16
<div id="myDiv">
<p>This is my paragraph</p>
<p>This is my paragraph</p>
</div>
getElementsById
One of the most commonly used methods of the document object is
the getElementById() method. This method allows developers to access a specific element
on the web page by its unique ID . The getElementById() method is a convenient way to
access a specific element on a web page, as it saves developers from having to traverse
the entire DOM tree to find the element. This method is especially useful when working
with large and complex web pages, as it allows developers to quickly and easily access the
elements they need.
For example, consider the following HTML code:
getElementsByClassName
This method is a part of the JavaScript document object and it allows developers to access
multiple elements on a web page by their class name. This method returns a live
HTMLCollection of elements with the given class name, or an empty HTMLCollection if no
such elements are found . This method is especially useful when working with large and
complex web pages, as it allows developers to quickly and easily access multiple elements
that share the same class name.
For example, consider the following HTML code :
JavaScript 17
<div class="myClass">This is my div</div>
getElementsByTagName
The getElementsByTagName() method is a part of the JavaScript document object and it allows
developers to access multiple elements on a web page by their HTML tag name. This
method returns a live HTMLCollection of elements with the given tag name, or an empty
HTMLCollection if no such elements are found.
For example, consider the following HTML code:
<p>This is my paragraph</p>
<p>This is my paragraph</p>
<p>This is my paragraph</p>
querySelector()
The querySelector() is a method used for searching and returning the very first
element within the document that matches the given selector. The queryselector in
javascript only returns the element that matches with one of the specified CSS selectors,
or a group of selectors. However, if no matches are found, it returns null.
document.querySelector(".box2").style.backgroundColor = "green";
querySelectorAll()
Since querySelector() in javascript returns only a single element, the additional
querySelectorAll() method can be used in situations where you need to get all matching
JavaScript 18
selector elements in the document.
document.querySelectorAll(".box").forEach((e) => {
e.style.backgroundColor = "yellow";
});
<div class="container">
<div style="border: 2px solid black" class="box"></div>
</div>
<script>
let e = document.querySelector(".box");
e.hasAttribute("style");
// true
e.hasAttribute("id");
// false
e.getAttribute("style");
JavaScript 19
// 'border: 2px solid black'
e.removeAttribute("style");
// style will be removed
e.setAttribute("id", "hero");
// id has been setted
e.attributes;
// NamedNodeMap {0: class, 1: id, 2: style, class: class, id:
id, style: style, length: 3}
</script>
Append Methods
Sure. All attributes are accessible by using the following methods:
<div class="container">
<div class="box">box 1</div>
<div class="box">box 2</div>
</div>
<script>
// adding elements to html page
let div = document.createElement("div");
div.innerHTML = "box 3";
JavaScript 20
div.setAttribute("class", "box");
let cont = document.querySelector(".container");
cont.append(div);
</script>
<div>
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
const elmnt = document.getElementById("p1"); elmnt.remove();
</script>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);
const parent = document.getElementById("div1");
const child = document.getElementById("p1");
parent.replaceChild(para, child);
</script>
JavaScript 21
Legal positions:
Value Description
const h2 = document.getElementById("myH2");
let html = "<p>My new paragraph.</p>";
h2.insertAdjacentHTML("afterend", html);
el.className = "new-class";
Property -
newClass: Here, you need to add the new class name inside double quotes. We can
also add multiple class names by giving space after each new class name.
classList Property?
The Classlist in JavaScript property allows you to powerfully manipulate the classes(the
group of HTML elements) attached to an HTML Element. You might have seen the like
button on many websites where you click on the like button it shows thumbs up otherwise
thumbs down, it is known as the toggle effect. To do so we have to change the class name
of the element and it can be done using the classList toggle method. You can also use
JavaScript classList property to add, remove, toggle, check if an element has a specified
class, and even replace classes on an element.
JavaScript 22
element.classList
The element here is an HTML element that has a class and to get the name of the
class .classList is used.
Toggle a Class
The toggle() method removes the CSS class from the class list of the element if the
specified CSS class is present, if the specified CSS class is not present then it adds the
CSS class.
element.classList.toggle('classname')
Suppose we created a website that has a switch to change the theme of the page. To do
that we will use the toggle method where if the entered class is not present in the element
then it will add the light-theme class entered in the toggle method. In the following
example, we are using the toggle() method to toggle for the division CSS class from the
element id section1.
setTimeout(() => {
alert("error");
}, 5000);
JavaScript 23
myVar = setTimeout(function, milliseconds);
clearTimeout(myVar);
If the function has not already been executed, you can stop the execution by calling
the clearTimeout() method:
The second parameter indicates the length of the time-interval between each execution.
setInterval(() => {
let x = Math.floor(Math.random() * 255 + 1);
let y = Math.floor(Math.random() * 255 + 1);
let z = Math.floor(Math.random() * 255 + 1);
document.body.style.backgroundColor = `rgb(${x},${y},${z})`;
}, 5000);
JavaScript 24
element.addEventListener(event, function);
The first parameter is the type of the event (like " click " or " mousedown " or any other HTML
DOM Event.)
The second parameter is the function we want to call when the event occurs.
// Example
let button = document.querySelector("#btn");
button.addEventListener("click", () => {
let inner = document.querySelector(".box");
inner.innerHTML = "bye bye";
});
Note that you don't use the "on" prefix for the event; use " click " instead of " onclick ".
element.removeEventListener("mousemove", myFunction);
Mouse Events
Event Occurs When
JavaScript 25
Clipboard Events
Attribute Value Description
oncut script Fires when the user cuts the content of an element
function sum(a, b) {
console.log(a + b)
}
function operation(val1, val2, callback) {
callback(val1, val2)
}
operation(6, 5, sum)
Output : 11
In the above code, we can see in the function operation the third parameter is a callback
function. We are first passing the "callback" as an argument and then calling it inside the
parent function 𝑖.𝑒.i.e., operation. Here, we have taken the "sum" as the callback function,
we can create any function and pass it as the callback in the operation function.
The next set of following tasks will only be addressed once the current task gets
finished. Thereby following a sequential code execution.
JavaScript 26
console.log('Start')
function divide(a, b) {
console.log(a / b)
}
function operation(val1, val2, callback) {
callback(val1, val2)
}
operation(16, 4, divide)
console.log('End')
Output :
Start
4
End
console.log('Start')
setTimeout(() => {
console.log('We are in the setTimeout()')
}, 4000)
console.log('End')
Output :
Start
End
We are in the setTimeout()
The execution of this code is different than what we are used to(synchronous).
Callback Hell
The phenomenon which happens when we nest multiple callbacks within a function is
called a callback hell. The shape of the resulting code structure resembles a pyramid and
hence callback hell is also called the “pyramid of the doom”. It makes the code very
difficult to understand and maintain. It is most frequently seen while working with Node.js.
The code below shows an example of a callback hell.
JavaScript 27
Promises
A promise is an object with a syntactical coating introduced by ES6 which became another
way of skipping writing callbacks to implement asynchronous operations. Web APIs like
fetch() are implemented using the promising methodology. It makes the code more
readable and is a solution to escape the callback hell.
Unlike synchronous functions, asynchronous functions may not return a value immediately.
Hence, these asynchronous functions instead return a Promise() which can be later used
to get the final value when it gets available in the future. We can easily handle situations
where we successfully receive the data using the resolve() or where we fail to get the data
due to some network error, timeout etc using the reject() as shown below.
Pending
Settled
Fulfilled
Rejected
When the action related to the promise is neither fulfilled nor rejected, it's in a
pending state.
When the action related to the promise is either fulfilled or rejected, it's in a settled
state.
JavaScript 28
When the action related to the promise is executed successfully(resolved), it's in
the fulfilled state.
When the action related to the promise fails(not resolved) due to some error, it's in
the rejected state.
Using the .then() method we can do further actions like calling another callback
function or catching the error.
Promise API
There are 6 static methods in the Promise class. We’ll quickly cover their use cases here.
Promise.all
Let’s say we want many promises to execute in parallel and wait until all of them are ready.
For instance, download several URLs in parallel and process the content once they are all
done.
Promise.allSettled
Promise.allSettled just waits for all promises to settle, regardless of the result. The resulting
array has:
JavaScript 29
{status:"rejected", reason:error} for errors.
Promise.race
Similar to Promise.all , but waits only for the first settled promise and gets its result (or
error).
Promise.any
Similar to Promise.race , but waits only for the first fulfilled promise and gets its result. If all
of the given promises are rejected, then the returned promise is rejected
with AggregateError – a special error object that stores all promise errors in
its errors property.
Promise.resolve/reject
Methods Promise.resolve and Promise.reject are rarely needed in modern code,
because async/await syntax (we’ll cover it a bit later) makes them somewhat obsolete.
JavaScript Async/Await
"async and await make promises easier to write"
async makes a function return a Promise
Async Syntax
The keyword async before a function makes the function return a promise:
Await Syntax
The await keyword can only be used inside an async function.
The await keyword makes the function pause the execution and wait for a resolved
promise before it continues:
JavaScript 30
Using Async Await
async function getdata() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(5);
}, 5000);
});
}
async function main() {
console.log("data processing ");
let data = await getdata();
console.log(data);
console.log("data is ready");
}
main();
And it also helps in tracking errors, which means that the exception explains why the error
occurred and when and where it happened in the code.
Types of Errors
1. Syntax Error:- Syntax errors appear when the user makes a mistake in the predefined
syntax of the javascript language. The interpreter cannot interpret this error raised during
the code compilation.
2. Runtime Error:- Runtime Error occurs during the program's execution and gets detected
only when you run the program; that's why it's known as a runtime error. And these errors
suddenly crash the program or applications, and that's where exception handling became
useful, and via the help of it, we can maintain the normal flow of the program.
3. Logical Error:- Logical Error occurs when there is any logical mistake in the program
that may not produce the desired output and may terminate abnormally. These types of
errors do not throw an error message or an exception.
Error Object
JavaScript 31
Whenever an error occurs during the execution or runtime of the program, the code stops
unexpectedly, and JavaScript raises an exception scenario with the Error object thrown by
the throw statement.
The error object is thrown by JavaScript, or the user can create a user-defined error object
with the help of the throw statement.
Message:- Whereas error message gives or describes the error message in string
form in JavaScript.
try{}:- The try block will contain the code, which may cause exceptions during the
execution. If any errors occur, It stops the execution immediately and passes the
control to the catch block.
catch{}:- The catch block contains the code that will only execute when the errors
occur in the corresponding try block. If the try block is executed successfully, then the
catch block will be ignored.
try {
// code
} catch (err) {
// code
}
finally{}:- The code placed inside the "finally" block will be executed whether an error
has occurred or not.
JavaScript 32
Point - finally is very useful in function , because in a function if we had a return statement
then our rest of the code after it will not run , but if we use finally then we can do this .
throw:- The throw keyword or statement is used for throwing custom or user-defined
errors.
JavaScript 33