Complete Js Notes
Complete Js Notes
JAVASCRIPT
JavaScript is a programming language commonly used to add dynamic
and interactions to web pages, applications
3 WAYS To import JS
1. External
2. Internal
3. Inline
JS ENGINE
the browsers have inbuilt JavaScript engine which help to convert
our JavaScript program into computer-understandable language.
Google Chrome V8
JavaScript Comments
JavaScript comments can be used to explain JavaScript code, and to
make it more readable.
Multi-line Comments
Multi-line comments start with /* and end with */
VARIABLES
A variable is a container that stores a value
Ex: var a; //declaring variable
a= 5; //assigning a value to variables
a // identifier
= //assignment operator
JavaScript Let
The let keyword was introduced in (2015)
Console log
The console.log () is a used for debugging purpose in JavaScript &
which helps to print any kind of variables defined before that needs
to be displayed to the user.
JavaScript Strings
A string (or a text string) is a series of characters like "John Doe".
JavaScript Numbers
All JavaScript numbers are stored as decimal numbers (floating point).
// Without decimals:
let x2 = 34;
JavaScript Booleans
Booleans can only have two values: true or false.
JAVASCRIPT undefined
The undefined property indicates that a variable has not been assigned a value, or not
declared at all.
JavaScript Null
null expresses a lack of identification, indicating that a variable
points to no object
JavaScript BigInt
JavaScript integers are only accurate up to 15 digits:
let y = BigInt("99999999999999999999")
JavaScript Arrays
JavaScript arrays are written with square brackets.
JavaScript Objects
JavaScript objects are written with curly braces {}.
Object properties are written as name:value pairs, separated by commas.
Arithmetic Operators
Assignment Operators
Comparison Operators
String Operators
Logical Operators
Bitwise Operators
Ternary Operators
Type Operators
Arithmetic Operators
Arithmetic Operators are used to perform arithmetic on numbers:
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
++ Increment
-- Decrement
Assignment Operators
Assignment operators assign values to JavaScript variables.
Ex: let x = 10;
= //assignment operator
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
Comparison Operators
Operator Description
== equal to
!= not equal
String operator
let text1 = "What a very ";
text1 += "nice day";
let text3 = text1 + " " + text2;
Type Coercion
conversion is the process of converting data of one type to another.
JavaScript Logical Operators
Operator Description
|| logical or
! logical not
Ternary Operator
Ex: let result = (10 > 0) ? true : false;
Type Operator
You can use the JavaScript typeof operator to find the type of a JavaScript variable.
console.log(typeof 42);
console.log(typeof 'blubber');
Bitwise Operators
Operator Name Description
Length
Ex: let text = "Hello World!";
let length = text.length;
charAt
let text = "HELLO WORLD";
let letter = text.charAt(0);
let letter = text.charAt(text.length-1);
concat()
let text1 = "sea";
let text2 = "food";
let result = text1.concat(text2);
let result = text1.concat(" ", text2);
includes()
The includes() method returns true if a string contains a specified string.
Repeat()
The repeat() method returns a string with a number of copies of a string.
Replace()
let text = "Visit Microsoft!";
let result = text.replace("Microsoft", "W3Schools");
indexOf()
--> returns -1 if the value is not found.
let text = "Hello world, welcome to the universe.";
let result = text.indexOf("welcome");
lastIndexOf()
--> returns -1 if the value is not found.
let text = "Hello planet earth, you are a great planet.";
let result = text.lastIndexOf("planet");
Trim()
Remove spaces:
JavaScript Arrays
An array is a special variable, which can hold more than one value:
Array Methods
Array length
Array totring()
Array join()
Array concat()
Array pop()
Array push()
Array shift()
Array unshift()
Array delete()
Array slice()
Array splice()
Array length
The length property returns the length (size) of an array:
Array toString()
The JavaScript method toString() converts an array to a string of (comma separated)
array values.
Array join()
The join() method also joins all array elements into a string.
It behaves just like toString(), but in addition you can specify the separator:
Concatenating Arrays
The concat() method creates a new array by merging (concatenating) existing arrays:
Array pop()
The pop() method removes the last element from an array:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();
Array push()
The push() method adds a new element to an array (at the end):
Array shift()
The shift() method removes the first array element and "shifts" all other elements to a
lower index.
Array unshift()
The unshift() method adds a new element to an array (at the beginning), and "unshifts"
older elements:
Array splice()
The splice() method can be used to add new items / remove items to an array:
Array slice()
The slice() method can be used to remove items to an array:
Array delete()
Array elements can be deleted using the JavaScript operator delete. But leaves undefined holes in
the array
Object
Objects are variables too. objects can contain many values along
with property name and value.
objectName["propertyName"] = ‘value’;
//Ex:
let user = {
firstName: 'Mickel',
lastName: "John",
gender: "Male",
}
console.log(user)
console.log(user.firstName)
console.log(user["firstName"])
user.firstName = 'carlos';
user.proffesinal = 'cricketer';
console.log(user)
delete user.gender;
console.log(user)
New Date()
Const todaysDate = new Date()
IF Else
if (condition1) {
statement1
}else if (condition2){
statement2
}else if (condition3)
statement3
Else{
statementN
Ex:
const number = prompt("Enter a number: ");
if (number > 0) {
console.log("The number is positive");
}
else if (number == 0) {
console.log("The number is 0");
}
else {
console.log("The number is negative");
}
Switch
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
case valueN:
statementN;
break;
default:
statementDefault;
}
switch (parseInt(number)) {
case 1:
console.log("The number is 1");
break;
case 0:
console.log("The number is 0");
break;
case -1:
console.log("The number is -1");
break;
default:
console.log("neither 1 or 0 or -1");
}
For Loop
for (initialization; checkcondition; update)
while Loop
while (condition) {
code block to be executed
}
Ex: let i = 0;
while (i < 5) {
console.log(i);
i++;
}
do while Loop
The do...while statements combo defines a code block to be
executed once, and repeated as long as a condition is true.
The do...while is used when you want to run a code block at least
one time.
Ex: let i = 0;
do {
console.log(i)
i++;
}
while (i < 5);+
For of Loop
Iterate (loop) over the values of an array:
For in Loop
Iterate (loop) over the properties of an object:
JavaScript Functions
A JavaScript function is a block of code designed to perform a particular
task.
The idea is to put some commonly or repeatedly done tasks
together and make a function so that instead of writing the same
code again and again for different inputs, we can call that function.
Syntax:
function functionName(Parameter1, Parametern)
{
// code to be executed
}
Every function should begin with the
keyword function followed by,
A user-defined function name that should be unique,
A list of statements composing the body of the function
enclosed within curly braces {}.
Ex:
function addNum(number1, number2) {
return number1 + number2;
}
argument
A value provided as input to a function.
parameter
A variable identifier provided as input to a function.
Events
An HTML event can be something the browser does, or something a
user does.
Mouse events:
mouseover onmouseover When the cursor of the mouse comes over the element
Keyboard events:
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
Form events:
change onchange When the user modifies or changes the value of a form element
When an HTML file is loaded into the browser, the javascript can
not understand the HTML document directly. So, a browser creates
corresponding Document Object Model of the page(DOM).
The HTML DOM can be accessed with JavaScript (and with other
programming languages).
Property Description
addEventListener
element.addEventListener("click", myFunction);
2. createTextNode
3. appendChild
Ex:
const node = document.createElement("li");
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
setAttribute
1. createAttribute
2. setAttributeNode
document.getElementsByTagName("h1")[0].setAttributeNode(att);
querySelector
document.querySelector(".example").style.backgroundColor = "red";
querySelectorAll
JavaScript Math
The JavaScript Math object allows you to perform mathematical
tasks on numbers.
1. Math.PI
2. Math.round(x) - returns the value of x rounded to its nearest
integer
3. Math.ceil(x) - rounds a number up to its nearest integer
4. Math.floor(x) - rounds a number down to its nearest integer
5. Math.pow(8, 2);
6. Math.sqrt(64);
7. Math.random() //0.1 to 1
8. Math.min(0, 150, 30, 20, -8, -200);
9. Math.max(0, 150, 30, 20, -8, -200);
Number Methods
In the chapter Number Methods, you will find more methods that
can be used to convert strings to numbers:
Method Description
let x = 9.656;
x.toFixed(0);
x.toFixed(2);
x.toFixed(4);
x.toFixed(6);
let x = 9.656;
x.toPrecision();
x.toPrecision(2);
x.toPrecision(4);
x.toPrecision(6);
JavaScript BOM
The Browser Object Model (BOM)deals with the browser itself and
provides objects and methods for interacting with the browser
window.
function myGreeting() {
function hello() {
alert(“hello”)
}
Location – manipulate the location of a document via
the location object.
Console.log(location )
Console.log(history.back(), history.forward())
Console.log(screen )
Hoisting
Hoisting is a concept that enables us to extract values of variables
even before initializing/assigning value without getting errors and
this happens during the 1st phase (memory creation phase) of the
Execution Context.
Features of Hoisting:
In JavaScript, Hoisting is the default behavior of moving all
the declarations at the top of the scope before code execution.
Basically, it gives us an advantage that no matter where
functions and variables are declared, they are moved to the top
of their scope regardless of whether their scope is global or
local.
What is JSON?
JSON or JavaScript Object Notation is a format for structuring
data.
JSON is the most commonly used format for transmitting data (data interchange) from a
server to a client and vice-versa. JSON data are very easy to parse and use. It is fast to
access and manipulate JSON data as they only contain texts.
JSON Object
The JSON object is written inside curly braces { }. JSON objects can contain
multiple key/value pairs. For example,
// JSON object
JSON Array
JSON array is written inside square brackets [ ]. For example,
// JSON array
JSON Data
You can access JSON data using the dot notation. For example,
// JSON object
const data = {
"name": "John",
"age": 22,
"hobby": {
"reading" : true,
"gaming" : false,
"sport" : {
"reading" : true,
"gaming" : false,
"sport" : {
"reading" : true,
"gaming" : false,
"sport" : "cricket"
},
console.log(data.hobby.sport); // football
console.log(data.class[1]); // HTML
// JavaScript object
const jsonData = { "name": "John", "age": 22 };
// converting to JSON
const obj = JSON.stringify(jsonData);
REGEX
A regular expression (regex) is a sequence of characters that
define a search pattern
A regular expression (regex for short) allow developers to match strings against a pattern, extract
submatch information, or simply test if the string conforms to that pattern.
Syntax
/pattern/modifiers;
Ex:
const text = 'john is very very good boy';
Console.log(text.replace(very, Very))
console.log(text.replace(regex, "VERY"))
Password Validation
const passVal= /[A-Z][a-z]+[0-9]+[@#$]/;
Email Validation
const emailValidation = /[a-z0-9_\-\.]+@[a-z][\.][a-z]{2, 10}/;
Try catch
The try statement defines the code block to run (to try).
The catch block catches the error and executes the code to handle it
The finally statement defines a code block to run regardless of the result.
try {
Try Block to check for errors.
}
catch(err) {
Catch Block to display errors.
}
finally {
Finally Block executes regardless of the try / catch result.
}
Ex:
try {
console.log('try');
} catch (e) {
console.log('catch');
} finally {
console.log('finally');
}
try {
dadalert("Welcome Fellow Geek!");
}
catch (err) {
console.log(err);
}
Ex:
const person = {
name: "ram",
age: 22,
greet: function(){
return `Hello ${this.name}, you are ${this.age} years old`
}
}
console.log(person.greet());
JavaScript Callbacks
JavaScript is an asynchronous language, which means that it can
handle multiple tasks simultaneously. Callbacks are a fundamental
aspect of JavaScript, as they allow you to run code after an
asynchronous operation has been completed.
function mainFunction(callback) {
console.log("Performing operation...");
callback("Operation complete");
}
function callbackFunction(result) {
console.log("Result: " + result);
}
mainFunction(callbackFunction);
Closure in JavaScript
A closure is the combination of a function bundled together
(enclosed) with references to its surrounding state (the lexical
environment). I
n other words, a closure gives you access to an outer function's
scope from an inner function. In JavaScript, closures are created
every time a function is created, at function creation time.
A closure is a feature of JavaScript that allows inner functions to
access the outer scope of a function. Closure helps in binding a
function to its outer boundary and is created automatically
whenever a function is created.
Ex:
function x() {
let a = 10;
console.log(a);
function y() {
console.log(a);
}
a = 40;
return y;
}
z = x();
z();
Arrow Function
Arrow functions were introduced in ES6.
Arrow functions allow us to write shorter function syntax:
Arrow functions reduce the size of the code.
it increases the readability of the code.
//Ex:
const arrowFunc = () => {
console.log( "Hi Arrow Function!" );
}
arrowFunc();
Synchronous JavaScript:
As the name suggests synchronous means to be in a sequence, i.e.
every statement of the code gets executed one by one. So,
basically a statement has to wait for the earlier statement to get
executed.
document.write("Hi"); // First
document.write("Mayukh") ;// Second
document.write("How are you");
Asynchronous JavaScript:
Asynchronous programming is a technique that enables your
program to start a potentially long-running task and still be able to
be responsive to other events while that task runs, rather than
having to wait until that task has finished. Once that task has
finished, your program is presented with the result.
Promises
Promises are used to handle asynchronous operations in javascript.
promise.
then(function (item) {
console.log(item);
}).
catch(function (err) {
console.log(err);
});
fetch('https://dummyjson.com/products/1')
.then(res => res.json())
.then(json => console.log(json))
Async function
Async simply allows us to write promises-based code as if it was
synchronous and it checks that we are not breaking the execution
thread. It operates asynchronously via the event loop. Async
functions will always return a value. It makes sure that a promise
is returned and if it is not returned then JavaScript automatically
wraps it in a promise which is resolved with its value.
//Ex:
const getData = async () => {
let data = "Hello World";
return data;
}
Console.log(getData)
function asynchronous_operational_method() {
let first_promise =
new Promise((resolve, reject) => resolve("Hello"));
let second_promise =
new Promise((resolve, reject) => {
setTimeout(() => {
resolve("world");
}, 3000);
});
let combined_promise =
Promise.all([first_promise, second_promise]);
return combined_promise;
}
display();
Promise All
it allows you to pass multiple promises, until all promises
goes to complete status
forEach function
const array1 = ['a', 'b', 'c'];
array1.forEach((element) => console.log(element));
Map Function
The Javascript map() method in JavaScript creates an array by
calling a specific function on each element present in the parent
array.
const array1 = [1, 4, 9, 16];
const map1 = array1.map((item, index) => item * 2);
Filter Function
The JavaScript Array filter() Method is used to create a new array
from a given array consisting of only those elements from the
given array which satisfy a condition set by the argument method.
const array= [1,2,3,4,5,6,7,8];
const result = array.filter((item, index) => item%2 === 0)
Destructuring assignment
The destructuring assignment syntax is a JavaScript expression that
makes it possible to unpack values from arrays, or properties from
objects, into distinct variables.
const x = [1, 2, 3, 4, 5];
const [y, z] = x;
console.log(y); // 1
console.log(z); // 2
Spread Operator
The JavaScript spread operator (...) allows us to quickly copy all or
part of an existing array or object into another array or object.
let obj1 = {
name: 'yogesh',
age: '10',
email: '[email protected]'
}
const res = {
...obj1,
email: '[email protected]'
}
console.log(res)
rest parameter
The rest parameter is an improved way to handle function
parameters, allowing us to more easily handle various inputs as
parameters in a function. The rest parameter syntax allows us to
represent an indefinite number of arguments as an array. With the
help of a rest parameter, a function can be called with any number
of arguments, no matter how it was defined
Array find()
find() method of Array instances returns the first element in the
provided array that satisfies he provided testing function. If no
values satisfy the testing function, undefined is returned.
const array1 = [5, 12, 8, 130, 44];
const found = array1.find((element) => element > 10);
console.log(found);
const inventory = [
{ id: 1, quantity: 2, name: "yogesh" },
{ name: 2, quantity: 0, name: "john" },
{ name: 3, quantity: 5, name: "mickel" },
];
let result = inventory.find((item)=> item.id == 2)
console.log(result)
<body>
<div>
<p>Name</p>
<input type="text" id="title">
</div>
<div>
<p>salary</p>
<input type="number" id="salary">
</div>
<div>
<p>age</p>
<input type="number" id="age">
</div>
<button type="button" onclick="handleFunc()">Submit</button>
<p id="diplymsg"></p>
<script>
function handleFunc() {
const title = document.getElementById("title").value;
const salary = document.getElementById("salary").value;
const age = document.getElementById("age").value;
const object = { name: title, salary: salary, age: age }
let result =
fetch(`https://dummy.restapiexample.com/api/v1/create`, {
method: "POST",
body: JSON.stringify(object)
})
result.then((item) => {
return item.json()
}).then((response) => {
document.getElementById("diplymsg").innerHTML =
response.message
})
}
</script>
</body>
</html>