Modern JavaScript explained in a way you've never seen before 🔥
Tags: javascript, webdev, beginners, programming
Published: 2021-11-09 08:39:44

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

```javascript
// var
var username = "Tommy"

//let
let firstName = "Tom"

//const
const lastName = "Cruise"

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

```

![variables](https://aviyel.com/assets/uploads/files/1635236139720-image.png)

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

![variable decleration](https://aviyel.com/assets/uploads/files/1634900942787-image.png)

***var***
```javascript
// var 
var name = "Tom Cruise";
console.log(name);

name = "pramit armpit";
console.log(name);
```
***Initialzing the variables***
```javascript
// Initializing the variables
var greetings;
console.log(greetings);
greetings = "yoo there";
console.log(greetings);
```

***Rules and convention of JavaScript variables***
```javascript
// 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***
```javascript
// multi word variables
let firstName = "thanos"; // camel casing
let first_name = "promear"; // underscore convention
let FirstName = "yolomeat"; // pascal case
```

***let***
```javascript
// let
let name = "Brad pitt";
console.log(name);
name = "Christain Bale";
console.log(name);
```

***const***
```javascript
// 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](https://aviyel.com/assets/uploads/files/1635181930151-image.png)

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.

```javascript
// 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:

![Primitive Data Type](https://aviyel.com/assets/uploads/files/1635218580122-image-resized.png)

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

![strings](https://aviyel.com/assets/uploads/files/1635218620156-image.png)

```javascript
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.
![Template Literals](https://aviyel.com/assets/uploads/files/1635218639991-image.png)

```javascript
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.

![Numbers](https://aviyel.com/assets/uploads/files/1635218684801-image.png)

```javascript
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:
```javascript
//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.
1 . Additional operator:
![additional Operator](https://aviyel.com/assets/uploads/files/1635218732066-image.png)

```javascript
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.

![Static vs dynamic](https://aviyel.com/assets/uploads/files/1635218768510-image.png)

- Adding Number to String:
```javascript
const numberOne = 100;
const stringOne = "100",
console.log(numberOne + stringOne);
```

2 . Subtraction operator
![Subtraction](https://aviyel.com/assets/uploads/files/1635218931115-image.png) 

```javascript
const a = 1000,
  b = 110,
  c = 40;

// Subtraction
console.group("Substration");
console.log(a - b);
console.log(b - c);
console.groupEnd();
```

3 . Multiplication Operator

![Multiplication](https://aviyel.com/assets/uploads/files/1635218943041-image.png)
```javascript
const a = 1000,
  b = 110,
  c = 40;

// Multiplication
console.group("Multiplication");
console.log(b * c);
console.log(a * b);
console.groupEnd();
```

4 . Division Operator
![Modulus Operator](https://aviyel.com/assets/uploads/files/1635218970368-image.png)
```javascript
const a = 1000,
    b = 100,
    c = 3;

// Division
console.group("Modulus");
console.log(b % c);
console.log(a % b);
console.groupEnd();
```
5 . Increment Operator
![Increment Operator](https://aviyel.com/assets/uploads/files/1635218985575-image.png)
```javascript
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();
```

6 . Decrement Operator
![Decrement Operator](https://aviyel.com/assets/uploads/files/1635219041246-image.png)
```javascript
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".
![Booleans](https://aviyel.com/assets/uploads/files/1635219241132-image.png)

```javascript
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.
![Null](https://aviyel.com/assets/uploads/files/1635219324063-image.png)

```javascript
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.

![Undefined](https://aviyel.com/assets/uploads/files/1635219412764-image.png)

```javascript
let name;
console.log(name) // undefined
```

---

## Non-Primitive Data Type:
![Non primitive data type](https://aviyel.com/assets/uploads/files/1635219497610-image.png)

- 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](https://aviyel.com/assets/uploads/files/1635219533954-image-resized.png)

```javascript
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.
![defining function](https://aviyel.com/assets/uploads/files/1635221595719-image-resized.png)

1 . Function Declaration ( Function definition or Function statement):
- name of a function.
- list of parameters to that function.
for example,
```javascript
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,
```javascript
const add = function(a,b){ 
      return a + b; 
};

let x = add(2,3)

console.log(x); // 5
```
Immediately Invocable Functions Expression - IFFEs
```javascript
(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.

```javascript
add(100,200)
sub(200,100)
```
***NOTE:*** Functions must be in scope when they are called, but the function declaration can be hoisted

```javascript
console.log(add(20,90));

function add(a,b){
    return a + b;
}
```

#### Parameters VS Arguments
![Parameter vs arguments](https://aviyel.com/assets/uploads/files/1635221638752-image.png)

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

![objects](https://aviyel.com/assets/uploads/files/1635221674646-image-resized.png)

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

```javascript
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.

```javascript
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"
```javascript
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,

```javascript
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
```javascript
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.

```javascript
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.

```javascript
const details = {
    name: () => {
        console.log("Hello there , Yo!! how are you doing ")
    };
}

details.name();

// Hello there , Yo!! how are you doing
```

##### Object destructuring:

```javascript
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:
```javascript
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.

```javascript
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.

```javascript
// 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.

![Arrays](https://aviyel.com/assets/uploads/files/1635221723058-image.png)

```javascript
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***
```javascript
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**

```javascript

let comics = ['DC', 'Marvel']

console.log(comics)

**Checking the length of an array.**

console.log(comics.length)
```

**Accessing array items using index position**
```javascript
let first = comics[0]
let second = comics[1]
```

**Accessing the last item of an array**
```javascript
let last = comics[comics.length - 1]
```

**Looping an array**
```javascript
comics.forEach(function(item, index, array) {
console.log(item, index)
})
// DC 0
// Marvel 1
```

**Adding Items to an end of an array.**
```javascript
let newLength = comics.push('Capcom')

// ["DC", "Marvel", "Capcom"]
```

**Removing an item from the end of an Array**
```javascript
let last = comics.pop() // remove Capcom 
// ["DC", "Marvel"]
```

**Removing an item from the beginning of an Array**
```javascript
let first = comics.shift() // remove DC from the front
// ["Marvel"]
```

**Adding an item to the beginning of an Array**
```javascript
let newLength = comics.unshift('Nintendo') // add to the front

// ["Nintendo", "Marvel"]
```

**Find the index of an item in the Array**
```javascript
let pos = comics.indexOf('Marvel')

// 1
```

**Removing an item by index position**
```javascript
let removedItem = comics.splice(1, 1) 

// ["Nintendo"]
```

**Removing items from an index position**
```javascript
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**
```javascript
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.

![conditionals](https://aviyel.com/assets/uploads/files/1635221768948-image.png)

#### If-statement
- If the expression is truthy then only the code executes
```javascript
const isOnline = true;

if (isOnline) {
    console.log("Thanos is Online")
}
```

#### else statement
- else block executes if the "if" condition fails.
```javascript
const isOnline = false;

if(isOnline){
console.log("Thanos is Online")
} else{
console.log("Thanos is Not Online")
}
```

### If-else statement
![If else statement](https://aviyel.com/assets/uploads/files/1635221825663-image.png)

**Equal to** 
```javascript
const age = 100;

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

**Not Equal to**
```javascript
const age = 100;

if (age != 100) {
  console.log("true");
} else {
  console.log("wrong");
}
```

**Equal to value and type**
```javascript
const age = 100;

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

**Not Equal to value and type**
```javascript
const age = 100;

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

**Greater than or less than**
```javascript
if (age >= 100) {
  console.log("true");
} else {
  console.log("wrong");
}
if (age < 100) {
  console.log("true");
} else {
  console.log("wrong");
}
```

**If Else statement**
```javascript
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**
```javascript
// 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**
```javascript
if (hisAge > 16 || hisAge < 25) {
  console.log(`${name} he can join the army`);
} else {
  console.log(`${name} cannot run in race`);
}
```

**Ternary operator**
```javascript
console.log(hisAge === 23 ? "Correct" : "Incorrect");
```

**If else without a brace**
```javascript
if (hisAge > 16 || hisAge < 25) console.log(`${name} he can join the army`);
else console.log(`${name} cannot run in race`);
```

### switch-case statement
![Switch case statement](https://aviyel.com/assets/uploads/files/1635193089912-image.png)

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.

```javascript
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
![Comparison operator](https://aviyel.com/assets/uploads/files/1635193196291-image.png)
![Comparison operator](https://aviyel.com/assets/uploads/files/1635193220896-image.png)

```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 comparison**
```javascript
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**
```javascript
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**
```javascript
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**
```javascript
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.

![Terenary operator ](https://aviyel.com/assets/uploads/files/1635193439166-image-resized.png)

> condition ? expressionIfTrue : expressionIfFalse

```javascript
const age = 230

console.log(age === 230 ? "Correct" : "Incorrect");
```

### Logical OR (||) operator
![Locial OR Truth table](https://aviyel.com/assets/uploads/files/1635221866270-image.png)

```javascript
false || false //  false
false || true // true
true || false //  true
true || true // true
```

### Logical AND (&&) operator
![Logical And Truth Table](https://aviyel.com/assets/uploads/files/1635221884213-image.png)

```javascript
false && false //  false
false && true // false
true && false //  false
true && true // true
```

### Loops
![Loops](https://aviyel.com/assets/uploads/files/1635222219644-image.png)

#### For loops
![For Loops](https://aviyel.com/assets/uploads/files/1635268777777-image.png)

```javascript
// For Loops
for (let i = 0; i <= 10; i++) {
    console.log(i);
}
```

**Changing Iteration**
```javascript
for (let i = 0; i <= 10; i++) {
    if (i === 2) {
        console.log("Two");
    }
    console.log(i);
}
```

### Continue the loop (Continue statement)
![continue](https://aviyel.com/assets/uploads/files/1635225296692-image.png)

```javascript
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)***
![Break statement](https://aviyel.com/assets/uploads/files/1635268884670-image.png)

```javascript
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***
```javascript
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***
![Looping through arrays](https://aviyel.com/assets/uploads/files/1635225835261-image-resized.png)
```javascript
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***
![Map](https://aviyel.com/assets/uploads/files/1635226433748-image.png)

```javascript
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***
```javascript
const userBase = {
    firstName: "pramit",
    lastName: "marattha",
    age: 230,
};

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

### While Loops and do-while
***While loop***
![while loops](https://aviyel.com/assets/uploads/files/1635226795656-image.png)
```javascript
let i = 0;
let j = 0;

while (i < 10) {
    console.log("Numbers " + i);
    i++;
}
```

### Do While Loops
![Do While Loops](https://aviyel.com/assets/uploads/files/1635227171901-image.png)

```javascript
do {
    console.log("Numbers " + j);
    j++;
} while (j < 10);
```

#### Endless loop
```javascript
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
```javascript
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
```javascript
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
```javascript
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***
![return](https://aviyel.com/assets/uploads/files/1635227735930-image.png)
```javascript
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
```javascript
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
![Error Handling](https://aviyel.com/assets/uploads/files/1635228064681-image.png)

**Catch all exception**
```javascript
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**
```javascript
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***
```javascript
function simepleExeption() {}

function exception(name, message) {
    this.name = name;
    this.message = message;
}

throw new exception("exception", "this is a message");
```

## Scope

![Scope](https://aviyel.com/assets/uploads/files/1635228910284-image-resized.png)

**Global scope**
```javascript
// Global Scope
var a = 1;
let b = 22;
const c = 333;
```

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

check();
```

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

**Loop block Scope**
```javascript
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.

![JavaScript classes](https://aviyel.com/assets/uploads/files/1635229298746-image.png)

### Class Declaration
```javascript
class sum {
    constructor(numberA, numberB) {
        this.numberA = numberA;
        this.numberB = numberB;
    }
}
```

### Class Expression

#### named expression
```javascript
let Sum = class sumTwo {
    constructor(numberA, numberB) {
        this.numberA = numberA;
        this.numberB = numberB;
    }
};
console.log(Sum.name);
// output: "sumTwo"
```
#### unnamed expression
```javascript
let Sum = class {
    constructor(numberA, numberB) {
        this.numberA = numberA;
        this.numberB = numberB;
    }
};
console.log(Sum.name);

// output: "Sum";
```

## Prototype Method
```javascript
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.

![Binding this](https://aviyel.com/assets/uploads/files/1635229476127-image.png)

```javascript
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.
```javascript
class Sum {
    numberA = 0;
    numberB;
    constructor(numberA, numberB) {
        this.numberA = numberA;
        this.numberB = numberB;
    }
}
```

### private field declaration.
```javascript
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.

![Extend Keywords](https://aviyel.com/assets/uploads/files/1635230109365-image.png)

```javascript
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:

![super](https://aviyel.com/assets/uploads/files/1635230008552-image.png)

The super keyword is used to access and call functions on an object's parent.
```javascript
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:
![Iterators](https://aviyel.com/assets/uploads/files/1635230874357-image-resized.png)
- 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().

```javascript
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:

```javascript
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](https://aviyel.com/assets/uploads/files/1635231565054-image.png)

- 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.
```javascript
function *thisIsGenerator(){

}
```
- To create generators in an anonymous function you need to add (*) at the end of the function itself
```javascript
function* (){
}
```

- The "yield" keyword in generators behaves the same as an await in promises.
```javascript
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.

![callbacks](https://aviyel.com/assets/uploads/files/1635232095683-image-resized.png)

- Callback function
```javascript
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

```javascript
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.

![callback hell](https://aviyel.com/assets/uploads/files/1635197850262-image.png)

```javascript
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.

![promises](https://aviyel.com/assets/uploads/files/1635232360938-image-resized.png)

**Creating a promise**
```javascript
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,

```javascript
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
![Promise Chaining](https://aviyel.com/assets/uploads/files/1635259638336-image-resized.png)

```javascript
someApiCall().then((result) => {
    return someAnotherApiCall();
}).then((result2) => {
    return someAnotherNextApiCall();
}).then((result3) => {
    // do something
}).catch((error) => {
    console.error(error)
});

```

### Async-Await:

![Async Await](https://aviyel.com/assets/uploads/files/1635233583000-image-resized.png)

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

```javascript
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,

```javascript
let promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("Promise is resolved");
    }, 1000);
});

const asynchronousFunction = async () => {
    let result = await promise;
    console.log(result);
};

asynchronousFunction();

```

![code demo](https://aviyel.com/assets/uploads/files/1635232733635-image.png)


---


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](https://twitter.com/AviyelHq) or [sign-up](https://aviyel.com/discussions) 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](https://discord.gg/TbfZmbvnN5)

Twitter =>[https://twitter.com/AviyelHq]