JavaScript Fundamentals and cheatsheet.

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

Hello Everyone !! In this tutorial, I am going to teach you about JavaScript and everything you need to get started with JavaScript.

Introduction:

What is JavaScript ?

  • JavaScript is a High-Level programming language.
  • It is often abbreviated as JS
  • Alongside HTML and CSS, JavaScript 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 that store the value.
  • It contains data that can be used throughout the entire program.
  • You can declare a variable using var, let, and const.
  • "var" is the less preferred way. So, "let" and "const" are highly recommended for declaring the variables.
var username = "Tommy"

let firstName = "Thomas"

const lastName = "Shelby"

// console.log(username)
// console.log(firstName)
// console.log(lastName)

Using Variables:

To declare variables we use "var","let" and "const"

  • "var" is not recommended way for declaring the variables. It is only used in the previous version of JavaScript (version before es6)
  • "let" is recommended way to declare the variable. It can be reassigned.
  • "const" is also recommended way to declare the variable. It cannot be redeclared and can only have a constant value.
// var let const

var name = "pramit marattha";
console.log(name);
name = "yolo kumar";
console.log(name);

// Initializing the variables
var greetings;
console.log(greetings);
greetings = "yoo there";
console.log(greetings);

// rules and conventions of javascript
// letters
// numbers
// _
// $
// cannot start with a numbers

var name = "thanos";
// var 1name // not valid

// multi word variables
var firstName = "thanos"; // camel casing
var first_name = "promear"; // underscore convention
var FirstName = "yolomeat"; // pascal case

// let

let name = "narayan gopal";
console.log(name);
name = "yolo kumar";
console.log(name);

// 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()

console.log() method helps to print the message in the web console. The message can be simple JavaScript strings, numbers, boolean, objects, and arrays.

// log to console
console.log("hello there");
console.log(123456789);
console.log(true);
console.log(false);
var 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("hello there");
console.log("hello there");
console.log("hello there");
console.log("hello there");
console.log("hello there");
console.log("hello there");
console.timeEnd("Hello");

Data Types:

image.png

Primitive Data Type:

  • Strings
  • Number
  • Boolean
  • Undefined
  • Null

Strings:

It is a primitive data type that represents and manipulates a sequence of characters such as letters, spaces numbers, and characters. Strings are usually wrapped around in quotes. (either double-quote or single)

let stringOne = "I am a string";
const StringTwo = "I am also a string"

let stringThree = "1234567890";
let stringSingleQuote = 'This is also a string'
Template literals (Template strings)

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.

`This is a string`

`This 
  is
  also
  a
  string
`

let name = "Thanos";

let str = `${name} is powerfull. He is ${500 + 500} years old.`

console.log(str);

Numbers:

It is also a primitive data type. It includes all sets of integers and floating-point numbers.

let firstNumber  = 12345;

let secondNumber = 56789;

let floatNumber = 123.456;

const numberOne = 100;
const numberTwo = 3;

let val;

val = numberOne + numberTwo;
val = numberOne * numberTwo;
val = numberOne - numberTwo;
val = numberOne / numberTwo;
val = numberOne % numberTwo;

//NOTE Math Object (its an object because it contains both properties as well as function)
val = Math.PI;
val = Math.E;
val = Math.round(2.111);
val = Math.ceil(1.4);
val = Math.floor(1.4);
val = Math.sqrt(49);
val = Math.abs(-11); // converts into positive Numbers
val = Math.pow(2, 2);
val = Math.min(1222, 123, 123342, 2829028, 226262, 626, 11, 1726, 10, 13, 62);
val = Math.max(1222, 123, 123342, 2829028, 226262, 626, 11, 1726, 10, 13, 62);
val = Math.random();

val = Math.random() * 10; // if we want random number from max numebr of 20
val = Math.floor(Math.random() * 10 + 1);

// results
console.log(val);
  • Airthematic operators.
const a = 10,
  b = 11,
  c = 30;

const str = "10",
  st2 = "11",
  str3 = "12";

// addition
console.group("Addition");
console.log(a + b);

console.log(b + c);

// addign string
console.log(str + str2);

// dynamically type language means you can change the type on the fly

// adding number nad string

console.log(a + str);

// substraction
console.group("Substration");
console.log(a - b);
console.log(b - c);

console.groupEnd();

// multiplication operator

console.group("Multiplication");

console.log(b * c);

console.log(a * b);

console.groupEnd();

// division operator
console.group("Division");
console.log(b / c);
console.log(a / b);
console.groupEnd();

// Increment

console.group("Increment");
console.log(a + 1);
console.log(a++);
console.log((c = c + a));
console.log((c += a));
a++;
++a;
b--;
--b;
c += a;
console.groupEnd();

Booleans:

It is a primitive data type that can be either "true" or "false"

let isOnline = true;

let isOffline = false;

Null:

It is also a primitive data type. It is simply an absence of value.

let a = null;

Undefined:

It is a primitive data type. It simply represents a lack of defined value. If the variables are declared but not assigned/initialized a specific value to it, that variable will have an undefined value.

let name;

console.log(name) // undefined

Non-Primitive Data Types:

  • Functions
  • Objects
  • Arrays

Functions:

Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript 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 should take some input and return an output where there is some 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 Decleration ( Function definition or Function statement):

  • name of a function.
  • list of parameter to that function.

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:

The function keyword can be used to define a function inside an expression. These types of functions can be anonymous. It doesn't have to have a name.

Anonymous Functions:
  • It does not have a name property.
  • It can be defined only by using the function keyword.
const add = function(a,b){ 
      return a + b; 
};

let x = add(2,3)

console.log(x); // 5

IFFEs


// Immidiately Invocable Functions Expressions - IFFEs
//NOTE functions that can be declared nad run at the same time
(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");

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.

Calling the function:

Defining a function does not execute it. Defining it names the function and specifies what to do when the function is called. Calling the function actually performs the specified actions with the indicated parameters.

add(1,2)

sub(4,3)

NOTE: Functions must be in scope when they are called, but the function declaration can be hoisted


console.log(multiply(2,4));


function multiply(a,b){
    return a * b;
}

Objects:

JavaScript objects are containers for named values called properties or methods.

  • A built-in non-primitive data type 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:

  • Object literal is enclosed with curly braces.
  • Values are mapped to the key with the colon symbol.
  • All keys must be unique, but values can be declared whatever/anything.
  • Key-value pairs are also referred to as object properties.
  • key-value pairs are separated by commas.
const details = {
    name:"Pramit",
    isOnline : true,
    phoneNumber: 123456789
}

Objects are mutable:

  • 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 details = {
    name: "Thanos",
    age:1000,
    phoneNumber: 6781367092
}

delete details.phoneNumber;

details.age = 1001;

console.log(details)

// {name:"Thanos",age:1001}

Dot(.) for accessing object properties

  • Properties of an object can be accessed by "Object.propertyName"
const car = {
   name: "Hummer",
   color:"black",
   licensePlate:1234
}

console.log(car.name) // Hummer

console.log(car.color) // Black
  • JavaScript will throw "undefined" if we try to access the property which is not declared ( which does not exist). example,
const car = {
   name: "Hummer",
   color:"black",
   licensePlate:1234
}

console.log(car.age) // Undefined

for-in loop in object

  • It iterates over the keys of an Object
const car = {
   name: "Hummer",
   color:"black",
   licensePlate:1234
}

for(let key in car){
 console.log(`${key} : ${cars[key]}`)
}

Passing Objects as an argument:

  • If the object is passed as arguments to a function, they passed by reference

const age = 100;
const details = { name: "pramit" };

const chngObjArgs = (ag, obj) => {
  ag = 7;
  obj.name = "Thanos";
};
chngObjArgs(age, details);

console.log(age);  // 100

console.log(details.name); // Thanos

Object Methods:

  • If the property value of an Object is functions then they are called Object Method.
const details = {
    name:()=>{
    console.log("Hello there , I am general Kenobi")
};

details.name() ;

// Hello there , I am general Kenobi

Object destructuring:

const details = {
    name:"Pramit",
    profession:"web developer",
    isOnline: true,
    isOffline:false,
    username:"ppp",
}

const {name,profession,isOnline,isOffline,username} = details;

console.log(name)

console.log(profession)

console.log(isOnline)

console.log(isOffline)

console.log(username)

Shorthand technique for Object Creations:

const name = "Thanos";

const details = {name};

console.log(details)

this keyword

"this" is a reserved keyword in JavaScript.It refers to the method's calling object and it can be used to access the method belonging to that object.

const details = {
    name:"Pramit",
    isOnline:true
   thisName(){
    return this.name;
    }
}

console.log(detail.thisName())
// Pramit

const ageCalc = {
   oldAge: 100,
   newAge:23,
   calculateAge(){
   return this.oldAge - this.newAge;
   }
}

console.log(ageCalc.calculateAge());

Factory Function:

  • function that returns an object is called the factory function.
const car = (name,color,engineType) => {
return {
    name:name,
    color:color,
    engineType:engineType
    startEngine(){
     console.log("Starting Engine.....")
    }
}
}

Arrays:

  • JavaScript arrays are used to store multiple values in a single variable.
  • An array can hold many values under a single name, and you can access the values by referring to an index number.
const stringArray = ["my","name","is","thanos"]

const numArray = [1,2,3,4,5,6,7,8,9]

// mixed array

const mixedArray = [1,"my",2,"name",8,"is",7,"thanos",true,false]
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.

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

const age = 100;

// equal to
if (age == "100") {
  console.log("true");
} else {
  console.log("wrong");
}

// Not equal to
if (age != 100) {
  console.log("true");
} else {
  console.log("wrong");
}

//NOTE equal to Value and type
if (age === 100) {
  console.log("true");
} else {
  console.log("wrong");
}

// Not equal to Value and type
if (age === 100) {
  console.log("true");
} else {
  console.log("wrong");
}
// Testing if the age is undefined
if (typeof age !== "undefined") {
  console.log(`Your age is ${age}`);
} else {
  console.log(`Either you died or you are immortal`);
}

// 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`);
}

// TERENARY OPerator
console.log(hisAge === 23 ? "Correct" : "Incorrect");

// Without braces
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 no 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

image.png

image.png

// comparisons operator in javascript

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
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

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

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 and 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

image.png

false || false      //  false
false || true       // true
true || false      //  true
true || true       // true

Logical AND (&&) operator

image.png

false && false      //  false
false && true       // false
true && false      //  false
true && true       // true

Loops

For loops

// Loops and Iteration

// 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);
}

//NOTE continue => It keep on cotinuing the loop
for (let i = 0; i <= 10; i++) {
  if (i === 2) {
    console.log("Two");
    continue;
  }
  console.log(i);
}

//NOTE breaks => It breaks the loop
for (let i = 0; i <= 10; i++) {
  if (i === 2) {
    console.log("Two");
    break;
  }
  console.log(i);
}

// Looping through arrays

const names = ["pramit", "ram", "shyam", "hari", "krishna", "gopal"];

for (let a = 0; a < names.length; a++) {
  console.log(names[a]);
}

//NOTE 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);
});

//NOTE Looping through arrays of objects using 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: "chaudhary" },
];

const ids = users.map((user) => {
  return user.id;
});

console.log(ids);

//NOTE for in loop used in objects

const userBase = {
  firstName: "pramit",
  lastName: "marattha",
  age: 23,
};

for (let x in userBase) {
  console.log(`${x} :==> ${userBase[x]}`);
}

While Loops and do-while

// while loops

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);

break statement

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);

continue statement

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);

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);

return statement

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 specifc 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
var a = 1;
let b = 22;
const c = 333;

function check() {
  var a = 4444;
  let b = 55555;
  const c = 666666;
  console.log(`Function Scope: ${a} ${b} ${c}`);
}

if (true) {
  var a = 4444;
  let b = 55555;
  const c = 666666;
  console.log(`If block Scope: ${a} ${b} ${c}`);
}

for (var a = 0; a < 10; a++) {
  console.log(`Loop block Scope : ${a}`);
}
check();

console.log(`Global Scope: ${a} ${b} ${c}`);

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 Decleration

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:

  • 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* (){
}
  • "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

  • 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

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)

image.png

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

image.png

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();

image.png

Cheerss!! I will also add tons of stuff that I missed here, in my next upcoming JavaScript series.

See you later ๐ŸŽ‰๐ŸŽ‰. BYEEE!!!

Follow me on Github and Twitter

Comments (2)

Nishant Gour's photo

Pramit Marattha Well structured article mate. Keep it up!

Pramit Marattha's photo

Thank you for your kind words