DEV Community

Cover image for Modern JavaScript explained in a way you've never seen before 🔥
Pramit Marattha for Aviyel Inc

Posted on • Updated on • Originally published at aviyel.com

Modern JavaScript explained in a way you've never seen before 🔥

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)

Enter fullscreen mode Exit fullscreen mode

variables

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

var

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

name = "pramit armpit";
console.log(name);
Enter fullscreen mode Exit fullscreen mode

Initialzing the variables

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

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
Enter fullscreen mode Exit fullscreen mode

Multiword variables

// multi word variables
let firstName = "thanos"; // camel casing
let first_name = "promear"; // underscore convention
let FirstName = "yolomeat"; // pascal case
Enter fullscreen mode Exit fullscreen mode

let

// let
let name = "Brad pitt";
console.log(name);
name = "Christain Bale";
console.log(name);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

console.log()

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");
Enter fullscreen mode Exit fullscreen mode

Data Types:

Primitive Data Type:

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.

strings

let someString = "This is a string";
const stringTwo = "This is also a string"
let stringThree = "123456789011223344";
let stringSingleQuote = 'This is single quote string'
Enter fullscreen mode Exit fullscreen mode

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

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
`
Enter fullscreen mode Exit fullscreen mode

Numbers:

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

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);
Enter fullscreen mode Exit fullscreen mode
  • 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);
Enter fullscreen mode Exit fullscreen mode

Airthematic operators.

1 . Additional operator:
additional Operator

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);
Enter fullscreen mode Exit fullscreen mode

NOTE: JavaScript is a dynamically typed language, which means that the type can be changed on the fly.

Static vs dynamic

  • Adding Number to String:
const numberOne = 100;
const stringOne = "100",
console.log(numberOne + stringOne);
Enter fullscreen mode Exit fullscreen mode

2 . Subtraction operator
Subtraction

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

// Subtraction
console.group("Substration");
console.log(a - b);
console.log(b - c);
console.groupEnd();
Enter fullscreen mode Exit fullscreen mode

3 . Multiplication Operator

Multiplication

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

// Multiplication
console.group("Multiplication");
console.log(b * c);
console.log(a * b);
console.groupEnd();
Enter fullscreen mode Exit fullscreen mode

4 . Division Operator
Modulus Operator

const a = 1000,
    b = 100,
    c = 3;

// Division
console.group("Modulus");
console.log(b % c);
console.log(a % b);
console.groupEnd();
Enter fullscreen mode Exit fullscreen mode

5 . Increment Operator
Increment Operator

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();
Enter fullscreen mode Exit fullscreen mode

6 . Decrement Operator
Decrement Operator

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();
Enter fullscreen mode Exit fullscreen mode

Booleans:

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

let isOpenSource;
isOpenSource = true;
isOpenSource = false;

//result
console.log(isOpenSource);
Enter fullscreen mode Exit fullscreen mode

Null:

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

let existence = null;

//result
console.log(existence);
Enter fullscreen mode Exit fullscreen mode

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

let name;
console.log(name) // undefined
Enter fullscreen mode Exit fullscreen mode

Non-Primitive Data Type:

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

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))
Enter fullscreen mode Exit fullscreen mode

Defining Functions:

A function is a reusable set of statements to perform a task or calculate a value.
defining function

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
};
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

Parameters VS Arguments

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

objects

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
}
Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

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
 */
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode
Shortcut technique for Object Creations:
const name = "Thanos";

const details = {name};

console.log(details) // { name: 'Thanos' }
Enter fullscreen mode Exit fullscreen mode
“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
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

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

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)
Enter fullscreen mode Exit fullscreen mode

Mixed Array

const mixedArray = [1,"my",2,"name",8,"is",7,"pramit",true,false]

//result
console.log(mixedArray)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Accessing array items using index position

let first = comics[0]
let second = comics[1]
Enter fullscreen mode Exit fullscreen mode

Accessing the last item of an array

let last = comics[comics.length - 1]
Enter fullscreen mode Exit fullscreen mode

Looping an array

comics.forEach(function(item, index, array) {
console.log(item, index)
})
// DC 0
// Marvel 1
Enter fullscreen mode Exit fullscreen mode

Adding Items to an end of an array.

let newLength = comics.push('Capcom')

// ["DC", "Marvel", "Capcom"]
Enter fullscreen mode Exit fullscreen mode

Removing an item from the end of an Array

let last = comics.pop() // remove Capcom 
// ["DC", "Marvel"]
Enter fullscreen mode Exit fullscreen mode

Removing an item from the beginning of an Array

let first = comics.shift() // remove DC from the front
// ["Marvel"]
Enter fullscreen mode Exit fullscreen mode

Adding an item to the beginning of an Array

let newLength = comics.unshift('Nintendo') // add to the front

// ["Nintendo", "Marvel"]
Enter fullscreen mode Exit fullscreen mode

Find the index of an item in the Array

let pos = comics.indexOf('Marvel')

// 1
Enter fullscreen mode Exit fullscreen mode

Removing an item by index position

let removedItem = comics.splice(1, 1) 

// ["Nintendo"]
Enter fullscreen mode Exit fullscreen mode

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' ]
Enter fullscreen mode Exit fullscreen mode

Copy an Array

let shallowCopy = comics.slice() // this is how to make a copy
// or
let copyArray = [...comics]
Enter fullscreen mode Exit fullscreen mode

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

If-statement

  • If the expression is truthy then only the code executes
const isOnline = true;

if (isOnline) {
    console.log("Thanos is Online")
}
Enter fullscreen mode Exit fullscreen mode

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")
}
Enter fullscreen mode Exit fullscreen mode

If-else statement

If else statement

Equal to

const age = 100;

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

Not Equal to

const age = 100;

if (age != 100) {
  console.log("true");
} else {
  console.log("wrong");
}
Enter fullscreen mode Exit fullscreen mode

Equal to value and type

const age = 100;

if (age === 100) {
  console.log("true");
} else {
  console.log("wrong");
}
Enter fullscreen mode Exit fullscreen mode

Not Equal to value and type

const age = 100;

if (age === 100) {
  console.log("true");
} else {
  console.log("wrong");
}
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

OR operator

if (hisAge > 16 || hisAge < 25) {
  console.log(`${name} he can join the army`);
} else {
  console.log(`${name} cannot run in race`);
}
Enter fullscreen mode Exit fullscreen mode

Ternary operator

console.log(hisAge === 23 ? "Correct" : "Incorrect");
Enter fullscreen mode Exit fullscreen mode

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`);
Enter fullscreen mode Exit fullscreen mode

switch-case statement

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!!!!!!!!!");
    }
}
Enter fullscreen mode Exit fullscreen mode

Comparison operator

  • Compares two value and return either true or false Comparison operator Comparison operator
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();
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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

condition ? expressionIfTrue : expressionIfFalse

const age = 230

console.log(age === 230 ? "Correct" : "Incorrect");
Enter fullscreen mode Exit fullscreen mode

Logical OR (||) operator

Locial OR Truth table

false || false //  false
false || true // true
true || false //  true
true || true // true
Enter fullscreen mode Exit fullscreen mode

Logical AND (&&) operator

Logical And Truth Table

false && false //  false
false && true // false
true && false //  false
true && true // true
Enter fullscreen mode Exit fullscreen mode

Loops

Loops

For loops

For Loops

// For Loops
for (let i = 0; i <= 10; i++) {
    console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

Changing Iteration

for (let i = 0; i <= 10; i++) {
    if (i === 2) {
        console.log("Two");
    }
    console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

Continue the loop (Continue statement)

continue

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);
Enter fullscreen mode Exit fullscreen mode

Breaking the loop (Break statement)
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);
Enter fullscreen mode Exit fullscreen mode

Looping through arrays

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

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

Looping through arrays using forEach
Looping through arrays

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

namesTwo.forEach((nam, index, array) => {
    console.log(`${index} : ${nam}`);
    console.log(array);
});
Enter fullscreen mode Exit fullscreen mode

Looping through arrays of objects using the map
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);
Enter fullscreen mode Exit fullscreen mode

For in loop used in Objects

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

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

While Loops and do-while

While loop
while loops

let i = 0;
let j = 0;

while (i < 10) {
    console.log("Numbers " + i);
    i++;
}
Enter fullscreen mode Exit fullscreen mode

Do While Loops

Do While Loops

do {
    console.log("Numbers " + j);
    j++;
} while (j < 10);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

return statement
return

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
);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Error handling

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);
}
Enter fullscreen mode Exit fullscreen mode

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");
    }
}
Enter fullscreen mode Exit fullscreen mode

Define Exception Type

function simepleExeption() {}

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

throw new exception("exception", "this is a message");
Enter fullscreen mode Exit fullscreen mode

Scope

Scope

Global scope

// Global Scope
var a = 1;
let b = 22;
const c = 333;
Enter fullscreen mode Exit fullscreen mode

Functional Scope

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

check();
Enter fullscreen mode Exit fullscreen mode

If block scope

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

Loop block Scope

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

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

Class Declaration

class sum {
    constructor(numberA, numberB) {
        this.numberA = numberA;
        this.numberB = numberB;
    }
}
Enter fullscreen mode Exit fullscreen mode

Class Expression

named expression

let Sum = class sumTwo {
    constructor(numberA, numberB) {
        this.numberA = numberA;
        this.numberB = numberB;
    }
};
console.log(Sum.name);
// output: "sumTwo"
Enter fullscreen mode Exit fullscreen mode

unnamed expression

let Sum = class {
    constructor(numberA, numberB) {
        this.numberA = numberA;
        this.numberB = numberB;
    }
};
console.log(Sum.name);

// output: "Sum";
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

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
Enter fullscreen mode Exit fullscreen mode

Field declaration:

public field declaration.

class Sum {
    numberA = 0;
    numberB;
    constructor(numberA, numberB) {
        this.numberA = numberA;
        this.numberB = numberB;
    }
}
Enter fullscreen mode Exit fullscreen mode

private field declaration.

class Sum {
    #numberA = 0;
    #numberB;
    constructor(numberA, numberB) {
        this.#numberA = numberA;
        this.#numberB = numberB;
    }
}
Enter fullscreen mode Exit fullscreen mode

Subclassing with extends

  • extends is used to create a class of another class.

Extend Keywords

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.
Enter fullscreen mode Exit fullscreen mode

Superclass call with super keyword:

super

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.
Enter fullscreen mode Exit fullscreen mode

Iterators:

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;
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Generators:

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

}
Enter fullscreen mode Exit fullscreen mode
  • To create generators in an anonymous function you need to add (*) at the end of the function itself
function* (){
}
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

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

  • Callback function
function one(call_two) {
    console.log("step one");
    call_two();
}

function two() {
    console.log("step two");
}

one(two);

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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

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);
Enter fullscreen mode Exit fullscreen mode

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

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)
Enter fullscreen mode Exit fullscreen mode

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]}`));
Enter fullscreen mode Exit fullscreen mode

Promise chaining

Promise Chaining

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

Enter fullscreen mode Exit fullscreen mode

Async-Await:

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;
}
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

code demo


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)

Collapse
 
romanost2020 profile image
RomanOst2020 • Edited

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

Collapse
 
pramit_marattha profile image
Pramit Marattha

Thankss!! I think I just misplaced the number order.. I am fixing it right now !!

Collapse
 
manojk7mech profile image
manojk7mech

Thank you this is very helpful...

Collapse
 
pramit_marattha profile image
Pramit Marattha

Thanks !! Fixing it right now !!

Collapse
 
sergei profile image
Sergei Sarkisian • Edited

The variable should also be declared using "const." It cannot be redefined and can only have a fixed value.

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

Collapse
 
marlonla profile image
Marlon Amâncio

Very good work and helpful! congratulations and thanks!

Collapse
 
jzombie profile image
jzombie

I like the artwork. Curious as to what you used to create it.