What exactly is JavaScript?
JavaScript is a High-Level programming language. It is commonly abbreviated as JS. JavaScript, along with HTML and CSS, is one of the core technologies of the World Wide Web. It supports event-driven, functional, and imperative programming styles.
So, without any further ado let's get started.
Variables
Variables are the containers in which value is stored.
It includes information that can be used throughout the program.
Variables can be declared with the var, let, and const operators.
The less preferred method is "var." So, "let" and "const" are highly recommended for declaring the variables.
// var
var username = "Tommy"
//let
let firstName = "Tom"
//const
const lastName = "Cruise"
console.log(username)
console.log(firstName)
console.log(lastName)
Using Variables:
To declare variables we use "var", "let" and "const".
The variable declaration method "var" is not recommended. It is only used in JavaScript's previous version (version before es6)
The variable should be declared using "let." It is possible to reassign it.
The variable should also be declared using "const." It cannot be redefined and can only have a fixed value.
var
// var
var name = "Tom Cruise";
console.log(name);
name = "pramit armpit";
console.log(name);
Initialzing the variables
// Initializing the variables
var greetings;
console.log(greetings);
greetings = "yoo there";
console.log(greetings);
Rules and convention of JavaScript variables
// Allowed
/*
* letters
* numbers
* _ (uderscores)
* $ (dollar signs)
*/
// Not allowed
// do not start variable names with a numbers
let 1name = "groot" // not valid
let name = "thanos"; // valid
Multiword variables
// multi word variables
let firstName = "thanos"; // camel casing
let first_name = "promear"; // underscore convention
let FirstName = "yolomeat"; // pascal case
let
// let
let name = "Brad pitt";
console.log(name);
name = "Christain Bale";
console.log(name);
const
// const => constant
const name = "promeat";
console.log(name);
// cannot reassign
name = "pramit";
// have to assign the value
const greetings;
// but we can change the data inside the object
const person = {
name: "pramit",
age: 230,
};
person.name = "promeat";
person.age = 100;
console.log(person);
// same goes to the array
const numbers = [1, 2, 3, 4, 5, 6, 7];
numbers.push(8);
console.log(numbers);
console.log()
The console.log() method is used to print the message in the web console. The message can be simple JavaScript strings, numbers, booleans, objects, or arrays.
// log to console
console.log("hello there");
console.log(123456789);
console.log(true);
console.log(false);
let hey = "yolo";
console.log(hey);
console.log([1, 2, 3]);
console.table({
a: 1,
b: 2
});
console.error("This is an error");
console.clear();
console.warn("This is an warning");
// -----------------------------------
// console time (check the scripts how long does the code takes)
console.time("Hello");
console.log("YOOO!!!!");
console.log("YOOO!!!!");
console.log("YOOO!!!!");
console.log("YOOO!!!!");
console.log("YOOO!!!!");
console.log("YOOO!!!!");
console.timeEnd("Hello");
Data Types:
Primitive Data Type:
- Strings
- Number
- Boolean
- Undefined
- Null
Strings:
It's a primitive data type that represents and manipulates a string of characters like letters, spaces, numbers, and characters. Strings are typically surrounded by quotes either a double-quote or a single-quote.
let someString = "This is a string";
const stringTwo = "This is also a string"
let stringThree = "123456789011223344";
let stringSingleQuote = 'This is single quote string'
Template literals (Template strings):
Template literals are string literals that support embedded expressions. They support multi-line strings as well as string interpolation.
let name = "Aviyel";
let field = "open source"
let purpose = `${name} is a community driven monetization platform for ${field} Projects`
let projectOnboard = `${name} has already onboarded ${4 + 1} ${field} projects`
console.log(purpose);
console.log(projectOnboard);
`This is a template string`
`This
is
a
multi-line
string
`
Numbers:
It is also a primitive data type. It encompasses all sets of integer and floating-point numbers.
let firstNumber = 12345;
let secondNumber = 56789;
let floatNumber = 123.456;
const numberOne = 100;
const numberTwo = 3;
let calculate;
calculate = numberOne + numberTwo;
//console.log(calculate);
calculate = numberOne * numberTwo;
//console.log(calculate);
calculate = numberOne - numberTwo;
//console.log(calculate);
calculate = numberOne / numberTwo;
//console.log(calculate);
calculate = numberOne % numberTwo;
// result
console.log(calculate);
- Math Object:
//Math Object (its an object because it contains both properties as well as function)
let valueCalc;
valueCalc = Math.PI;
//console.log(valueCalc);
valueCalc = Math.E;
//console.log(valueCalc);
valueCalc = Math.round(2.111);
//console.log(valueCalc);
valueCalc = Math.ceil(1.4);
//console.log(valueCalc);
valueCalc = Math.floor(1.4);
//console.log(valueCalc);
valueCalc = Math.sqrt(49);
//console.log(valueCalc);
valueCalc = Math.abs(-11); // converts into positive Numbers
//console.log(valueCalc);
valueCalc = Math.pow(2, 2);
//console.log(valueCalc);
valueCalc = Math.min(1222, 123, 123342, 2829028, 226262, 626, 11, 1726, 10, 13, 62);
//console.log(valueCalc);
valueCalc = Math.max(1222, 123, 123342, 2829028, 226262, 626, 11, 1726, 10, 13, 62);
//console.log(valueCalc);
valueCalc = Math.random();
//console.log(valueCalc);
valueCalc = Math.random() * 10; // if we want random number from max numebr of 20
//console.log(valueCalc);
valueCalc = Math.floor(Math.random() * 10 + 1);
//result
console.log(valueCalc);
Airthematic operators.
const a = 100,
b = 110,
c = 300;
const str = "100",
st2 = "110",
str3 = "300";
// addition
console.group("Addition");
console.log(a + b);
console.log(b + c);
console.groupEnd();
// adding string
console.log(str + str2);
NOTE: JavaScript is a dynamically typed language, which means that the type can be changed on the fly.
- Adding Number to String:
const numberOne = 100;
const stringOne = "100",
console.log(numberOne + stringOne);
const a = 1000,
b = 110,
c = 40;
// Subtraction
console.group("Substration");
console.log(a - b);
console.log(b - c);
console.groupEnd();
3 . Multiplication Operator
const a = 1000,
b = 110,
c = 40;
// Multiplication
console.group("Multiplication");
console.log(b * c);
console.log(a * b);
console.groupEnd();
const a = 1000,
b = 100,
c = 3;
// Division
console.group("Modulus");
console.log(b % c);
console.log(a % b);
console.groupEnd();
let a = 1000,
b = 100,
c = 3;
console.group("Increment");
console.log(a + 1);
console.log(a++);
console.log((c = c + a));
console.log((c += a));
console.groupEnd();
let a = 1000,
b = 100,
c = 3;
console.group("Decrement");
console.log(a - 1);
console.log(a--);
console.log((c = c - a));
console.log((c -= a));
console.groupEnd();
Booleans:
It is a primitive data type that can be either "true" or "false".
let isOpenSource;
isOpenSource = true;
isOpenSource = false;
//result
console.log(isOpenSource);
Null:
It is also a primitive data type. It is simply an absence of value.
let existence = null;
//result
console.log(existence);
Undefined:
It simply denotes the absence of a defined value. If a variable is declared but not assigned/initialized with a specific value, it will have an undefined value. It simply denotes the absence of a defined value. If a variable is declared but not assigned/initialized with a specific value, it will have an undefined value.
let name;
console.log(name) // undefined
Non-Primitive Data Type:
- Functions
- Objects
- Arrays
Functions:
Functions are one of JavaScript's fundamental building blocks. In JavaScript, a function is similar to a procedure—a set of statements that performs a task or calculates a value—but for a procedure to qualify as a function, it must take some input and return an output with an obvious relationship between the input and the output.
function add(a, b) {
return a + b;
}
console.log(add(1, 2));
// es6 arrow function
const add = (a, b) => a + b;
console.log(add(1, 2))
Defining Functions:
A function is a reusable set of statements to perform a task or calculate a value.
1 . Function Declaration ( Function definition or Function statement):
- name of a function.
- list of parameters to that function. for example,
function sub(a,b){
return a - b
};
The function "sub" takes two parameters a and b. This function consists of one return statement that returns the subtracted value of a - b.
Return.
- Functions return values using the return.
- It ends function execution and returns the specified value to the location where it was called.
- If a return statement is not declared the function will throw "undefined" by default.
2 . Function expression:
Within an expression, the function keyword can be used to define a function. These functions can be performed anonymously. It isn't required to give it a name.
Anonymous Functions:
- It does not have a name property.
- It can be defined only by using the function keyword. for example,
const add = function(a,b){
return a + b;
};
let x = add(2,3)
console.log(x); // 5
Immediately Invocable Functions Expression - IFFEs
(function(x = 2) {
console.log(`${x * x}`);
console.log(`Immidiately Invocable Functions Expressions - IFFEs`);
})();
(function(y, name) {
console.log(`${y * y}`);
console.log(`${name} yooooooo`);
})(9, "nine");
NOTE: IFFEs can be declared and run at the same time.
Calling the function:
Defining a function does not execute it. Calling the function actually performs the specified actions with the indicated parameters.
add(100,200)
sub(200,100)
NOTE: Functions must be in scope when they are called, but the function declaration can be hoisted
console.log(add(20,90));
function add(a,b){
return a + b;
}
Parameters VS Arguments
Parameters:
- A parameter is a named variable passed into a function. Parameter variables are used to import arguments into functions.
Arguments:
- An argument is a value (primitive or object) passed as input to a function.
Objects:
JavaScript objects are containers for named values called properties or methods. Objects are built-in non-primitive data types for storing key-value pairs.
Data inside of that objects is not in order and the values can be of any type.
Property and value of an Object:
- Curly braces surround the object literal.
- The colon symbol is used to map values to keys.
- All keys must be unique, but values can be whatever/anything they want.
- Object properties are another name for key-value pairs.
- Commas are used to separate key-value pairs.
const projectDetails = {
name: "Typesense",
isOpenSource: true,
githubStars: 8200
}
Objects can be changed:
- The content inside the objects can be changed even if they are declared with const.
- New properties can be added, deleted, and can be changed.
const projectDetails = {
name: "Typesense",
isOpenSource: true,
githubStars: 8200
}
delete projectDetails.isOpenSource;
projectDetails.githubStars = 9000;
console.log(projectDetails)
// { name: 'Typesense', githubStars: 9000 }
A dot (.) for accessing object properties
- Properties of an object can be accessed by "Object.propertyName"
const car = {
name: "Lambo",
color: "orange",
licensePlate: 420
}
console.log(car.name) // Lambo
console.log(car.color) // orange
- JavaScript will throw "undefined" if we try to access the property which is not declared ( which does not exist). example,
const car = {
name: "Lambo",
color:"orange",
licensePlate: 420
}
console.log(car.age) // Undefined
For-in loop in object
- It iterates over the keys of an Object
const car = {
name: "Lambo",
color: "orange",
licensePlate: 420
}
for (let key in car) {
console.log(`${key} : ${cars[key]}`)
}
/*
*name : Lambo
*color : orange
*licensePlate : 420
*/
Passing Objects as an argument:
- When an object is passed as an argument to a function, it is passed by reference.
const age = 100;
const details = {
name: "pramit"
};
const chngObjArgs = (ag, obj) => {
age = 7;
obj.name = "Thanos";
};
chngObjArgs(age, details);
console.log(age); // 100
console.log(details.name); // Thanos
Object Methods:
- If an Object's property value is a function, they are referred to as Object Methods.
const details = {
name: () => {
console.log("Hello there , Yo!! how are you doing ")
};
}
details.name();
// Hello there , Yo!! how are you doing
Object destructuring:
const details = {
name: 'Pramit',
profession: 'web developer',
isOnline: true,
isOffline: false,
username: 'promeat',
};
const {
name,
profession,
isOnline,
isOffline,
username
} = details;
console.log(name); // Pramit
console.log(profession); // web developer
console.log(isOnline); // true
console.log(isOffline); // false
console.log(username); // promeat
Shortcut technique for Object Creations:
const name = "Thanos";
const details = {name};
console.log(details) // { name: 'Thanos' }
“this” keyword in JavaScript Object
In JavaScript, "this" is a reserved keyword. It refers to the method's calling object and can be used to access the object's method.
const details = {
name: "Pramit",
isOnline: true
thisName() {
return this.name;
}
}
console.log(detail.thisName()) // Pramit
// Another Example
const ageCalc = {
oldAge: 100,
newAge: 23,
calculateAge() {
return this.oldAge - this.newAge;
}
}
console.log(ageCalc.calculateAge()); // 77
Factory Function:
- The factory function is a function that returns an object.
// Factory Function creating car
let Car = function(name, color) {
// creating car object
let car = {};
// parameters as keys to this object
car.name = name;
car.color = color;
// function to start engine
car.vroom = function() {
return 'Vrom vrom!! ' + car.name + ' is ' + car.color + ' color ';
};
return car;
};
let carOne = Car('Lambo', 'orange');
console.log(carOne.vroom()); // Vrom vrom!! Lambo is orange color
let carTwo = Car('Ferarri', 'Red');
console.log(carTwo.vroom()); // Vrom vrom!! Ferarri is Red color
Arrays:
Multiple values can be stored in a single variable using JavaScript arrays.
Many values can be stored in an array with a single name, and the values can be accessed by referring to an index number.
const stringArray = ["my", "name", "is", "pramit"]
// result
console.log(stringArray)
const numArray = [1, 2, 3, 4, 5, 6, 7, 8, 9]
// result
console.log(numArray)
Mixed Array
const mixedArray = [1,"my",2,"name",8,"is",7,"pramit",true,false]
//result
console.log(mixedArray)
Index:
- Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations.
- Array elements are arranged by an index value.
- Index value always starts with 0.
Creating an array
let comics = ['DC', 'Marvel']
console.log(comics)
**Checking the length of an array.**
console.log(comics.length)
Accessing array items using index position
let first = comics[0]
let second = comics[1]
Accessing the last item of an array
let last = comics[comics.length - 1]
Looping an array
comics.forEach(function(item, index, array) {
console.log(item, index)
})
// DC 0
// Marvel 1
Adding Items to an end of an array.
let newLength = comics.push('Capcom')
// ["DC", "Marvel", "Capcom"]
Removing an item from the end of an Array
let last = comics.pop() // remove Capcom
// ["DC", "Marvel"]
Removing an item from the beginning of an Array
let first = comics.shift() // remove DC from the front
// ["Marvel"]
Adding an item to the beginning of an Array
let newLength = comics.unshift('Nintendo') // add to the front
// ["Nintendo", "Marvel"]
Find the index of an item in the Array
let pos = comics.indexOf('Marvel')
// 1
Removing an item by index position
let removedItem = comics.splice(1, 1)
// ["Nintendo"]
Removing items from an index position
let comics = ['Nintendo', 'DC', 'Marvel', 'Capcom']
console.log(comics)
// ['Nintendo', 'DC', 'Marvel', 'Capcom']
let removedItems = comics.splice(1, 2)
console.log(comics)
// [ 'Nintendo', 'Capcom' ]
console.log(removedItems)
// [ 'DC', 'Marvel' ]
Copy an Array
let shallowCopy = comics.slice() // this is how to make a copy
// or
let copyArray = [...comics]
Conditionals
Conditional statements control behavior and determine whether or not pieces of code can run. Conditional statements are used to control the execution flow based on certain conditions. If a condition is true, you can do one action; if it is false, you can take a different action.
If-statement
- If the expression is truthy then only the code executes
const isOnline = true;
if (isOnline) {
console.log("Thanos is Online")
}
else statement
- else block executes if the "if" condition fails.
const isOnline = false;
if(isOnline){
console.log("Thanos is Online")
} else{
console.log("Thanos is Not Online")
}
If-else statement
Equal to
const age = 100;
// equal to
if (age == "100") {
console.log("true");
} else {
console.log("wrong");
}
Not Equal to
const age = 100;
if (age != 100) {
console.log("true");
} else {
console.log("wrong");
}
Equal to value and type
const age = 100;
if (age === 100) {
console.log("true");
} else {
console.log("wrong");
}
Not Equal to value and type
const age = 100;
if (age === 100) {
console.log("true");
} else {
console.log("wrong");
}
Greater than or less than
if (age >= 100) {
console.log("true");
} else {
console.log("wrong");
}
if (age < 100) {
console.log("true");
} else {
console.log("wrong");
}
If Else statement
const color = "purple";
if (color === "red") {
console.log("Color is red");
} else if (color === "green") {
console.log("Color is green");
} else {
console.log("Color is Neither red nor green");
}
Logical Operator
// Ampersand operator
const name = "pramit";
const hisAge = 23;
if (hisAge > 0 && hisAge < 20) {
console.log(`${name} is a Teenager`);
} else if (hisAge > 20 && hisAge < 30) {
console.log(`${name} is in his Twenties`);
} else {
console.log("He is OLD");
}
OR operator
if (hisAge > 16 || hisAge < 25) {
console.log(`${name} he can join the army`);
} else {
console.log(`${name} cannot run in race`);
}
Ternary operator
console.log(hisAge === 23 ? "Correct" : "Incorrect");
If else without a brace
if (hisAge > 16 || hisAge < 25) console.log(`${name} he can join the army`);
else console.log(`${name} cannot run in race`);
switch-case statement
The switch statement is used to perform different actions based on different conditions.
- Switch is evaluated once.
- value of the expression is compared with each case.
- if there is a match the code block gets executed.
- if there is not any match the default code block gets executed.
const foobar = "bar";
switch (foobar) {
case "foo": {
let x = 60;
console.log(x + 9);
break;
}
case "bar": {
let y = 400;
console.log(y + 20);
break;
}
default: {
console.log("REEEE!!!!!!!!!");
}
}
Comparison operator
- Compares two value and return either true or false
const name = "pramit";
const name2 = "PRAMIT";
console.group("strings");
console.log(name == "pramit"); // true
console.log(name == name2); //false
console.log(name == name2.toLowerCase());
console.groupEnd();
Numbers comparison
const firstNumber = 69;
const secondNumber = "69";
console.group("numbers");
console.log(firstNumber == secondNumber); // true
console.log(firstNumber === secondNumber); // false
console.log(firstNumber != secondNumber); //false
console.log(firstNumber !== secondNumber); //true
console.groupEnd();
Booleans comparison
let yolo;
let nothing = null;
console.group("booleans");
console.log(Boolean("")); //false
console.log(Boolean("this")); //true
console.log(Boolean(yolo)); //false
console.log(Boolean(nothing)); //false
console.log(Boolean({})); //true
console.log(Boolean([])); //true
console.groupEnd();
Objects and Arrays comparison
const array1 = [1, 2, 3, 4, 5, 6];
const array2 = [1, 2, 3, 4, 5, 6];
const obj1 = {
name: "pramit"
};
const obj2 = {
name: "pramit"
};
console.group("objects and arrays");
console.log(array1 == array2); // false
console.log(obj1 == obj2); // false
console.log(array1 === array2); // false
console.log(obj1 === obj2); // false
console.groupEnd();
AND or OR operator
console.group("And");
console.log(Boolean("true_") && Boolean("true_")); // true
console.log(Boolean("true_") && Boolean("")); // false
console.log(Boolean("") && Boolean("true")); // false
console.log(Boolean("") && Boolean("")); // false
console.groupEnd();
console.group("OR");
console.log(Boolean("true_") || Boolean("true_")); // true
console.log(Boolean("true_") || Boolean("")); // true
console.log(Boolean("") || Boolean("true")); // true
console.log(Boolean("") || Boolean("")); // false
console.groupEnd();
Ternary operator
It's an operator which takes three operands: a condition followed by a question mark (?), and then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy.
condition ? expressionIfTrue : expressionIfFalse
const age = 230
console.log(age === 230 ? "Correct" : "Incorrect");
Logical OR (||) operator
false || false // false
false || true // true
true || false // true
true || true // true
Logical AND (&&) operator
false && false // false
false && true // false
true && false // false
true && true // true
Loops
For loops
// For Loops
for (let i = 0; i <= 10; i++) {
console.log(i);
}
Changing Iteration
for (let i = 0; i <= 10; i++) {
if (i === 2) {
console.log("Two");
}
console.log(i);
}
Continue the loop (Continue statement)
for (let i = 0; i <= 10; i++) {
if (i === 2) {
console.log("Two");
continue;
}
console.log(i);
}
// Another example
let arr1 = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 14, 13, 21, 11, 333, 556, 66,
];
let str = "";
for (let i = 0; i < arr1.length; i++) {
if (i % 2 === 1) continue;
str += (str == "" ? "" : ";") + arr1[i];
// str = str.split(";").sort((a, b) => a - b);
}
console.log(str);
Breaking the loop (Break statement)
for (let i = 0; i <= 10; i++) {
if (i === 2) {
console.log("Two");
break;
}
console.log(i);
}
// Another example
let arr1 = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 14, 13, 21, 11, 333, 556, 66,
];
let str = "";
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] > 10) break;
str += (str === "" ? "" : "; ") + arr1[i];
}
console.log(str);
Looping through arrays
const names = ["pramit", "ram", "shyam", "hari", "krishna", "gopal"];
for (let a = 0; a < names.length; a++) {
console.log(names[a]);
}
Looping through arrays using forEach
const namesTwo = ["pramit", "ram", "shyam", "hari", "krishna", "gopal"];
namesTwo.forEach((nam, index, array) => {
console.log(`${index} : ${nam}`);
console.log(array);
});
Looping through arrays of objects using the map
const users = [
{
id: 1,
name: "pramit"
},
{
id: 2,
name: "marattha"
},
{
id: 3,
name: "ram"
},
{
id: 4,
name: "hari"
},
{
id: 5,
name: "gopal"
},
{
id: 6,
name: "krishna"
},
{
id: 7,
name: "shanker"
},
{
id: 8,
name: "shyam"
},
];
const ids = users.map((user) => {
return user.id;
});
console.log(ids);
For in loop used in Objects
const userBase = {
firstName: "pramit",
lastName: "marattha",
age: 230,
};
for (let x in userBase) {
console.log(`${x} :==> ${userBase[x]}`);
}
While Loops and do-while
let i = 0;
let j = 0;
while (i < 10) {
console.log("Numbers " + i);
i++;
}
Do While Loops
do {
console.log("Numbers " + j);
j++;
} while (j < 10);
Endless loop
for (;;) {
console.log("Stuck in an endless loop");
}
while (true) {
console.log("Stuck in an endless loop");
}
do {
console.log("Stuck in an endless loop");
} while (true);
For in loop
let arr1 = [1, 2, 3, 4, 5, 6, 7, 899, 99, 98, 7, 653, 32, 4];
let sum = 0;
for (let i in arr1) {
// console.log(arr1.hasOwnProperty(i));
if (arr1.hasOwnProperty(i)) {
sum += arr1[i];
}
}
console.log(sum);
For of loop
let arr1 = [1, 2, 3, 4, 5, 6, 7, 899, 99, 98, 7, 653, 32, 4];
let sum = 0;
// for (let i of arr1) {
// sum += i;
// }
for (let i of arr1) {
sum += i;
}
console.log(sum);
labeled statement
let firstMatch = -1;
let arr1 = [1, 2, 3, 4, 5, 6];
let arr2 = arr1.filter((i) => i % 2 === 0);
// console.log(arr2);
firstLoop: for (let i in arr1) {
for (let x in arr2) {
if (arr1[i] === arr2[x]) {
firstMatch = arr1[i];
break firstLoop;
}
}
}
console.log("🚀 ~ file: labeledStatement.js ~ line 2 ~ firstMatch", firstMatch);
function containNumber(numbers, number) {
for (let i in numbers) {
if (numbers.hasOwnProperty(i)) {
if (numbers[i] == number) {
return true;
}
}
}
return false;
}
let arr1 = [1, 23, 4, 5, 67, 60];
let conatinsTwo = containNumber(arr1, 23);
console.log(
"🚀 ~ file: returnStatement.js ~ line 15 ~ conatinsTwo",
conatinsTwo
);
return without value
function someDataWithValue(value) {
someData();
if (!value) {
return;
}
someOtherData();
}
function someData() {
console.log("Some Data");
}
function someOtherData() {
console.log("Some Other Data");
}
someDataWithValue(false);
Error handling
Catch all exception
function catchWhenNullEmpty(array) {
if (array.length == null) {
throw "array is null";
}
if (array.length === 0) {
throw new RangeError();
}
return array;
}
try {
catchWhenNullEmpty(["null"]);
console.log(catchWhenNullEmpty(["null"]));
} catch (error) {
console.log(error);
}
Catch the specific exception
function throwNewNullOrEmpty(array) {
if (array == null) {
throw "Array is null";
}
if (array.length === 0) {
throw new RangeError();
}
}
try {
throwNewNullOrEmpty([]);
} catch (e) {
if (e.name === "RangeError") {
console.log("Array is Empty");
} else {
console.log("Array is not specified");
}
}
Define Exception Type
function simepleExeption() {}
function exception(name, message) {
this.name = name;
this.message = message;
}
throw new exception("exception", "this is a message");
Scope
Global scope
// Global Scope
var a = 1;
let b = 22;
const c = 333;
Functional Scope
function check() {
var a = 4444;
let b = 55555;
const c = 666666;
console.log(`Function Scope: ${a} ${b} ${c}`);
}
check();
If block scope
if (true) {
var a = 4444;
let b = 55555;
const c = 666666;
console.log(`If block Scope: ${a} ${b} ${c}`);
}
Loop block Scope
for (var a = 0; a < 10; a++) {
console.log(`Loop block Scope : ${a}`);
}
Classes
Classes are a template for creating objects.
-
Class syntax has two components
- class declaration.
- class expression.
Constructor:
The constructor method is a special method of a class for creating and initializing an object of that class. A constructor can use the super keyword to call the constructor of the super class.
Class Declaration
class sum {
constructor(numberA, numberB) {
this.numberA = numberA;
this.numberB = numberB;
}
}
Class Expression
named expression
let Sum = class sumTwo {
constructor(numberA, numberB) {
this.numberA = numberA;
this.numberB = numberB;
}
};
console.log(Sum.name);
// output: "sumTwo"
unnamed expression
let Sum = class {
constructor(numberA, numberB) {
this.numberA = numberA;
this.numberB = numberB;
}
};
console.log(Sum.name);
// output: "Sum";
Prototype Method
class Sum {
constructor(numberA, numberB) {
this.numberA = numberA;
this.numberB = numberB;
}
// Getter
get totalSum() {
return this.calculateSum();
}
// Method
calculateSum() {
return this.numberA + this.numberB;
}
}
const tSum = new Sum(10, 10);
console.log(tSum.totalSum); // 20
Binding "this"
When a static or prototype method is called without a value for this, such as by assigning the method to a variable and then calling it, then "this" value will be undefined inside the method.
class Animal {
speak() {
return this;
}
static eat() {
return this;
}
}
let obj = new Animal();
obj.speak(); // the Animal object
let speak = obj.speak;
speak(); // undefined
Animal.eat() // class Animal
let eat = Animal.eat;
eat(); // undefined
Field declaration:
public field declaration.
class Sum {
numberA = 0;
numberB;
constructor(numberA, numberB) {
this.numberA = numberA;
this.numberB = numberB;
}
}
private field declaration.
class Sum {
#numberA = 0;
#numberB;
constructor(numberA, numberB) {
this.#numberA = numberA;
this.#numberB = numberB;
}
}
Subclassing with extends
- extends is used to create a class of another class.
class Instrument {
constructor(name) {
this.name = name;
}
play() {
console.log(`${this.name} creates a melodic harmony.`);
}
}
class Guitar extends Instrument {
constructor(name) {
super(name);
}
play() {
console.log(`${this.name} creates a melody.`);
}
}
let strum = new Guitar("Ibanez");
strum.play(); // Ibanez creates a melody.
Superclass call with super keyword:
The super keyword is used to access and call functions on an object's parent.
class Instrument {
constructor(name) {
this.name = name;
}
play() {
console.log(`${this.name} creates a melodic harmony.`);
}
}
class Guitar extends Instrument {
play() {
super.play()
console.log(`${this.name} creates a melody.`);
}
}
let strum = new Guitar("Ibanez");
strum.play();
// Ibanez creates a melodic harmony.
// Ibanez creates a melody.
Iterators:
- An iterator is an object which defines a sequence and potentially a return value upon its termination.
- iterators allow you to iterate over an object
Specifically, an iterator is any object which implements the Iterator protocol by having a next() method that returns an object with two properties:
value
done
Once created, an iterator object can be iterated explicitly by repeatedly calling next().
function calcRangeIterator(start = 0, end = Infinity, step = 1) {
let nextIndex = start;
let iterationCount = 0;
const rangeIterator = {
next: function() {
let result;
if (nextIndex < end) {
result = {
value: nextIndex,
done: false
}
nextIndex += step;
iterationCount++;
return result;
}
return {
value: iterationCount,
done: true
}
}
};
return rangeIterator;
}
using iterators:
const it = calcRangeIterator(1, 10, 2);
let result = it.next();
while (!result.done) {
console.log(result.value);
result = it.next();
}
console.log("Iterated over sequence of size: ", result.value);
Generators:
Generators are a useful tool that allows us to create iterators by defining a function.
To create generators you need to add (*) in front of the function name.
function *thisIsGenerator(){
}
- To create generators in an anonymous function you need to add (*) at the end of the function itself
function* (){
}
- The "yield" keyword in generators behaves the same as an await in promises.
function* uniqueIdGenerator() {
let i = 0;
while (true) {
yield i++;
}
}
const uniqueId = uniqueIdGenerator();
console.log(uniqueId.next().value); // 0
console.log(uniqueId.next().value); // 1
console.log(uniqueId.next().value); // 2
console.log(uniqueId.next().value); // 3
console.log(uniqueId.next().value); // 4
console.log(uniqueId.next().value); // 5
console.log(uniqueId.next().value); // 6
console.log(uniqueId.next().value); // 7
console.log(uniqueId.next().value); // 8
console.log(uniqueId.next().value); // 9
Callbacks
Callbacks are functions that produce a result after a certain amount of time has passed. These types of asynchronous callbacks are typically used to access values from databases, download photos, read files, and so on. We can't move on to the next line because it can raise an error saying unavailable, and we can't pause our program because these take time to complete. As a result, we must save the result and return it when it is complete.
- Callback function
function one(call_two) {
console.log("step one");
call_two();
}
function two() {
console.log("step two");
}
one(two);
example about callbacks
order ingredients ===> fetch ====> start production ====> serve
let stocks = {
Fruits: ["grapes", "apple", "orange", "banana"],
Liquid: ["water", "ice"],
Holder: ["cone", "cup"],
Toppings: ["sprinkles", "chocolate"],
};
console.log(stocks.Fruits[3]);
Callback hell
Callback hell is a serious problem produced by complicated nested callbacks. Each callback takes an argument that is the outcome of the callbacks before it. The code structure resembles a pyramid in this way, making it difficult to comprehend and maintain. Furthermore, if one function fails, all other functions suffer as a result.
let order = (Fruit_name, call_production) => {
// console.log("order placed");
setTimeout(() => {
console.log(`${stocks.Fruits[Fruit_name]} was selected`);
call_production();
}, 2000);
};
let production = () => {
// console.log("starting production");
setTimeout(() => {
console.log("production has started");
setTimeout(() => {
console.log("Fruit chopped");
setTimeout(() => {
console.log(`${stocks.Liquid[0]} and ${stocks.Liquid[1]} was added`);
setTimeout(() => {
console.log("machine started");
setTimeout(() => {
console.log(`${stocks.Holder[1]} was selected`);
setTimeout(() => {
console.log(`${stocks.Toppings[1]} was added`);
setTimeout(() => {
console.log(`Icecream was served`);
}, 2000);
}, 2000);
}, 2000);
}, 1000);
}, 1000);
}, 2000);
}, 0);
};
order(0, production);
Promises
Promises are used to handle an asynchronous operation.
Promises are used to find out that if the async operations are successfully carried out.
Promises have three states:
- Pending.
- Fulfilled.
- Rejected.
Creating a promise
const isOnline = true;
let prom = new Promise((resolve, reject) => {
if (isOnline) {
resolve("User is online");
} else {
reject("User is not online");
}
});
console.log(prom)
another example,
let stocks = {
Fruits: ["grapes", "apple", "orange", "banana"],
Liquid: ["water", "ice"],
Holder: ["cone", "cup"],
Toppings: ["sprinkles", "chocolate"],
};
let is_shop_open = true;
let order = (time, work) => {
return new Promise((resolve, reject) => {
if (is_shop_open) {
setTimeout(() => {
resolve(work());
}, time);
} else {
reject(console.log("Shop is Closed"));
}
});
};
order(2000, () => console.log(`${stocks.Fruits[0]}`));
Promise chaining
someApiCall().then((result) => {
return someAnotherApiCall();
}).then((result2) => {
return someAnotherNextApiCall();
}).then((result3) => {
// do something
}).catch((error) => {
console.error(error)
});
Async-Await:
async/await is syntactic sugar on top of the promises and provides a way to handle the asynchronous tasks in a synchronous manner
Await pauses the async function until the promise returns a result (resolve or reject) value.
If the promise resolves successfully, the await operator returns the resolved value: const resolvedVal = await promise. Otherwise, you can catch a rejected promise inside try/catch.
Async function always returns a promise, which gives the ability to nest async functions.
async function fetchMovies() {
const response = await fetch('http://www.omdbapi.com/?t=a&y=2000&plot=full');
if (!response.ok) {
throw new Error('Failed to fetch movies');
}
const movies = await response.json();
return movies;
}
another example,
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise is resolved");
}, 1000);
});
const asynchronousFunction = async () => {
let result = await promise;
console.log(result);
};
asynchronousFunction();
Full article(Part-1)available here => https://aviyel.com/post/1187
Full article(Part-2)available here => https://aviyel.com/post/1264
Happy Coding!!
Follow @aviyelHQ or sign-up on Aviyel for early access if you are a project maintainer, contributor, or just an Open Source enthusiast.
Join Aviyel's Discord => Aviyel's world
Twitter =>[https://twitter.com/AviyelHq]
Top comments (7)
The article explains a lot of JS things in a simple and interesting way. I advise you to study, but some errors are possible, which the author will correct and modify.
The errors found in the article have already been fixed:
For example,
~5. Increment Operator => the example declares a constant, but a variable is required (replace const with let)
TypeError: Assignment to constant variable.
Where is point 6?
Same problem with constant in 7. Decrement Operator
Why is the example Not Equal to value and type = Equal to value and type?~
Thankss!! I think I just misplaced the number order.. I am fixing it right now !!
Thank you this is very helpful...
Thanks !! Fixing it right now !!
Not perfectly correct. The link (reference) to the value is fixed and can not be changed, but the value itself can be mutated (e.g. in case of objects or arrays).
Very good work and helpful! congratulations and thanks!
I like the artwork. Curious as to what you used to create it.