├── CONTRIBUTING.md
├── 1_variables_and_data_types
├── null_and_undefined.js
├── Numbers.js
├── Variables.js
├── objects.js
├── Strings.js
└── variablesDataTypes.md
├── 10_DOM
├── script.js
├── index.html
└── dom.md
├── LEARN.md
├── 2_Operators
├── index.html
├── ArithmeticOperators.js
├── comparisonOperators.js
└── Operators.md
├── 8_Objects_in_detail
├── objects2.js
├── object.js
└── objects.md
├── 3_Logic_and_Control_flow
├── Loops.js
├── switch.js
├── Logical_operators.js
├── Truthy_and_falsy_values.js
└── LogicAndControlFlow.md
├── 6_Strings_in_detail
├── Exercise.js
├── strings_2.js
├── string.js
└── strings.md
├── 5_Hoisting_and_Closure
├── Hoisting.js
├── Closure.js
└── HoistingAndClosure.md
├── 4_Functions
├── scope.js
├── ArrowFunction.js
├── TypesOfFunctions.js
└── Functions.md
├── README.md
├── 7_Arrays_in_detail
├── Arrays.js
├── Arrays_2.js
├── Arrays_3.js
└── Arrays.md
├── 11_Classes_this_and_new_keyword
├── script.js
└── 11.md
├── 12_Asynchronous_Concepts
├── script.js
├── script2.js
└── 12.md
├── 9_Value_vs_Reference
├── script.js
└── value_vs_reference.md
└── LICENSE
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | ## Steps to Contribute :
2 |
3 | 1. Feel free to open a pull request of any learnings that I might have missed.
4 | 2. Document it appropriately.
--------------------------------------------------------------------------------
/1_variables_and_data_types/null_and_undefined.js:
--------------------------------------------------------------------------------
1 | // Null
2 | // Null is assigning a value i.e nothing
3 | const age = null;
4 | console.log(age);
5 |
6 | // when you don't assign any value to the variable then it becomes undefined.
7 | let firstName;
8 | console.log(firstName);
9 |
--------------------------------------------------------------------------------
/10_DOM/script.js:
--------------------------------------------------------------------------------
1 | const menuClicked = (currEl) => {
2 | const menuItems = document.getElementsByClassName("menu-item");
3 |
4 | for (let i = 0; i < menuItems.length; i++) {
5 | menuItems[i].classList.remove("active");
6 | }
7 |
8 | currEl.classList.add("active");
9 | };
10 |
--------------------------------------------------------------------------------
/LEARN.md:
--------------------------------------------------------------------------------
1 | ## How did I build this repo ?
2 |
3 | I started learning key concepts of JavaScript from all the online resources available. Mainly, I went through [JSM's video](https://www.youtube.com/watch?v=g7T23Xzys-A) on crash course in Javascript and documented my learning at each step. One book I referred mainly was Eloquent Javascript by Marijn Haverbeke.
--------------------------------------------------------------------------------
/2_Operators/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Operators
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/8_Objects_in_detail/objects2.js:
--------------------------------------------------------------------------------
1 | const dog = {
2 | name: "Fluffy",
3 | bark: () => {
4 | console.log("woof,woof");
5 | },
6 | };
7 |
8 | dog.bark(); // woof,woof
9 |
10 | // this keyword
11 | const car = {
12 | name: "Lambo",
13 | model: 2019,
14 | Details: function () {
15 | console.log(this.name, this.model);
16 | },
17 | };
18 |
19 | car.Details(); // Lambo 2019
20 |
21 |
--------------------------------------------------------------------------------
/1_variables_and_data_types/Numbers.js:
--------------------------------------------------------------------------------
1 | // Numbers - Integers, Fractions
2 |
3 | const firstNumber = 12;
4 | const secondNumber = 27;
5 |
6 | const result = firstNumber + secondNumber;
7 |
8 | console.log(result);
9 |
10 | // Boolean - True / False
11 |
12 | const isCool = true;
13 |
14 | const age = 22;
15 |
16 | if (age >= 18) {
17 | console.log("You are Good to drive");
18 | } else {
19 | console.log("You are very young to drive");
20 | }
21 |
--------------------------------------------------------------------------------
/2_Operators/ArithmeticOperators.js:
--------------------------------------------------------------------------------
1 | const a = 5;
2 | const b = 10;
3 | let result = 0;
4 |
5 | // Addition
6 | result = a + b;
7 |
8 | // Subtraction
9 | result = a - b;
10 |
11 | // Multiplication
12 | result = a * b;
13 |
14 | // Division
15 | result = a / b;
16 |
17 | // Exponent
18 | result = b ** a;
19 |
20 | // Modulo
21 | result = a % b;
22 |
23 | // Increment and Decrement
24 | result++;
25 | result--;
26 |
27 | console.log(result);
28 |
--------------------------------------------------------------------------------
/3_Logic_and_Control_flow/Loops.js:
--------------------------------------------------------------------------------
1 | // while loop, generally it looks like this,
2 | // while (condition){
3 | // block of code;
4 | // }
5 | // The while loop loops through a block of code as long as a specified condition is true
6 |
7 | let i = 0;
8 |
9 | while (i < 10) {
10 | console.log(i);
11 | i++;
12 | }
13 |
14 | // for loop
15 | // for([initialisation]; [condition];[final-expression]){
16 | // block of code;
17 | // }
18 |
19 | for (let i = 1; i < 10; i++) {
20 | console.log(i);
21 | }
22 |
--------------------------------------------------------------------------------
/1_variables_and_data_types/Variables.js:
--------------------------------------------------------------------------------
1 | // JavaScript has 3 ways of declaring a variable
2 | // 1. Using var
3 | // 2. Using let
4 | // 3. Using const ( Read Only )
5 |
6 | // There are some rules to declare variable names
7 | // 1. Do not use existing JS keywords
8 | // 2. You cannot use any special character while naming a variable other then _ and $
9 |
10 | var variableName = "Welcome to Variables";
11 |
12 | console.log(variableName);
13 |
14 | variableName = "Hello World";
15 |
16 | console.log(variableName);
17 |
--------------------------------------------------------------------------------
/1_variables_and_data_types/objects.js:
--------------------------------------------------------------------------------
1 | // Objects
2 | // An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method
3 |
4 | // const Person = {
5 | // name: "Shubham",
6 | // age: 21,
7 | // };
8 |
9 | // console.log(typeof Person);
10 |
11 | const arr = [1, 2, 3, 4];
12 | console.log(typeof arr);
13 |
14 | // date is an object;
15 | const date = new Date();
16 | console.log(typeof date);
17 |
--------------------------------------------------------------------------------
/10_DOM/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | DOM
8 |
9 |
10 |
11 | - Maths
12 | - Science
13 | - English
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/6_Strings_in_detail/Exercise.js:
--------------------------------------------------------------------------------
1 | const guestList = "Our guests are: emma, jacob, isabella, ethan";
2 |
3 | const guestListLength = guestList.length;
4 | console.log(guestListLength);
5 |
6 | const upperCasedGuestList = guestList.toUpperCase();
7 | console.log(upperCasedGuestList);
8 |
9 | const isEthanOnTheList = upperCasedGuestList.includes("ETHAN");
10 | console.log(isEthanOnTheList);
11 |
12 | const subStringGuests = upperCasedGuestList.slice(16, guestList.length);
13 | console.log(subStringGuests);
14 |
15 | const guests = subStringGuests.split(" ");
16 | console.log(guests);
17 |
18 |
19 |
--------------------------------------------------------------------------------
/5_Hoisting_and_Closure/Hoisting.js:
--------------------------------------------------------------------------------
1 | // Hoisting in JavaScript
2 | // Bringing the variables to the top of the scope.
3 | // Only the variable declaration gets to the top
4 |
5 | // console.log(age);
6 |
7 | // var age = 12;
8 |
9 | // hoist();
10 |
11 | // The function will be executed even
12 | // if the function call is done before the function declaration
13 | // function hoist() {
14 | // var message = "test";
15 | // console.log(message);
16 | // }
17 |
18 | // console.log(num);
19 | // const num = 23;
20 |
21 | hoist();
22 |
23 | var hoist = () => {
24 | var message = "test";
25 | console.log(message);
26 | };
27 |
--------------------------------------------------------------------------------
/1_variables_and_data_types/Strings.js:
--------------------------------------------------------------------------------
1 | // Strings
2 | // String is a dataype used to represent text
3 | const exampleString = "Hello, World!";
4 | console.log(exampleString);
5 |
6 | // There are 3 ways of representing a string
7 |
8 | const singleQuote = 'Hello';
9 | const doubleQuote = "Hello";
10 | // We can use singleQuote or doubleQuote if we just want to statically display it.
11 |
12 | const userName = "Shubham";
13 | // We can use backTick for extended functionality such as dynamically changing it when required.
14 | // ${} this is called a template literal
15 | const backTick = `Hello, ${userName}`;
16 |
17 | console.log(backTick);
18 |
19 | const exampleBackTick = `${3 + 2}`;
20 |
21 | console.log(exampleBackTick);
22 |
--------------------------------------------------------------------------------
/5_Hoisting_and_Closure/Closure.js:
--------------------------------------------------------------------------------
1 | // Closures in JavaScript
2 |
3 | // const outer = () => {
4 | // const outerVar = "Hello";
5 |
6 | // const inner = () => {
7 | // const innervar = "Hi";
8 | // console.log(outerVar, innervar);
9 | // };
10 | // return inner;
11 | // };
12 |
13 | // const innerFunc = outer();
14 |
15 | // innerFunc();
16 |
17 | const init = () => {
18 | const hobby = "Learning JavaScript"; // Local variable created by init function
19 |
20 | const displayHobby = () => {
21 | // displayHobby is the inner function, a closer
22 | console.log(hobby); // using a variable created in the parent function
23 | };
24 |
25 | displayHobby();
26 | };
27 |
28 | init();
29 |
--------------------------------------------------------------------------------
/4_Functions/scope.js:
--------------------------------------------------------------------------------
1 | // Scope
2 | // There are 3 types of scope
3 | // 1. Global Scope
4 | // 2. Function Scope
5 | // 3. Block Scope
6 |
7 | // Global Scope
8 | // const firstName = "Shubham";
9 | // const GlobalScope = () => {
10 | // console.log(firstName);
11 | // };
12 |
13 | // GlobalScope();
14 |
15 | // Local Scope
16 |
17 | const someFunction = () => {
18 | let firstName = "John";
19 | console.log(firstName);
20 |
21 | const someFunction2 = () => {
22 | console.log(firstName);
23 | };
24 |
25 | someFunction2();
26 | };
27 |
28 | someFunction();
29 |
30 | // Block Scope
31 |
32 | if (true) {
33 | var firstName = "Jane";
34 | }
35 |
36 | console.log(firstName);
37 |
38 | // Declaring a variable with var inside a blockscope can also let you access the variable in global scope.
--------------------------------------------------------------------------------
/4_Functions/ArrowFunction.js:
--------------------------------------------------------------------------------
1 | // Arrow function
2 |
3 | const square = (number) => {
4 | return number * number;
5 | };
6 |
7 | // A short hand to declare arrow function if there is just one statement in the function:
8 | const square1 = (number) => number * number;
9 |
10 | const result = square(3);
11 | console.log(result);
12 |
13 | // Difference between parameters and arguments
14 | // Paramters => used when defining a function
15 | // Arguments => passed when making a function call
16 | // E.g.
17 |
18 | const sayHi = (name, age = 0) => {
19 | // By default the we can make value of age will be 0, to avoid undefined as a result when age is not being passed.
20 |
21 | // name is a paramter
22 | console.log(`Hi ${name}, you are ${age} years old!`);
23 | };
24 |
25 | sayHi("Shubham"); // 'Shubham' is an argument value that is being passed
26 |
--------------------------------------------------------------------------------
/3_Logic_and_Control_flow/switch.js:
--------------------------------------------------------------------------------
1 |
2 | // The switch statement is used to perform different actions based on different conditions
3 | // syntax ,
4 | // switch (condition){
5 | // case 'xyz':
6 | // block of code;
7 | // break;
8 |
9 | // case 'abc':
10 | // block of code;
11 | // break;
12 | // }
13 |
14 |
15 |
16 | const superHero = "Batman";
17 |
18 | switch (superHero) {
19 | case "Captain America":
20 | console.log("Never give up!");
21 | break;
22 |
23 | case "Iron Man":
24 | console.log("I am Iron Man!");
25 | break;
26 |
27 | case "Thor":
28 | console.log("That is my hammer!");
29 | break;
30 |
31 | case "Black Widow":
32 | console.log("One shot, one kill");
33 | break;
34 |
35 | default:
36 | console.log("Enter a valid superhero name");
37 | }
38 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Crash Course on JavaScript
2 |
3 | 
4 |
5 | ## Contents -
6 |
7 | - #### [Variables and Data Types](/1_variables_and_data_types/variablesDataTypes.md)
8 | - #### [Operators](/2_Operators/Operators.md)
9 | - #### [Logic and Control Flow](/3_Logic_and_Control_flow/LogicAndControlFlow.md)
10 | - #### [Functions](/4_Functions/Functions.md)
11 | - #### [Hoisting and Closures](/5_Hoisting_and_Closure/HoistingAndClosure.md)
12 | - #### [Strings in Detail](/6_Strings_in_detail/strings.md)
13 | - #### [Arrays in Detail](/7_Arrays_in_detail/Arrays.md)
14 | - #### [Objects in Detail](/8_Objects_in_detail/objects.md)
15 | - #### [Value vs Reference](/9_Value_vs_Reference/value_vs_reference.md)
16 | - #### [DOM](/10_DOM/dom.md)
17 | - #### [Classes, this and new keyword](/11_Classes_this_and_new_keyword/11.md)
18 | - #### [Asynchronous Concepts](/12_Asynchronous_Concepts/12.md)
19 |
--------------------------------------------------------------------------------
/3_Logic_and_Control_flow/Logical_operators.js:
--------------------------------------------------------------------------------
1 | // The below line of code outputs 999,
2 | // because it evaluates from left to right and
3 | // it returns the last true value in the condition
4 | console.log("truthy" && 1 && "test" && 999);
5 |
6 | // The below line of code outputs 0,
7 | // because there is one false value in the
8 | // entire condition and it will always return 0
9 | console.log("truthy" && 0 && "test" && 999);
10 |
11 | // For OR operator
12 | // The below line returns "truthy" because,
13 | // when the first value of the condition is true,
14 | // it doesn't check rest of the values.
15 | console.log("truthy" || 0 || "test" || 999);
16 |
17 | // The below line returns undefined,
18 | // because it checks all the values and
19 | // when all values are false, it returns the last one
20 | console.log("" || 0 || null || undefined);
21 |
22 | // NOT operator
23 | const value = "";
24 |
25 | if (!!value) {
26 | console.log("Value is truthy");
27 | } else {
28 | console.log("Value is falsy");
29 | }
30 |
--------------------------------------------------------------------------------
/2_Operators/comparisonOperators.js:
--------------------------------------------------------------------------------
1 | // Comparison Operators ==> true / false
2 |
3 | const a = 5;
4 | const b = 10;
5 |
6 | // Greater than
7 | console.log(a > b);
8 |
9 | // Greater than equal to
10 | console.log(a >= b);
11 |
12 | // Less than
13 | console.log(a < b);
14 |
15 | // Less than equal to
16 | console.log(a <= b);
17 |
18 | // Loose equality
19 | // Doesn't compare the DATA TYPES
20 | console.log(a == b);
21 |
22 | // Not equal
23 | console.log(a != b);
24 |
25 | // Strict Equality
26 | // Compares VALUES and DATA TYPES
27 | // Returns true only if both are the same
28 | console.log(a === b);
29 |
30 | // Strict Inequality
31 | console.log(a !== b);
32 |
33 |
34 |
35 | // Logical Operators
36 | // AND && => ALL OPERANDS ARE TRUE => TRUE
37 | console.log(true && true && true);
38 | // OR || => ATLEAST ONE OPERAND IS TRUE => TRUE
39 | console.log(true || false);
40 | // NOT ! => Reverses the Boolean value
41 | console.log(!true);
42 |
43 | // Assignment Operator
44 | let num = 34;
45 | num += 2;
46 | console.log(num);
47 |
--------------------------------------------------------------------------------
/3_Logic_and_Control_flow/Truthy_and_falsy_values.js:
--------------------------------------------------------------------------------
1 | // If condition
2 |
3 | // if (condition){
4 | // block of code
5 | // }
6 |
7 | // const age = 8;
8 |
9 | // if (age > 18) {
10 | // console.log("You may enter");
11 | // } else if (age === 18) {
12 | // console.log("Welcome, You just turned 18!");
13 | // } else {
14 | // console.log("Grow up");
15 | // }
16 |
17 | // FALSY VALUES - Excluding them all other values are TRUTHY VALUES
18 | // false
19 | // 0
20 | // ''
21 | // null
22 | // undefined
23 | // NaN
24 |
25 | // SOME TRUTHY VALUES
26 | // true
27 | // 1
28 | // "hello"
29 | // 27 (any number)
30 | // {} // empty object is also considered to be true
31 | // [] // empty array is also considered to be true
32 |
33 | const stars = 5;
34 |
35 | if (stars) {
36 | console.log(`Congrats,you have ${stars} stars`);
37 | } else {
38 | console.log("You don't have any stars");
39 | }
40 |
41 | // Ternary operator
42 | // Syntax ,
43 | // (condition) ? // true : // false
44 | const age = 1;
45 |
46 | age > 18 ? console.log("You may drive") : console.log("You cannot drive yet!");
47 |
--------------------------------------------------------------------------------
/4_Functions/TypesOfFunctions.js:
--------------------------------------------------------------------------------
1 | // Functions
2 | // A BLOCK OF CODE ==> PERFORMS A TASK
3 |
4 | // There are multiple ways of function declaration,
5 | // A function declaration(defining a fuction)
6 | // function name(params){
7 | // statements
8 | //}
9 | // The advantage of using a function declaration is having an access
10 | // to 'this' keyword.
11 |
12 | // A function expression
13 | // const name = function(params){
14 | //statements
15 | // }
16 |
17 | // A arrow function
18 | // const name = (params) => {
19 | // statements
20 | // };
21 |
22 | // function square(number) {
23 | // return number * number;
24 | // }
25 |
26 | // FUNCTION CALL (calling / executing a function)
27 | // const ans = square(6);
28 | // console.log(ans);
29 |
30 | // function sayHi(name){
31 | // console.log(`Hi, ${name}`);
32 | // }
33 |
34 | // sayHi('Shubham');
35 |
36 | // The below function will print the sum and return undefined
37 | // function add(a, b) {
38 | // console.log(a + b);
39 | // }
40 |
41 | // const ans = add(3, 3);
42 |
43 | // Undefined will be printed out
44 | // console.log(ans);
45 |
46 |
--------------------------------------------------------------------------------
/7_Arrays_in_detail/Arrays.js:
--------------------------------------------------------------------------------
1 | // Arrays Introduction
2 | // let months = ["January", "February", "March", "April"];
3 |
4 | // for (let i = 0; i < months.length; i++) {
5 | // console.log(months[i]);
6 | // }
7 |
8 | const names = ["John", "Bob", "David", "Mark"];
9 |
10 | // Array Push - Adds a new element containing
11 | // the enetered value to the end of the array
12 | names.push("Shubham");
13 | console.log(names);
14 |
15 | // Array Pop - Deletes the last element of an array
16 | names.pop();
17 | console.log(names);
18 |
19 | // Array Shift - deletes the first element of the array
20 | names.shift();
21 | console.log(names);
22 |
23 | // Array Unshift - adds the new value to the start of the array
24 | names.unshift("Samarth");
25 | console.log(names);
26 |
27 | // Array Splice - It adds or removes values in any position of an array
28 | names.splice(2, 0, "Divyanshi", "Ayushi");
29 | console.log(names);
30 |
31 | names.splice(2, 2);
32 | console.log(names);
33 |
34 | // Array Slice - Copies certain part of an array into a newly created array
35 | const noOneLikesSam = names.slice(1);
36 | console.log(noOneLikesSam);
37 |
--------------------------------------------------------------------------------
/11_Classes_this_and_new_keyword/script.js:
--------------------------------------------------------------------------------
1 | // The new keyword
2 | // The new keyword creates an object of num
3 | // which then let's us access to various methods,
4 | // like .toFixed() in the below code.
5 | // const num = new Number(100.25);
6 |
7 | // console.log(num.toFixed(0)); // 100
8 |
9 | // const person = {
10 | // name: "John",
11 | // getName() {
12 | // console.log(this);
13 | // },
14 | // };
15 |
16 | // person.getName(); // { name: 'John', getName: [Function: getName] }
17 |
18 | // Class is a schema for
19 | // an object that can save
20 | // many values
21 |
22 | // class Person {
23 | // constructor(name, age, isWorking) {
24 | // this.name = name;
25 | // this.age = age;
26 | // this.isWorking = isWorking;
27 | // }
28 | // }
29 |
30 | // const user = new Person("John", 22, true);
31 |
32 | // console.log(user);
33 |
34 | // How can we do the same thing above using
35 | // arrow function ?
36 |
37 | const createPerson = (name, age, isWorking) => ({ name, age, isWorking });
38 |
39 | const user1 = createPerson("Shubham", 23, false);
40 | console.log(user1);//{ name: 'Shubham', age: 23, isWorking: false }
41 |
--------------------------------------------------------------------------------
/12_Asynchronous_Concepts/script.js:
--------------------------------------------------------------------------------
1 | // Asynchronous Code
2 |
3 | // setInterval
4 | // clearInterval
5 | // const myInterval = setInterval(() => console.log("Hello, world!"), 2000);
6 | // clearInterval(myInterval);
7 |
8 | // setTimeout
9 | // clearTimeout
10 | // const myTimeout = setTimeout(() => console.log("Lets play"), 5000);
11 |
12 | // console.log("logging in the bottom");
13 |
14 | // Synchronous Code
15 | // const functionOne = () => {
16 | // console.log("Function One"); // 1
17 |
18 | // functionTwo();
19 |
20 | // console.log("Function One, Part two"); // 3
21 | // };
22 |
23 | // const functionTwo = () => {
24 | // console.log("Function two"); // 2
25 | // };
26 |
27 | const functionOne = () => {
28 | console.log("Function One"); // 1
29 |
30 | functionTwo();
31 |
32 | console.log("Function One, Part two"); // 2
33 | };
34 |
35 | const functionTwo = () => {
36 | setTimeout(() => console.log("Function two"), 2000); // 3
37 | };
38 |
39 | functionOne();
40 |
41 | // callbacks;
42 |
43 | const cart = ["Shoes", "Shirt", "Pant"];
44 |
45 | const Promise = createOrder(cart);
46 |
47 | Promise.then((orderId) => {
48 | processPayment(orderId);
49 | });
50 |
--------------------------------------------------------------------------------
/11_Classes_this_and_new_keyword/11.md:
--------------------------------------------------------------------------------
1 | #### The New Keyword
2 |
3 | ```js
4 | // The new keyword
5 | // The new keyword creates an object of num
6 | // which then let's us access to various methods,
7 | // like .toFixed() in the below code.
8 | const num = new Number(100.25);
9 |
10 | console.log(num.toFixed(0));// 100
11 | ```
12 |
13 | #### This Keyword
14 |
15 | ```js
16 | const person = {
17 | name: "John",
18 | getName() {
19 | console.log(this);
20 | },
21 | };
22 |
23 | person.getName(); // { name: 'John', getName: [Function: getName] }
24 | ```
25 |
26 | #### Class
27 |
28 | ```js
29 | // Class is a schema for
30 | // an object that can save
31 | // many values
32 |
33 | class Person {
34 | constructor(name, age, isWorking) {
35 | this.name = name;
36 | this.age = age;
37 | this.isWorking = isWorking;
38 | }
39 | }
40 |
41 | const user = new Person("John", 22, true);
42 |
43 | console.log(user); // Person { name: 'John', age: 22, isWorking: true }
44 |
45 | // How can we do the same thing above using
46 | // arrow function ?
47 |
48 | const createPerson = (name, age, isWorking) => ({ name, age, isWorking });
49 |
50 | const user1 = createPerson("Shubham", 23, false);
51 | console.log(user1);//{ name: 'Shubham', age: 23, isWorking: false }
52 | ```
53 |
54 |
--------------------------------------------------------------------------------
/6_Strings_in_detail/strings_2.js:
--------------------------------------------------------------------------------
1 | // Getting a substring of a string
2 |
3 | // const exampleString = "hotdog";
4 |
5 | // slice() method is used to get the substring of a string
6 | // It takes 2 arguments i.e, the start index and the end index;
7 | // const hot = exampleString.slice(0, 3);
8 | // console.log(hot);
9 |
10 | // const dog = exampleString.slice(3, 6);
11 | // console.log(dog);
12 |
13 | // Split a string
14 | // using the split() method
15 |
16 | // const exampleString = "dog";
17 |
18 | // const characters = exampleString.split("");
19 | // console.log(characters); // ['d','o','g']
20 |
21 | // const allAlphabets = "The quick brown fox jumps over the lazy dog.";
22 |
23 | // const splitAllAlphabets = allAlphabets.split(" ");
24 | // console.log(splitAllAlphabets);
25 | // [
26 | // 'The', 'quick',
27 | // 'brown', 'fox',
28 | // 'jumps', 'over',
29 | // 'the', 'lazy',
30 | // 'dog.'
31 | // ]
32 |
33 | // Reverse a String
34 | // const exampleString = "test";
35 |
36 | // const reversedString = exampleString.split("").reverse().join("");
37 | // console.log(reversedString);
38 |
39 | // Repeat method
40 | // const dog = "woof";
41 | // console.log(dog.repeat(5));
42 |
43 | // trim() method
44 | const email = " shubhamskadam963@gmail.com ";
45 | console.log(email);
46 |
47 | console.log(email.trim());
48 |
--------------------------------------------------------------------------------
/12_Asynchronous_Concepts/script2.js:
--------------------------------------------------------------------------------
1 | const fetchUser = (username) => {
2 | return new Promise((resolve, reject) => {
3 | setTimeout(() => {
4 | console.log("[Now we have the user]");
5 |
6 | resolve({ username });
7 | }, 2000);
8 | });
9 | };
10 |
11 | const fetchUserPhotos = (username) => {
12 | return new Promise((resolve, reject) => {
13 | setTimeout(() => {
14 | console.log(`Now we have the photos for ${username}`);
15 | resolve(["Photo1", "Photo2"]);
16 | }, 2000);
17 | });
18 | };
19 |
20 | const fetchPhotoDetails = (photo) => {
21 | return new Promise((resolve, reject) => {
22 | setTimeout(() => {
23 | console.log(`[Now we have the photo details ${photo}]`);
24 | resolve("details...");
25 | }, 2000);
26 | });
27 | };
28 |
29 | // This was one way of calling the function
30 | // fetchUser("Shubham")
31 | // .then((user) => fetchUserPhotos(user.username))
32 | // .then((photos) => fetchPhotoDetails(photos[0]))
33 | // .then((details) => console.log(`Your photo details are ${details}`));
34 |
35 | // The second way is using Async ==> Await
36 |
37 | const displayData = async () => {
38 | const user = await fetchUser("Shubham");
39 | const photos = await fetchUserPhotos(user.username);
40 | const details = await fetchPhotoDetails(photos[0]);
41 |
42 | console.log(details);
43 | };
44 |
45 | displayData();
46 |
--------------------------------------------------------------------------------
/7_Arrays_in_detail/Arrays_2.js:
--------------------------------------------------------------------------------
1 | // const numbers = [2, 4, 6, 8];
2 |
3 | // numbers.forEach((value, i) => console.log(value, i));
4 |
5 | // when to use forEach :
6 | // You want to do something with each element in the array
7 |
8 | // Don't use when :
9 | // You want to stop or break the loop when some condition is true.
10 | // When you are working with async code.
11 |
12 | // let sum = 0;
13 | // numbers.forEach((value) => (sum += value));
14 | // console.log(sum);
15 |
16 | // const inventory = [
17 | // { price: 7, name: "egg" },
18 | // { price: 10, name: "lays" },
19 | // { price: 12, name: "maggie" },
20 | // ];
21 |
22 | // Array Map
23 | // const prices = inventory.map((item) => console.log(item.price));
24 | // const names = inventory.map((item) => console.log(item.name));
25 |
26 | // Array filter
27 | // const numbers = [2, 5, -2, 0, -5, 1];
28 |
29 | // const positiveNumbers = numbers.filter((number) => number >= 0);
30 | // console.log(positiveNumbers);
31 |
32 | // const negativeNumbers = numbers.filter((number) => number <= 0);
33 | // console.log(negativeNumbers);
34 |
35 | const employeesData = [
36 | { name: "Shubham", overtime: 5 },
37 | { name: "Samarth", overtime: 7 },
38 | { name: "Seema", overtime: 8 },
39 | ];
40 |
41 | const employeesToReward = employeesData.filter(
42 | (employee) => employee.overtime >= 7
43 | );
44 |
45 | const employeeNames = employeesToReward.map((employee) => employee.name);
46 |
47 | employeeNames.forEach((user)=>{
48 | console.log(`Congratulations, ${user}`);
49 | })
--------------------------------------------------------------------------------
/6_Strings_in_detail/string.js:
--------------------------------------------------------------------------------
1 | // There are 3 types of strings
2 |
3 | // Strings wrapped up with single and double quotes are just plain txt
4 | // const single = "Hi, this is a normal text";
5 | // const double = "Hi, this is also a normal texat";
6 |
7 | // String wrapped inside a backtick has extended functionality
8 | // const backTick = `An extended Functionality provided to strings`;
9 |
10 | // const sum = (a, b) => a + b;
11 |
12 | // console.log(`I want to add ${sum(3, 4)}`);
13 |
14 | // How to get length of a string
15 |
16 | // const firstName = "You are a good person";
17 |
18 | // const firstLetter = firstName[0];
19 | // const lastLetter = firstName[firstName.length - 1];
20 |
21 | // console.log(firstLetter, lastLetter);
22 |
23 | // UPPERCASE and lowercase
24 |
25 | // const mixedCase = "I'am really Happy Today";
26 |
27 | // const lowerCase = mixedCase.toLowerCase();
28 | // const upperCase = mixedCase.toUpperCase();
29 |
30 | // console.log(upperCase);
31 |
32 | const hobbies = "I love HTML, CSS and JavaScript, JavaScript";
33 |
34 | // returns the index of first Occurrence of the word JavaScript
35 | const firstIndex = hobbies.indexOf("JavaScript");
36 | console.log(firstIndex);
37 |
38 | // returns the index of last Occurrence of the word JavaScript
39 | const lastIndex = hobbies.lastIndexOf("JavaScript");
40 | console.log(lastIndex);
41 |
42 | // includes() => Checks whether the word exists in the string.
43 | const includesCSS = hobbies.includes("CSS");
44 | console.log(includesCSS);
45 |
46 | // startsWith();
47 | console.log(hobbies.startsWith("I"));
48 |
49 | // endsWith();
50 | console.log(hobbies.endsWith('JavaScript'));
51 |
--------------------------------------------------------------------------------
/7_Arrays_in_detail/Arrays_3.js:
--------------------------------------------------------------------------------
1 | // Array Find
2 |
3 | // The Find method for arrays returns the
4 | // first value that satisfies the condition
5 |
6 | // const numbers = [1, 2, 3, 4, 5, 6, 7];
7 |
8 | // const value = numbers.find((number) => number > 5);
9 | // console.log(value);
10 |
11 | // const cities = ["Bangalore", "Mumbai", "New Delhi", "Noida", "Hyderabad"];
12 |
13 | // const city = cities.find((city) => city.startsWith("N"));
14 |
15 | // console.log(city);
16 |
17 | // // Array Includes
18 | // const movies = ["Avengers", "Superman", "Batman"];
19 |
20 | // if (movies.includes("Avengers")) {
21 | // console.log("The movie is available on prime");
22 | // } else {
23 | // console.log("The movie is not available on prime.");
24 | // }
25 |
26 | // Array sort => Alphabetically,
27 | // doesn't sort numbers
28 | // This sort method mutates the original array
29 | // const names = ["Shubham", "Aditya", "Divyanshi", "Samarth"];
30 | // names.sort();
31 | // console.log(names);
32 |
33 | // const numbers = [4, 12, 8, 5, 1];
34 |
35 | // Ascending order
36 | // numbers.sort((a, b) => a - b);
37 | // console.log(numbers);
38 |
39 | // Descending order
40 | // numbers.sort((a, b) => b - a);
41 | // console.log(numbers);
42 |
43 | // const array = [1, 2, 3, 4, 5];
44 |
45 | // Array Some => returns true if atleast one element passes the test
46 | // console.log(array.some((number) => number > 5)); // false
47 |
48 | // Array Every => return true if all elements pass the test
49 | // console.log(array.every((number) => number > 0)); // true
50 |
51 | // Array Reduce
52 |
53 | const groceryList = [29, 12, 45, 35, 87, 110];
54 |
55 | const total = groceryList.reduce((total, price) => total + price, 0);
56 |
57 | console.log(total); // 318
58 |
--------------------------------------------------------------------------------
/9_Value_vs_Reference/script.js:
--------------------------------------------------------------------------------
1 | // const animals = ["dogs", "cats"];
2 |
3 | // const otherAnimals = animals;
4 |
5 | // animals.push("pig");
6 |
7 | // console.log(animals); // [ 'dogs', 'cats', 'pig' ]
8 | // We get the same output for otherAnimals too,
9 | // because the otherAnimals is also referencing the same memory
10 | // as the animals.
11 | // console.log(otherAnimals); // [ 'dogs', 'cats', 'pig' ]
12 |
13 | // Cloning Arrays
14 | // 1st way : Spread Operator
15 | // const numbers = [1, 2, 3, 4];
16 | // const copiedNumbers = numbers;
17 |
18 | // Using spread Opeator,
19 | // Also known as Shallow Cloning
20 | // const newNumbers = [...numbers];
21 |
22 | // numbers.push(5);
23 | // console.log(numbers); // [ 1, 2, 3, 4, 5 ]
24 | // console.log(copiedNumbers); // [ 1, 2, 3, 4, 5 ]
25 | // console.log(newNumbers); // [ 1, 2, 3, 4 ]
26 |
27 | // 2nd way : Array.slice()
28 | // const numbers = [1, 2, 3, 4];
29 | // const copiedNumbers = numbers;
30 |
31 | // Using spread Opeator,
32 | // Also known as Shallow Cloning
33 | // const newNumbers = numbers.slice();
34 |
35 | // numbers.push(5);
36 | // console.log(numbers); // [ 1, 2, 3, 4, 5 ]
37 | // console.log(copiedNumbers); // [ 1, 2, 3, 4, 5 ]
38 | // console.log(newNumbers); // [ 1, 2, 3, 4 ]
39 |
40 | // Cloning Objects
41 | // 1st way : Spread Operator
42 | // const person = { name: "John", age: 22 };
43 | // const newPerson = { ...person };
44 |
45 | // person.age = 23;
46 | // console.log(person); // { name: 'John', age: 23 }
47 | // console.log(newPerson); // { name: 'John', age: 22 }
48 |
49 | // 2nd way : Object.assign()
50 | // const person = { name: "John", age: 22 };
51 | // const newPerson = Object.assign({},person);
52 |
53 | // person.age = 23;
54 | // console.log(person); // { name: 'John', age: 23 }
55 | // console.log(newPerson); // { name: 'John', age: 22 }
56 |
57 | // Deep Cloning
58 | // We can create a shallow copy of person object
59 | // but we have to do it for all the inner objects as well.
60 | // To solve this we can do a deep cloning where we make
61 | // use of JSON.stringify() method
62 |
63 | const person = {
64 | name: "Shubham",
65 | car: {
66 | brand: "BMW",
67 | color: "blue",
68 | wheels: 4,
69 | },
70 | };
71 |
72 | const newPerson = JSON.stringify(person);
73 |
74 | // newPerson will be in the form of string,
75 | // to convert it back to an object,
76 | // we use JSON.parse();
77 |
78 | const updatedPerson = JSON.parse(newPerson);
79 |
80 | updatedPerson.car.color = "red";
81 | console.log(person); // { name: 'Shubham', car: { brand: 'BMW', color: 'blue', wheels: 4 } }
82 | console.log(updatedPerson); // { name: 'Shubham', car: { brand: 'BMW', color: 'red', wheels: 4 } }
83 |
--------------------------------------------------------------------------------
/10_DOM/dom.md:
--------------------------------------------------------------------------------
1 | ## DOM Methods
2 |
3 | - `getElementById`: This method retrieves an element from the document by its ID.
4 |
5 | - `querySelector`: This method retrieves the first element that matches a specified CSS selector.
6 |
7 | - `querySelectorAll`: This method retrieves all elements that match a specified CSS selector.
8 |
9 | - `getElementsByTagName`: This method retrieves all elements with a specified tag name.
10 |
11 | - `getElementsByClassName`: This method retrieves all elements with a specified class name.
12 |
13 | Here are some examples of how you might use these methods:
14 |
15 | ```js
16 | Copy codeconst element = document.getElementById('my-element');
17 |
18 | const firstParagraph = document.querySelector('p');
19 |
20 | const listItems = document.querySelectorAll('li');
21 |
22 | const divs = document.getElementsByTagName('div');
23 |
24 | const redElements = document.getElementsByClassName('red');
25 | ```
26 |
27 | Here is a list of some common DOM (Document Object Model) properties and methods that you can use to manipulate HTML elements:
28 |
29 | #### Properties
30 |
31 | - `innerHTML`: This property gets or sets the HTML content within an element.
32 | - `style`: This property gets or sets the inline style of an element.
33 | - `className`: This property gets or sets the class name of an element.
34 | - `id`: This property gets or sets the ID of an element.
35 | - `value`: This property gets or sets the value of an input element.
36 |
37 | #### Methods
38 |
39 | - `getAttribute`: This method gets the value of an attribute of an element.
40 | - `setAttribute`: This method sets the value of an attribute of an element.
41 | - `addEventListener`: This method adds an event listener to an element.
42 | - `removeEventListener`: This method removes an event listener from an element.
43 | - `appendChild`: This method adds a new child element to an element.
44 |
45 | Here are some examples of how you might use these properties and methods:
46 |
47 | ```js
48 | Copy codeconst element = document.getElementById('my-element');
49 |
50 | element.innerHTML = 'Hello, world!';
51 |
52 | element.style.color = 'red';
53 |
54 | element.className = 'highlight';
55 |
56 | element.id = 'new-id';
57 |
58 | const input = document.querySelector('input');
59 | input.value = 'Hello, world!';
60 |
61 | const attributeValue = element.getAttribute('data-attribute');
62 |
63 | element.setAttribute('data-attribute', 'new value');
64 |
65 | element.addEventListener('click', () => {
66 | console.log('Element was clicked!');
67 | });
68 |
69 | element.removeEventListener('click', myClickHandler);
70 |
71 | const newElement = document.createElement('p');
72 | newElement.innerHTML = 'This is a new element';
73 | element.appendChild(newElement);
74 | ```
--------------------------------------------------------------------------------
/1_variables_and_data_types/variablesDataTypes.md:
--------------------------------------------------------------------------------
1 | ## Variables and Data Types
2 |
3 | JavaScript has 3 ways of declaring a variable :
4 |
5 | 1. Using var
6 |
7 | 2. Using let
8 |
9 | 3. Using const ( Read Only )
10 |
11 | There are some rules to declare variable names
12 |
13 | 1. Do not use existing JS keywords
14 | 2. Name must begin with a letter
15 | 3. Names are case sensitive
16 | 4. You cannot use any special character while naming a variable other then \_ and $
17 |
18 | ```js
19 | var variableName = "Welcome to Variables";
20 |
21 | // updating the variable
22 | variableName = "Hello World";
23 | ```
24 |
25 | ### Strings
26 |
27 | String is a datatype used to represent text.
28 |
29 | ```js
30 | const exampleString = "Hello, World!";
31 | ```
32 |
33 | There are 3 ways of representing a string:
34 |
35 | - Single Quotes
36 |
37 | - Double Quotes
38 |
39 | - Backticks
40 |
41 | We can use Single Quote or Double Quote if we just want to statically display it.
42 |
43 | ```js
44 | const singleQuote = 'Hello';
45 | const doubleQuote = "Hello";
46 | ```
47 |
48 | We can use Backtick for extended functionality such as dynamically changing it when required.
49 |
50 | ```js
51 | const userName = "Shubham";
52 | const backTick = `Hello, ${userName}`;
53 | console.log(backTick); // 'Hello, Shubham'
54 | ```
55 |
56 | '${}' this is called a template literal.
57 |
58 | ### Numbers
59 |
60 | Numbers - Integers , Fractions.
61 |
62 | ```javascript
63 | const firstNumber = 12;
64 | const secondNumber = 27;
65 |
66 | const result = firstNumber + secondNumber;
67 |
68 | console.log(result); // '39'
69 | ```
70 |
71 | ### Booleans
72 |
73 | Boolean - True / False.
74 |
75 | ```js
76 | const age = 22;
77 |
78 | if (age >= 18) {
79 | console.log("You are Good to drive"); // You are Good to drive
80 | } else {
81 | console.log("You are very young to drive");
82 | }
83 | ```
84 |
85 | ### Null and Undefined
86 |
87 | The null value represents the intentional absence of any object value.
88 |
89 | ```js
90 | const age = null;
91 | console.log(age); // null
92 | ```
93 |
94 | when you don't assign any value to the variable then it becomes undefined.
95 |
96 | ```js
97 | let firstName;
98 | console.log(firstName); // undefined
99 | ```
100 |
101 | ### Objects
102 |
103 | An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method.
104 |
105 | ```js
106 | const Person = {
107 | name: "Shubham",
108 | age: 21,
109 | };
110 |
111 | console.log(typeof Person); // object
112 |
113 | const arr = [1, 2, 3, 4];
114 | console.log(typeof arr); // object
115 |
116 | // date is an object;
117 | const date = new Date();
118 | console.log(typeof date); // object
119 |
--------------------------------------------------------------------------------
/2_Operators/Operators.md:
--------------------------------------------------------------------------------
1 | ## Operators
2 |
3 | ### Arithmetic Operators
4 |
5 | ```js
6 | const a = 5;
7 | const b = 10;
8 | let result = 0;
9 |
10 | // Addition
11 | result = a + b;
12 |
13 | // Subtraction
14 | result = a - b;
15 |
16 | // Multiplication
17 | result = a * b;
18 |
19 | // Division
20 | result = a / b;
21 |
22 | // Exponent
23 | result = a ** b;
24 |
25 | // Modulo
26 | result = a % b;
27 |
28 | // Increment and Decrement
29 | result++;
30 | result--;
31 | ```
32 |
33 | ### Comparison Operators
34 |
35 | Comparison Operators returns true / false.
36 |
37 | ```js
38 | const a = 5;
39 | const b = 10;
40 |
41 | // Greater than
42 | console.log(a > b); // false
43 |
44 | // Greater than equal to
45 | console.log(a >= b); // false
46 |
47 | // Less than
48 | console.log(a < b); // true
49 |
50 | // Less than equal to
51 | console.log(a <= b); // true
52 |
53 | // Loose equality
54 | // Doesn't compare the DATA TYPES
55 | console.log(a == b); // false
56 |
57 | // Not equal
58 | console.log(a != b); //true
59 |
60 | // Strict Equality
61 | // Compares VALUES and DATA TYPES
62 | // Returns true only if both are the same
63 | console.log(a === b); //false
64 |
65 | // Strict Inequality
66 | console.log(a !== b); //true
67 | ```
68 |
69 | ### Logical Operators
70 |
71 | Logical operators are used to determine the logic between variables or values.
72 |
73 | ```js
74 | // Logical Operators
75 |
76 | // AND && => ALL OPERANDS ARE TRUE => TRUE
77 | console.log(true && true && true); // true
78 |
79 | // OR || => ATLEAST ONE OPERAND IS TRUE => TRUE
80 | console.log(true || false); // true
81 |
82 | // NOT ! => Reverses the Boolean value
83 | console.log(!true); // false
84 | ```
85 |
86 | ```js
87 | // The below line of code outputs 999,
88 | // because it evaluates from left to right and
89 | // it returns the last true value in the condition
90 | console.log("truthy" && 1 && "test" && 999); // 999
91 |
92 | // The below line of code outputs 0,
93 | // because there is one false value in the
94 | // entire condition and it will always return 0
95 | console.log("truthy" && 0 && "test" && 999); // 0
96 |
97 | // For OR operator
98 | // The below line returns "truthy" because,
99 | // when the first value of the condition is true,
100 | // it doesn't check rest of the values.
101 | console.log("truthy" || 0 || "test" || 999); // truthy
102 |
103 | // The below line returns undefined,
104 | // because it checks all the values and
105 | // when all values are false, it returns the last one
106 | console.log("" || 0 || null || undefined); // undefined
107 | ```
108 |
109 | ### Assignment Operator
110 |
111 | An assignment operator assigns a value to its left operand based on the value of its right operand.
112 |
113 | ```js
114 | let num = 34;
115 | num += 2;
116 | console.log(num); // 36
117 | ```
--------------------------------------------------------------------------------
/8_Objects_in_detail/object.js:
--------------------------------------------------------------------------------
1 | // object is an unordered collection
2 | // of related date in form of
3 | // key value pair
4 |
5 | // const person = {
6 | // firstName: "Shubham",
7 | // lastName: "Kadam",
8 | // age: 23,
9 | // car: {
10 | // brand: "Mercedes",
11 | // year: 2020,
12 | // },
13 | // };
14 |
15 | // console.log(person);
16 |
17 | // Dot notation
18 | // const person = {
19 | // firstName: "Shubham",
20 | // };
21 |
22 | // person.dog = {
23 | // name: "fluffy",
24 | // age: 2,
25 | // };
26 |
27 | // person.age = 23;
28 | // console.log(person.dog.age);
29 |
30 | // Square bracket notation
31 | // const property = "age";
32 |
33 | // console.log(person[property]);
34 |
35 | // Object.keys() creates an array containg the keys of an object.
36 |
37 | // Intialize an object
38 | const employee = {
39 | boss: "Shubham",
40 | secretary: "Samarth",
41 | sales: "John",
42 | accountant: "Oscar",
43 | };
44 |
45 | // Let's say we want to see all the positions(keys) in the employee object
46 | const positions = Object.keys(employee);
47 | console.log(positions);
48 |
49 | // Object.values() creates an array containg the values of an object.
50 | const session = {
51 | id: 1,
52 | time: `26-July-2022`,
53 | device: "Mobile",
54 | browser: "Chrome",
55 | };
56 |
57 | const sessionInfo = Object.values(session);
58 | console.log(sessionInfo);
59 |
60 | // Object.entries() creates an array containg the key/value of an object.
61 | const operatingSystem = {
62 | name: "Ubuntu",
63 | version: "20.04",
64 | license: "Open Source",
65 | };
66 |
67 | const entries = Object.entries(operatingSystem);
68 |
69 | entries.forEach((entry) => {
70 | let key = entry[0];
71 | let value = entry[1];
72 |
73 | console.log(`${key}:${value}`);
74 | });
75 |
76 | // Object.freeze() prevents modification to
77 | // properties and values of an object,
78 | // and prevents properties from being
79 | // added or removed from an object
80 |
81 | // Intialize an object
82 | // const user = {
83 | // username: "Shubham",
84 | // password: "12345",
85 | // };
86 |
87 | // const admin = Object.freeze(user);
88 |
89 | // user.username = "Samarth"; // Trying to overwrite the object username
90 | // console.log(user.username); // Shubham (remains the same);
91 |
92 | // Object.seal() prevents new properties
93 | // from being added to an object,
94 | // but allows the modification of existing properties
95 | // Intialize an object
96 |
97 | const user = {
98 | username: "Shubham",
99 | password: "12345",
100 | };
101 |
102 | const newUser = Object.seal(user);
103 |
104 | newUser.username = "Samarth"; // The username will be changed
105 | newUser.age = 23; // the age property will not be added because we applied Object.seal()
106 |
107 | console.log(user);
108 |
--------------------------------------------------------------------------------
/3_Logic_and_Control_flow/LogicAndControlFlow.md:
--------------------------------------------------------------------------------
1 | ## Logic and Control Flow
2 |
3 | ### Conditional Statements
4 |
5 | Conditional statements are used to perform different actions based on different conditions.
6 |
7 | ```js
8 | // if, else and else if
9 |
10 | const age = 8;
11 |
12 | if (age > 18) {
13 | console.log("You may enter");
14 | } else if (age === 18) {
15 | console.log("Welcome, You just turned 18!");
16 | } else {
17 | console.log("Grow up"); // Grow up
18 | }
19 | ```
20 |
21 | FALSY VALUES - Excluding them all other values are TRUTHY VALUES
22 |
23 | - false
24 | - 0
25 | - ''
26 | - null
27 | - undefined
28 | - NaN
29 |
30 | SOME TRUTHY VALUES
31 |
32 | - true
33 | - 1
34 | - "hello"
35 | - 27 (any number)
36 | - {} - empty object is also considered to be true
37 | - [] - empty array is also considered to be true
38 |
39 | ```js
40 | const stars = 5;
41 |
42 | if (stars) {
43 | console.log(`Congrats, you have ${stars} stars`); // Congrats, you have 5 stars
44 | } else {
45 | console.log("You don't have any stars");
46 | }
47 | ```
48 |
49 | #### Ternary Operator
50 |
51 | ```js
52 | // Syntax ,
53 | // (condition) ? // true : // false
54 | const age = 1;
55 | age > 18 ? console.log("You may drive") : console.log("You cannot drive yet!");
56 | // You cannot drive yet!
57 | ```
58 |
59 | ## Loops
60 |
61 | ### while loop
62 |
63 | The while loop loops through a block of code as long as a specified condition is true.
64 |
65 | ```js
66 | // while (condition){
67 | // block of code;
68 | // }
69 |
70 | let i = 0;
71 |
72 | // loop to display numbers from 0 to 9
73 | while (i < 10) {
74 | console.log(i);
75 | i++;
76 | }
77 | ```
78 |
79 | ### for loop
80 |
81 | The for statement creates a loop with 3 optional expressions.
82 |
83 | ```js
84 | for (expression 1; expression 2; expression 3) {
85 | // code block to be executed
86 | }
87 | // loop to display numbers from 0 to 9
88 | for (let i = 0; i < 10; i++) {
89 | console.log(i);
90 | }
91 | ```
92 |
93 | ### Switch Statement
94 |
95 | The switch statement is used to perform different actions based on different conditions.
96 |
97 | ```js
98 | // syntax ,
99 | // switch (condition){
100 | // case 'xyz':
101 | // block of code;
102 | // break;
103 |
104 | // case 'abc':
105 | // block of code;
106 | // break;
107 | // }
108 | ```
109 |
110 | ```js
111 | const superHero = "Iron Man";
112 |
113 | switch (superHero) {
114 | case "Captain America":
115 | console.log("Never give up!");
116 | break;
117 |
118 | case "Iron Man":
119 | console.log("I am Iron Man!"); // I am Iron Man!
120 | break;
121 |
122 | case "Thor":
123 | console.log("That is my hammer!");
124 | break;
125 |
126 | case "Black Widow":
127 | console.log("One shot, one kill");
128 | break;
129 |
130 | default:
131 | console.log("Enter a valid superhero name");
132 | }
133 | ```
134 |
--------------------------------------------------------------------------------
/4_Functions/Functions.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | A BLOCK OF CODE ==> PERFORMS A TASK
4 |
5 | There are multiple ways of function declaration.
6 |
7 | ```js
8 | function square(number) {
9 | // Function declaration
10 | return number * number;
11 | }
12 |
13 | // FUNCTION CALL (calling / executing a function)
14 | const ans = square(6);
15 | console.log(ans); // 36
16 | ```
17 |
18 | The advantage of using a function declaration is having an access to 'this' keyword.
19 |
20 | #### A function expression
21 |
22 | Another way of declaring a function.
23 |
24 | ```js
25 | // const varName = function(params){
26 | //statements
27 | // }
28 |
29 | const sayHi = function (name) {
30 | console.log(`Hello, ${name}`);
31 | };
32 |
33 | sayHi("Shubham");
34 | ```
35 |
36 | #### An arrow Function
37 |
38 | A modern way of writing functions in JavaScript.
39 |
40 | ```js
41 | // const varName = (params) => {
42 | // statements
43 | // };
44 |
45 | const sayHi = (name) => {
46 | console.log(`Hello, ${name}`);
47 | };
48 |
49 | sayHi("Shubham");
50 | ```
51 |
52 | ```js
53 | const square = (number) => {
54 | return number * number;
55 | };
56 |
57 | // A short hand to declare arrow function if there is just one statement in the function:
58 | const square1 = (number) => number * number;
59 | ```
60 |
61 | #### Parameters and Arguments
62 |
63 | Parameters are used when defining a function
64 |
65 | Arguments are passed when making a function call.
66 |
67 | ```js
68 | const sayHi = (name, age = 0) => {
69 | // By default we can make the
70 | // value of age to be 0
71 | // to avoid undefined as a
72 | // result when age is not being passed.
73 | // name and age are parameters here
74 | console.log(`Hi ${name}, you are ${age} years old!`); // Hi Shubham, you are 0 years old.
75 | };
76 |
77 | sayHi("Shubham"); // 'Shubham' is an argument that is being passed
78 | ```
79 |
80 | ### Scope
81 |
82 | There are three types of Scope :
83 |
84 | 1. Global Scope
85 | 2. Function Scope
86 | 3. Block Scope
87 |
88 | #### Global Scope
89 |
90 | the global scope is the scope that contains, and is visible in, all other scopes.
91 |
92 | ```js
93 | const firstName = "Shubham";
94 | const GlobalScope = () => {
95 | console.log(firstName); // Shubham
96 | };
97 |
98 | GlobalScope();
99 | ```
100 |
101 | #### Local Scope
102 |
103 | Local variables have Function Scope. They can only be accessed from within the function.
104 |
105 | ```js
106 | const someFunction = () => {
107 | let firstName = "John";
108 | console.log(firstName); // John
109 |
110 | const someFunction2 = () => {
111 | console.log(firstName); // John
112 | };
113 |
114 | someFunction2();
115 | };
116 |
117 | someFunction();
118 | ```
119 |
120 | #### Block Scope
121 |
122 | This scope restricts the variable that is declared inside a specific block, from access by the outside of the block.
123 |
124 | ```js
125 | if (true) {
126 | var firstName = "Jane";
127 | }
128 |
129 | console.log(firstName);
130 | // Declaring a variable with var
131 | // inside a blockscope can also let
132 | // you access the variable in global scope.
133 | ```
134 |
--------------------------------------------------------------------------------
/9_Value_vs_Reference/value_vs_reference.md:
--------------------------------------------------------------------------------
1 | #### Copy by Reference
2 |
3 | ```js
4 | const animals = ["dogs", "cats"];
5 |
6 | const otherAnimals = animals;
7 |
8 | animals.push("pig");
9 |
10 | console.log(animals); // [ 'dogs', 'cats', 'pig' ]
11 | console.log(otherAnimals); // [ 'dogs', 'cats', 'pig' ]
12 | ```
13 |
14 | The first block of code demonstrates how variables in JavaScript can be copied by reference, rather than by value. When you assign an array or object to a new variable, the new variable is simply a reference to the original array or object. This means that any changes made to the original array or object will also be reflected in the copied variable, because they are both pointing to the same memory location.
15 |
16 | #### Shallow Cloning
17 |
18 | ```js
19 | // Cloning Arrays
20 | // 1st way : Spread Operator
21 | const numbers = [1, 2, 3, 4];
22 | const copiedNumbers = numbers;
23 |
24 | const newNumbers = [...numbers];
25 |
26 | numbers.push(5);
27 | console.log(numbers); // [ 1, 2, 3, 4, 5 ]
28 | console.log(copiedNumbers); // [ 1, 2, 3, 4, 5 ]
29 | console.log(newNumbers); // [ 1, 2, 3, 4 ]
30 |
31 | // 2nd way : Array.slice()
32 | const numbers = [1, 2, 3, 4];
33 | const copiedNumbers = numbers;
34 |
35 | const newNumbers = numbers.slice();
36 |
37 | numbers.push(5);
38 | console.log(numbers); // [ 1, 2, 3, 4, 5 ]
39 | console.log(copiedNumbers); // [ 1, 2, 3, 4, 5 ]
40 | console.log(newNumbers); // [ 1, 2, 3, 4 ]
41 |
42 | ```
43 |
44 | ```js
45 | // Cloning Objects
46 | // 1st way : Spread Operator
47 | const person = { name: "John", age: 22 };
48 | const newPerson = { ...person };
49 |
50 | person.age = 23;
51 | console.log(person); // { name: 'John', age: 23 }
52 | console.log(newPerson); // { name: 'John', age: 22 }
53 |
54 | // 2nd way : Object.assign()
55 | const person = { name: "John", age: 22 };
56 | const newPerson = Object.assign({}, person);
57 |
58 | person.age = 23;
59 | console.log(person); // { name: 'John', age: 23 }
60 | console.log(newPerson); // { name: 'John', age: 22 }
61 | ```
62 |
63 | A shallow copy is a copy that only includes the top-level properties of the original array or object, rather than copying all nested properties as well.
64 |
65 | The first way to create a shallow copy is to use the spread operator (`...`). This creates a new array or object with the same properties as the original, but they are not nested. The second way to create a shallow copy is to use the `Array.slice()` or `Object.assign()` methods. These methods work similarly to the spread operator, but they are more specific to arrays and objects, respectively.
66 |
67 | #### Deep Cloning
68 |
69 | ```js
70 | // Deep Cloning
71 | const person = {
72 | name: "Shubham",
73 | car: {
74 | brand: "BMW",
75 | color: "blue",
76 | wheels: 4,
77 | },
78 | };
79 |
80 | const newPerson = JSON.stringify(person);
81 |
82 | const updatedPerson = JSON.parse(newPerson);
83 |
84 | updatedPerson.car.color = "red";
85 | console.log(person); // { name: 'Shubham', car: { brand: 'BMW', color: 'blue', wheels: 4 } }
86 | console.log(updatedPerson); // { name: 'Shubham', car: { brand: 'BMW', color: 'red', wheels: 4 } }
87 | ```
88 |
89 | A deep copy is a copy that includes all nested properties of the original object, rather than just the top-level properties.
90 |
91 | To create a deep copy, the code uses the `JSON.stringify()` and `JSON.parse()` methods. `JSON.stringify()` converts an object to a JSON string, which is a format that can be easily stored or transmitted. `JSON.parse()` converts a JSON string back into an object.
92 |
93 | By using these methods, the code is able to create a deep copy of the original object, which can be modified independently without affecting the original object.
94 |
--------------------------------------------------------------------------------
/5_Hoisting_and_Closure/HoistingAndClosure.md:
--------------------------------------------------------------------------------
1 | ### Hoisting
2 |
3 | In JavaScript, hoisting is the behavior of moving declarations to the top of the current scope. In other words, when the code is executed, declarations are processed before any code is executed. This means that you can use a variable or function before it has been declared.
4 |
5 | For example, consider the following code:
6 |
7 | ```js
8 | Copy codeconsole.log(x); // undefined
9 | var x = 10;
10 | ```
11 |
12 | Even though `x` is defined on the second line, it is still accessible on the first line because of hoisting. The declarations are moved to the top of the current scope, so the code is effectively rewritten as:
13 |
14 | ```js
15 | Copy codevar x;
16 | console.log(x); // undefined
17 | x = 10;
18 | ```
19 |
20 | This behavior is specific to declarations (e.g. `var`, `let`, and `const`). Assignments and other code are not affected by hoisting.
21 |
22 | It is generally a good idea to declare all variables at the top of their respective scopes to avoid any confusion or unexpected behavior related to hoisting.
23 |
24 | ```js
25 | hoist();
26 |
27 | // The function will be executed even
28 | // if the function call is done before the function declaration
29 | function hoist() {
30 | var message = "test";
31 | console.log(message); // test
32 | }
33 | ```
34 |
35 | With modern JavaScript we can avoid Hoisting, in the code below we are making use of let and const.
36 |
37 | ```js
38 | console.log(age); // undeclared error
39 | console.log(num); // undeclared num
40 | let age = 32;
41 | let num = 23;
42 | ```
43 |
44 | ```js
45 | hoist();
46 |
47 | const hoist = () => {
48 | // reference error
49 | var message = "test";
50 | console.log(message);
51 | };
52 | ```
53 |
54 | ### Closure
55 |
56 | In JavaScript, a closure is a function that has access to the outer (enclosing) function's variables—scope chain—even after the outer function has returned.
57 |
58 | Here is an example of a closure in JavaScript:
59 |
60 | ```js
61 | function outerFunction(x) {
62 | return function innerFunction(y) {
63 | return x + y;
64 | }
65 | }
66 |
67 | const add5 = outerFunction(5);
68 | console.log(add5(3)); // 8
69 | ```
70 |
71 | In this example, the `innerFunction` has access to the `x` variable from the outer function even after the outer function has returned. The `innerFunction` is said to close over the variables from the outer function.
72 |
73 | Closures are often used to create private variables in JavaScript. For example:
74 |
75 | ```js
76 | function counter() {
77 | let count = 0;
78 | return function() {
79 | return ++count;
80 | }
81 | }
82 |
83 | const myCounter = counter();
84 | console.log(myCounter()); // 1
85 | console.log(myCounter()); // 2
86 | ```
87 |
88 | In this example, the `count` variable is not accessible from outside the `counter` function, but the inner function returned by `counter` has access to it. This allows the inner function to maintain state across multiple invocations.
89 |
90 | Closures are an important concept in JavaScript and are commonly used in many different types of code.
91 |
92 | ```js
93 | const outer = () => {
94 | const outerVar = "Hello";
95 |
96 | const inner = () => {
97 | const innervar = "Hi";
98 | console.log(outerVar, innervar);
99 | };
100 | return inner;
101 | };
102 |
103 | const innerFunc = outer();
104 |
105 | innerFunc();
106 | ```
107 |
108 | ```js
109 | const init = () => {
110 | const hobby = "Learning JavaScript"; // Local variable created by init function
111 |
112 | const displayHobby = () => {
113 | // displayHobby is the inner function, a closer
114 | console.log(hobby); // using a variable created in the parent function
115 | };
116 |
117 | displayHobby();
118 | };
119 |
120 | init();
121 | ```
122 |
123 |
--------------------------------------------------------------------------------
/6_Strings_in_detail/strings.md:
--------------------------------------------------------------------------------
1 | ## Strings
2 |
3 | There are 3 types of Strings :
4 |
5 | - Strings with single quotes
6 | - Strings with double quotes
7 | - Strings with Backticks
8 |
9 | ```js
10 | // Strings wrapped up with single and double quotes are just plain txt
11 | const single = "Hi, this is a normal text";
12 | const double = "Hi, this is also a normal text";
13 |
14 | // String wrapped inside a backtick has extended functionality
15 | const backTick = `An extended Functionality provided to strings`;
16 |
17 | const sum = (a, b) => a + b;
18 |
19 | console.log(`I want to add ${sum(3, 4)}`); // I want to add 7
20 |
21 | ```
22 |
23 | #### Length of the String
24 |
25 | We can use the .length property to get the length of the string.
26 |
27 | ```js
28 | const firstName = "You are a good person";
29 |
30 | const firstLetter = firstName[0];
31 | const lastLetter = firstName[firstName.length - 1];
32 |
33 | console.log(firstLetter, lastLetter); // Y , n
34 | ```
35 |
36 | #### Uppercase and Lowercase
37 |
38 | To make a string Uppercase the toUpperCase() method is being called.
39 |
40 | To make a string Lowercase the toLowerCase() method is being called.
41 |
42 | ```js
43 | const mixedCase = "I'am really Happy Today";
44 |
45 | const lowerCase = mixedCase.toLowerCase();
46 | const upperCase = mixedCase.toUpperCase();
47 |
48 | console.log(lowerCase)// i'am really happy today
49 | console.log(upperCase);// I'AM REALLY HAPPY TODAY
50 | ```
51 |
52 | #### Searching for a Substring
53 |
54 | ```js
55 | const hobbies = "I love HTML, CSS and JavaScript, JavaScript";
56 |
57 | // returns the index of first Occurrence of the word JavaScript
58 | const firstIndex = hobbies.indexOf("JavaScript");
59 | console.log(firstIndex); // 21
60 |
61 | // returns the index of last Occurrence of the word JavaScript
62 | const lastIndex = hobbies.lastIndexOf("JavaScript");
63 | console.log(lastIndex); // 33
64 |
65 | // includes() => Checks whether the word exists in the string.
66 | const includesCSS = hobbies.includes("CSS");
67 | console.log(includesCSS); // true
68 |
69 | // startsWith();
70 | console.log(hobbies.startsWith("I")); // true
71 |
72 | // endsWith();
73 | console.log(hobbies.endsWith('JavaScript')); // true
74 |
75 | ```
76 |
77 | #### Getting a Substring of a String
78 |
79 | ```js
80 | const exampleString = "hotdog";
81 |
82 | // slice() method is used to get the substring of a string
83 | // It takes 2 arguments i.e, the start index and the end index;
84 | const hot = exampleString.slice(0, 3);
85 | console.log(hot); // hot
86 |
87 | const dog = exampleString.slice(3, 6);
88 | console.log(dog); // dog
89 | ```
90 |
91 | #### Split a String
92 |
93 | ```js
94 | // Using the split() method
95 |
96 | const exampleString = "dog";
97 |
98 | const characters = exampleString.split("");
99 | console.log(characters); // ['d','o','g']
100 |
101 | const allAlphabets = "The quick brown fox jumps over the lazy dog.";
102 |
103 | const splitAllAlphabets = allAlphabets.split(" ");
104 | console.log(splitAllAlphabets);
105 | // [
106 | // 'The', 'quick',
107 | // 'brown', 'fox',
108 | // 'jumps', 'over',
109 | // 'the', 'lazy',
110 | // 'dog.'
111 | // ]
112 |
113 | ```
114 |
115 | #### Reverse a String
116 |
117 | The reverse method doesn't work over strings. So we split the string so that it becomes an array.
118 |
119 | Now we call the reverse method to reverse the array and lastly join method to join the characters to make it a string again.
120 |
121 | ```js
122 | const exampleString = "test";
123 |
124 | const reversedString = exampleString.split("").reverse().join("");
125 | console.log(reversedString);
126 | ```
127 |
128 | #### Repeat
129 |
130 | ```js
131 | const dog = "woof";
132 | console.log(dog.repeat(5)); // woofwoofwoofwoofwoof
133 | ```
134 |
135 | #### Trim
136 |
137 | Trimming up unnecessary spaces in a string using the trim() method.
138 |
139 | ```js
140 | // trim() method
141 | const email = " shubhamskadam963@gmail.com ";
142 |
143 | console.log(email); // shubhamskadam963@gmail.com
144 | console.log(email.trim());// shubhamskadam963@gmail.com
145 | ```
146 |
147 |
--------------------------------------------------------------------------------
/12_Asynchronous_Concepts/12.md:
--------------------------------------------------------------------------------
1 | #### Intervals and Timers
2 |
3 | ```js
4 | // Asynchronous Code
5 |
6 | // setInterval
7 | // clearInterval
8 |
9 | // outputs Hello, world! Every 2 seconds
10 | const myInterval = setInterval(() => console.log("Hello, world!"), 2000);
11 | clearInterval(myInterval); // Clears the Interval
12 |
13 | // setTimeout
14 | // clearTimeout
15 |
16 | // Outputs Let's Play after 5 seconds
17 | const myTimeout = setTimeout(() => console.log("Lets play"), 5000);
18 |
19 | console.log("logging in the bottom");
20 | ```
21 |
22 | #### Introduction to Synchronous and Asynchronous
23 |
24 | ```js
25 | // Synchronous Code
26 | const functionOne = () => {
27 | console.log("Function One"); // This will be printed first
28 |
29 | functionTwo();
30 |
31 | console.log("Function One, Part two"); // This will be printed third
32 | };
33 |
34 | const functionTwo = () => {
35 | console.log("Function two"); // This will be printed second
36 | };
37 |
38 | // Asynchronous Code
39 |
40 | const functionOne = () => {
41 | console.log("Function One"); // This will be printed first
42 |
43 | functionTwo();
44 |
45 | console.log("Function One, Part two"); // This will be printed second
46 | };
47 |
48 | const functionTwo = () => {
49 | setTimeout(() => console.log("Function two"), 2000); // This will be printed third
50 |
51 | ```
52 |
53 | #### Callback functions
54 |
55 | ```js
56 | // Callback functions
57 |
58 | const fetchUser = (username, callback) => {
59 | setTimeout(() => {
60 | callback({ username });
61 | }, 2000);
62 | };
63 |
64 | fetchUser("Shubham", (user) => {
65 | console.log(`Hello, ${user.username}`); // Hello, Shubham
66 | });
67 | ```
68 |
69 | There are two problems that we face in callbacks:-
70 |
71 | 1. Callback Hell: Asynchronous operations in JavaScript can be achieved through callbacks. Whenever there are multiple dependent Asynchronous operations it will result in a lot of nested callbacks. This will cause a 'pyramid of doom' like structure.
72 | 2. Inversion of control: When we give the control of callbacks being called to some other API, this may create a lot of issues. That API may be buggy, may not call our callback and create order as in the above example, may call the payment callback twice etc.
73 |
74 | #### Promises
75 |
76 | In JavaScript, a Promise is an object that represents the result of an asynchronous operation. A Promise can be in one of three states: pending, fulfilled, or rejected.
77 |
78 | A Promise starts in the pending state, and it can either be fulfilled with a value or rejected with a reason (error). Once a Promise is fulfilled or rejected, it is considered settled, and it cannot be changed anymore.
79 |
80 | Promises are used to handle asynchronous operations in a synchronous manner, making it easier to write and reason about async code. Instead of using callback functions, you can use the then and catch methods on a Promise to specify what should happen when the Promise is fulfilled or rejected.
81 |
82 | ```js
83 | // Let's say we have a shopping cart
84 | const cart = ['shoes','pants','shirt'];
85 |
86 | // If we had to implement a series of operations
87 | // let's say we have a function to,
88 | // 1. Create an order which will return a orderID
89 | // 2. Proceed to payment with orderId and return payment info.
90 | // 3. Show order summary with payment info
91 |
92 | createOrder(cart,(orderID)=>{
93 | proceedToPayment(orderID,(paymentInfo)=>{
94 | showOrderSummary(paymentInfo,()=>{
95 | displayOrderSummary();
96 | })
97 | }
98 | })
99 | // In the above code we see the call back hell or
100 | // also known as Pyramid of doom
101 |
102 | // We can write the same code using promises
103 | createOrder(cart)
104 | .then((orderId)=>{
105 | return proceedToPayment(orderId)
106 | })
107 | .then((paymentInfo)=>{
108 | return showOrderSummary(paymentInfo)
109 | })
110 | .then(()=>{
111 | displayOrderSummary();// not returning anything because we are just displaying
112 | })
113 |
114 | // why do we use promises ?
115 | // 1. To avoid Inversion of Control [Not calling the fuction over another function]
116 | // 2. To avoid Call Back hell and have better control of our code
117 | ```
118 |
--------------------------------------------------------------------------------
/8_Objects_in_detail/objects.md:
--------------------------------------------------------------------------------
1 | ## Objects in detail
2 |
3 | #### Creating an Object
4 |
5 | ```js
6 | const person = {
7 | firstName: "Shubham",
8 | lastName: "Kadam",
9 | age: 23,
10 | car: {
11 | brand: "Mercedes",
12 | year: 2020,
13 | },
14 | };
15 | ```
16 |
17 | The first block of code shows how to create a new object using object literal syntax. An object literal is a list of key-value pairs enclosed in curly braces `{}`. The keys are represented by strings, and the values can be any data type (strings, numbers, arrays, etc).
18 |
19 | #### The Dot and Square Notation
20 |
21 | ```js
22 | // Dot notation
23 | const person = {
24 | firstName: "Shubham",
25 | };
26 |
27 | person.dog = {
28 | name: "fluffy",
29 | age: 2,
30 | };
31 |
32 | person.age = 23; // Age is being added in person object
33 | console.log(person.dog.age); // 2
34 |
35 | // Square bracket notation
36 | const property = "age";
37 |
38 | console.log(person[property]); // 23
39 | ```
40 |
41 | The above code demonstrates two ways to access and modify the properties of an object: dot notation and square bracket notation.
42 |
43 | With dot notation, you can access or set a property of an object using a dot (`.`) followed by the property name. For example, `person.age = 23` sets the `age` property of the `person` object to 23.
44 |
45 | With square bracket notation, you can access or set a property using a string inside square brackets (`[]`). For example, `person['age'] = 23` sets the `age` property of the `person` object to 23.
46 |
47 | ```js
48 | const dog = {
49 | name: "Fluffy",
50 | bark: () => {
51 | console.log("woof,woof");
52 | },
53 | };
54 |
55 | dog.bark(); // woof,woof
56 |
57 | // this keyword
58 | const car = {
59 | name: "Lambo",
60 | model: 2019,
61 | Details: function () {
62 | console.log(this.name, this.model);
63 | },
64 | };
65 |
66 | car.Details(); // Lambo 2019
67 | ```
68 |
69 | `this` notation is useful when you need to access a property whose name is stored in a variable.
70 |
71 | #### Methods
72 |
73 | ```js
74 | // Object.keys() creates an array containg the keys of an object.
75 |
76 | // Intialize an object
77 | const employee = {
78 | boss: "Shubham",
79 | secretary: "Samarth",
80 | sales: "John",
81 | accountant: "Oscar",
82 | };
83 |
84 | // Let's say we want to see all the positions(keys) in the employee object
85 | const positions = Object.keys(employee);
86 | console.log(positions); // [ 'boss', 'secretary', 'sales', 'accountant' ]
87 |
88 | // Object.values() creates an array containg the values of an object.
89 | const session = {
90 | id: 1,
91 | time: `26-July-2022`,
92 | device: "Mobile",
93 | browser: "Chrome",
94 | };
95 |
96 | const sessionInfo = Object.values(session);
97 | console.log(sessionInfo); // [ 1, '26-July-2022', 'Mobile', 'Chrome' ]
98 |
99 | // Object.entries() creates an array containg the key/value of an object.
100 | const operatingSystem = {
101 | name: "Ubuntu",
102 | version: "20.04",
103 | license: "Open Source",
104 | };
105 |
106 | const entries = Object.entries(operatingSystem);
107 |
108 | console.log(entries); // [
109 | [ 'name', 'Ubuntu' ],
110 | [ 'version', '20.04' ],
111 | [ 'license', 'Open Source' ]
112 | ]
113 |
114 | // Intialize an object
115 | const user = {
116 | username: "Shubham",
117 | password: "12345",
118 | };
119 |
120 | const admin = Object.freeze(user);
121 |
122 | user.username = "Samarth"; // Trying to overwrite the object username
123 | console.log(user.username); // Shubham (remains the same);
124 |
125 | // Object.seal() prevents new properties
126 | // from being added to an object,
127 | // but allows the modification of existing properties
128 | // Intialize an object
129 |
130 | const user = {
131 | username: "Shubham",
132 | password: "12345",
133 | };
134 |
135 | const newUser = Object.seal(user);
136 |
137 | newUser.username = "Samarth"; // The username will be changed
138 | newUser.age = 23; // the age property will not be added because we applied Object.seal()
139 |
140 | console.log(user);// { username: 'Samarth', password: '12345' }
141 |
142 | ```
143 |
144 | The above block of code demonstrates four methods that are built into JavaScript: `Object.keys()`, `Object.values()`, `Object.entries()`, and `Object.freeze()`.
145 |
146 | - `Object.keys()` creates an array containing the keys (property names) of an object.
147 | - `Object.values()` creates an array containing the values of an object.
148 | - `Object.entries()` is a built-in JavaScript method that returns an array of an object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
149 | - `Object.freeze()` is a method in JavaScript that prevents an object from being modified. It makes the object's properties and values read-only, and prevents new properties from being added, removed, or modified. Once an object is frozen, you can no longer change its properties or values, and you cannot add or remove properties from the object.
150 |
151 |
--------------------------------------------------------------------------------
/7_Arrays_in_detail/Arrays.md:
--------------------------------------------------------------------------------
1 | ## Arrays in Detail
2 |
3 | **JavaScript array** is an object that represents a collection of similar type of elements.
4 |
5 | ```js
6 | let months = ["January", "February", "March", "April"];
7 |
8 | for (let i = 0; i < months.length; i++) {
9 | console.log(months[i]);
10 | }
11 | // January
12 | // February
13 | // March
14 | // April
15 | ```
16 |
17 | #### Array-Methods
18 |
19 | ```js
20 | const names = ["John", "Bob", "David", "Mark"];
21 |
22 | // Array Push - Adds a new element containing
23 | // the entered value to the end of the array
24 | names.push("Shubham");
25 | console.log(names); // [ 'John', 'Bob', 'David', 'Mark', 'Shubham' ]
26 |
27 | // Array Pop - Deletes the last element of an array
28 | names.pop();
29 | console.log(names); // [ 'John', 'Bob', 'David', 'Mark' ]
30 |
31 | // Array Shift - deletes the first element of the array
32 | names.shift();
33 | console.log(names); // [ 'Bob', 'David', 'Mark' ]
34 |
35 | // Array Unshift - adds the new value to the start of the array
36 | names.unshift("Samarth");
37 | console.log(names); // [ 'Samarth', 'Bob', 'David', 'Mark' ]
38 |
39 | // Array Splice - It adds or removes values in any position of an array
40 | names.splice(2, 0, "Shruti", "Rishi");
41 | console.log(names); // [ 'Samarth', 'Bob', 'Shruti', 'Rishi', 'David', 'Mark' ]
42 |
43 | names.splice(2, 2);
44 | console.log(names); // [ 'Samarth', 'Bob', 'David', 'Mark' ]
45 |
46 | // Array Slice - Copies certain part of an array into a newly created array
47 | const noOneLikesSam = names.slice(1);
48 | console.log(noOneLikesSam); // [ 'Bob', 'David', 'Mark' ]
49 | ```
50 |
51 | #### forEach method
52 |
53 | ```js
54 | const numbers = [2, 4, 6, 8];
55 |
56 | numbers.forEach((value, i) => console.log(value, i)); // prints all the values and indexes
57 |
58 | // when to use forEach :
59 | // You want to do something with each element in the array
60 |
61 | // Don't use when :
62 | // You want to stop or break the loop when some condition is true.
63 | // When you are working with async code.
64 |
65 | let sum = 0;
66 | numbers.forEach((value) => (sum += value));
67 | console.log(sum); // 20
68 | ```
69 |
70 | #### Map method
71 |
72 | ```js
73 | const inventory = [
74 | { price: 7, name: "egg" },
75 | { price: 10, name: "lays" },
76 | { price: 12, name: "maggie" },
77 | ];
78 |
79 | // Array Map
80 | const prices = inventory.map((item) => console.log(item.price)); // displays only the prices
81 | const names = inventory.map((item) => console.log(item.name)); // diplays only the names
82 | ```
83 |
84 | #### Array Filter
85 |
86 | ```js
87 | const numbers = [2, 5, -2, 0, -5, 1];
88 |
89 | const positiveNumbers = numbers.filter((number) => number >= 0);
90 | console.log(positiveNumbers);
91 |
92 | const negativeNumbers = numbers.filter((number) => number <= 0);
93 | console.log(negativeNumbers);
94 |
95 | // Another real life example
96 | const employeesData = [
97 | { name: "Shubham", overtime: 5 },
98 | { name: "Samarth", overtime: 7 },
99 | { name: "Seema", overtime: 8 },
100 | ];
101 |
102 | const employeesToReward = employeesData.filter(
103 | (employee) => employee.overtime >= 7
104 | );
105 |
106 | const employeeNames = employeesToReward.map((employee) => employee.name);
107 |
108 | employeeNames.forEach((user) => {
109 | console.log(`Congratulations, ${user}`); // Congratulations, Samarth
110 | // Congratulations, Seema
111 | });
112 | ```
113 |
114 | #### Array Find
115 |
116 | ```js
117 | // Array Find
118 |
119 | // The Find method for arrays returns the
120 | // first value that satisfies the condition
121 |
122 | const numbers = [1, 2, 3, 4, 5, 6, 7];
123 |
124 | const value = numbers.find((number) => number > 5);
125 | console.log(value); // 6
126 |
127 | const cities = ["Bangalore", "Mumbai", "New Delhi", "Noida", "Hyderabad"];
128 |
129 | const city = cities.find((city) => city.startsWith("N"));
130 |
131 | console.log(city); // New Delhi
132 | ```
133 |
134 | #### Array Includes
135 |
136 | ```js
137 | // Array Includes
138 | const movies = ["Avengers", "Superman", "Batman"];
139 |
140 | if (movies.includes("Avengers")) {
141 | console.log("The movie is available on prime"); // The movie is available on prime
142 | } else {
143 | console.log("The movie is not available on prime.");
144 | }
145 |
146 | // Note Includes method is case sensitive
147 | ```
148 |
149 | #### Array Sort
150 |
151 | ```js
152 | // Array sort => Alphabetically,
153 | // doesn't sort numbers
154 | // This sort method mutates the original array
155 | const names = ["Shubham", "Aditya", "Shruti", "Samarth"];
156 | names.sort();
157 | console.log(names); // [ 'Aditya', 'Shruti', 'Samarth', 'Shubham' ]
158 |
159 | const numbers = [4, 12, 8, 5, 1];
160 |
161 | // Ascending order
162 | numbers.sort((a, b) => a - b);
163 | console.log(numbers); // [ 1, 4, 5, 8, 12 ]
164 |
165 | // Descending order
166 | numbers.sort((a, b) => b - a);
167 | console.log(numbers); // [ 12, 8, 5, 4, 1 ]
168 | ```
169 |
170 | #### Some and Every
171 |
172 | ```js
173 | const array = [1, 2, 3, 4, 5];
174 |
175 | // Array Some => returns true if atleast one element passes the test
176 | console.log(array.some((number) => number > 5)); // false
177 |
178 | // Array Every => return true if all elements pass the test
179 | console.log(array.every((number) => number > 0)); // true
180 | ```
181 |
182 | #### Array Reduce
183 |
184 | ```js
185 | // Array Reduce
186 |
187 | const groceryList = [29, 12, 45, 35, 87, 110];
188 |
189 | const total = groceryList.reduce((total, price) => total + price, 0);
190 |
191 | console.log(total); // 318
192 | ```
193 |
194 | All the code blocks above demonstrates how to use arrays and various array methods in JavaScript. An array is an object that represents a collection of similar type of elements. The code first defines an array `months` and then uses a `for` loop to iterate over the array, printing each element to the console. The code then demonstrates several array methods including `push`, `pop`, `shift`, `unshift`, `splice`, `slice`, `forEach`, `map`, `filter`, and `find`. The `push` method adds a new element to the end of the array, the `pop` method removes the last element of an array, the `shift` method removes the first element of an array, the `unshift` method adds a new value to the start of the array, the `splice` method adds or removes elements in any position of the array, the `slice` method copies a certain part of an array into a new array, the `forEach` method executes a provided function once for each array element, the `map` method creates a new array with the results of calling a provided function on every element in the array, the `filter` method creates a new array with all elements that pass the test implemented by the provided function, and the `find` method returns the first element in the array that satisfies a provided testing function.
195 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Creative Commons Legal Code
2 |
3 | CC0 1.0 Universal
4 |
5 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6 | LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8 | INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9 | REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10 | PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11 | THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12 | HEREUNDER.
13 |
14 | Statement of Purpose
15 |
16 | The laws of most jurisdictions throughout the world automatically confer
17 | exclusive Copyright and Related Rights (defined below) upon the creator
18 | and subsequent owner(s) (each and all, an "owner") of an original work of
19 | authorship and/or a database (each, a "Work").
20 |
21 | Certain owners wish to permanently relinquish those rights to a Work for
22 | the purpose of contributing to a commons of creative, cultural and
23 | scientific works ("Commons") that the public can reliably and without fear
24 | of later claims of infringement build upon, modify, incorporate in other
25 | works, reuse and redistribute as freely as possible in any form whatsoever
26 | and for any purposes, including without limitation commercial purposes.
27 | These owners may contribute to the Commons to promote the ideal of a free
28 | culture and the further production of creative, cultural and scientific
29 | works, or to gain reputation or greater distribution for their Work in
30 | part through the use and efforts of others.
31 |
32 | For these and/or other purposes and motivations, and without any
33 | expectation of additional consideration or compensation, the person
34 | associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35 | is an owner of Copyright and Related Rights in the Work, voluntarily
36 | elects to apply CC0 to the Work and publicly distribute the Work under its
37 | terms, with knowledge of his or her Copyright and Related Rights in the
38 | Work and the meaning and intended legal effect of CC0 on those rights.
39 |
40 | 1. Copyright and Related Rights. A Work made available under CC0 may be
41 | protected by copyright and related or neighboring rights ("Copyright and
42 | Related Rights"). Copyright and Related Rights include, but are not
43 | limited to, the following:
44 |
45 | i. the right to reproduce, adapt, distribute, perform, display,
46 | communicate, and translate a Work;
47 | ii. moral rights retained by the original author(s) and/or performer(s);
48 | iii. publicity and privacy rights pertaining to a person's image or
49 | likeness depicted in a Work;
50 | iv. rights protecting against unfair competition in regards to a Work,
51 | subject to the limitations in paragraph 4(a), below;
52 | v. rights protecting the extraction, dissemination, use and reuse of data
53 | in a Work;
54 | vi. database rights (such as those arising under Directive 96/9/EC of the
55 | European Parliament and of the Council of 11 March 1996 on the legal
56 | protection of databases, and under any national implementation
57 | thereof, including any amended or successor version of such
58 | directive); and
59 | vii. other similar, equivalent or corresponding rights throughout the
60 | world based on applicable law or treaty, and any national
61 | implementations thereof.
62 |
63 | 2. Waiver. To the greatest extent permitted by, but not in contravention
64 | of, applicable law, Affirmer hereby overtly, fully, permanently,
65 | irrevocably and unconditionally waives, abandons, and surrenders all of
66 | Affirmer's Copyright and Related Rights and associated claims and causes
67 | of action, whether now known or unknown (including existing as well as
68 | future claims and causes of action), in the Work (i) in all territories
69 | worldwide, (ii) for the maximum duration provided by applicable law or
70 | treaty (including future time extensions), (iii) in any current or future
71 | medium and for any number of copies, and (iv) for any purpose whatsoever,
72 | including without limitation commercial, advertising or promotional
73 | purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74 | member of the public at large and to the detriment of Affirmer's heirs and
75 | successors, fully intending that such Waiver shall not be subject to
76 | revocation, rescission, cancellation, termination, or any other legal or
77 | equitable action to disrupt the quiet enjoyment of the Work by the public
78 | as contemplated by Affirmer's express Statement of Purpose.
79 |
80 | 3. Public License Fallback. Should any part of the Waiver for any reason
81 | be judged legally invalid or ineffective under applicable law, then the
82 | Waiver shall be preserved to the maximum extent permitted taking into
83 | account Affirmer's express Statement of Purpose. In addition, to the
84 | extent the Waiver is so judged Affirmer hereby grants to each affected
85 | person a royalty-free, non transferable, non sublicensable, non exclusive,
86 | irrevocable and unconditional license to exercise Affirmer's Copyright and
87 | Related Rights in the Work (i) in all territories worldwide, (ii) for the
88 | maximum duration provided by applicable law or treaty (including future
89 | time extensions), (iii) in any current or future medium and for any number
90 | of copies, and (iv) for any purpose whatsoever, including without
91 | limitation commercial, advertising or promotional purposes (the
92 | "License"). The License shall be deemed effective as of the date CC0 was
93 | applied by Affirmer to the Work. Should any part of the License for any
94 | reason be judged legally invalid or ineffective under applicable law, such
95 | partial invalidity or ineffectiveness shall not invalidate the remainder
96 | of the License, and in such case Affirmer hereby affirms that he or she
97 | will not (i) exercise any of his or her remaining Copyright and Related
98 | Rights in the Work or (ii) assert any associated claims and causes of
99 | action with respect to the Work, in either case contrary to Affirmer's
100 | express Statement of Purpose.
101 |
102 | 4. Limitations and Disclaimers.
103 |
104 | a. No trademark or patent rights held by Affirmer are waived, abandoned,
105 | surrendered, licensed or otherwise affected by this document.
106 | b. Affirmer offers the Work as-is and makes no representations or
107 | warranties of any kind concerning the Work, express, implied,
108 | statutory or otherwise, including without limitation warranties of
109 | title, merchantability, fitness for a particular purpose, non
110 | infringement, or the absence of latent or other defects, accuracy, or
111 | the present or absence of errors, whether or not discoverable, all to
112 | the greatest extent permissible under applicable law.
113 | c. Affirmer disclaims responsibility for clearing rights of other persons
114 | that may apply to the Work or any use thereof, including without
115 | limitation any person's Copyright and Related Rights in the Work.
116 | Further, Affirmer disclaims responsibility for obtaining any necessary
117 | consents, permissions or other rights required for any use of the
118 | Work.
119 | d. Affirmer understands and acknowledges that Creative Commons is not a
120 | party to this document and has no duty or obligation with respect to
121 | this CC0 or use of the Work.
122 |
--------------------------------------------------------------------------------