Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SuperBonsaii/30551ea9f7d4b7bef48f2e65e4a02325 to your computer and use it in GitHub Desktop.
Save SuperBonsaii/30551ea9f7d4b7bef48f2e65e4a02325 to your computer and use it in GitHub Desktop.
YouTube Gists

Welcome

Hello Learner,

This is the home for all our code samples that we prepare for our YouTube Channel. Hope you find them useful.

Please look at our work at bonsaiilabs and let us know if there is anything that we can do to help you get better, smarter, and faster!

Thank you
bonsaiilabs team

// Writable property
'use strict';

let iPhone = {
    name: 'iPhone 11',
    color: 'blue'
}

console.log(iPhone)

iPhone["price"] = 600
console.log(iPhone)

iPhone["price"] = 0
console.log(iPhone)

// read-only property
'use strict';

let iPhone = {
    name: 'iPhone 11',
    color: 'blue'
}

Object.defineProperty(iPhone, "price", {
    value: 1200,
    writable: false, // default true
    enumerable: true
})

console.log(iPhone)

iPhone["price"] = 0
console.log(iPhone)
let transaction = {id: 119 ,name: 'Westfield clothing', amount: 45}

//Without Modifying transaction
let newTransaction = Object.assign({}, transaction, {category: 'Personal'})
console.log('Transaction: ', transaction);
console.log('New Transaction: ', newTransaction);


//Modify transaction: Approach 01
let newTransaction = Object.assign(transaction, {category: 'Personal'});
console.log('Transaction: ', transaction);
console.log('New Transaction: ', newTransaction);


//Modify transaction: Approach 02
transaction.category = 'Personal';
console.log('Transaction: ', transaction);
const users = {}

if(users && Object.entries(users).length === 0){
    console.log('Object is empty');
}
else console.log('Object is either null or undefined')
'use strict'

let person = {
    name: "Tony Stark",
    phone: "500-124-9900",
    location: "California",
    birthYear: 1972
}

console.table(person)
function getData() {
    console.time("github_time")
    fetch("https://api.github.com/users/hhimanshu")
    .then(response=>response.json())
    .then(user=> {
        console.table(user)
        console.timeEnd("github_time")
    })
}

getData()

Convert a JavaScript Array into Object

let realEstate = [
	{
        id: '3c5f4c26-f048-11e9-81b4-2a2ae2dbcce4',
		name: 'Vancouver Luxury Apartments',
        price: 450000
	},
	{
        id: '3c5f4e9c-f048-11e9-81b4-2a2ae2dbcce4',
		name: 'Calgary Housing',
        price: 330000
	},
	{
        id: '3c5f52d4-f048-11e9-81b4-2a2ae2dbcce4',
		name: 'AGM Apartments',
        price: 300000
	}
];


function reducer(acc, cur) {
    return {...acc, [cur.id]: cur}
}

let newRealEstate = realEstate.reduce(reducer, {})
console.log(newRealEstate)

without default parameters

function add(a, b) {
    console.log('a=' + a + ', b=' + b)
    let c = a + b;
    return c;
}

add(10, 20)
add()
add(10)
add(undefined, 20)

with default parameters

function add(a = 0, b = 0) {
    console.log('a=' + a + ', b=' + b)
    let c = a + b;
    return c;
}

add(10, 20)
add()
add(10)
add(undefined, 20)

The HTML

<!DOCTYPE html>
<html lang="en">

  <head>
    <title>bonsaiilabs - DOM 101</title>
  </head>

  <body>
    <h1 lang="en" style="color: blue">Learning DOM with <i>bonsaiilabs</i></h1>
    
    <h3>Team Members</h3>
    <ul>
      <li>Harit Himanshu: @harittweets</li>
      <li>Deeksha Sharma: @deekshasharma25</li>
    </ul>
  </body>

</html>

Accessing the DOM

Get the Document

this.document
document

this.document === document // true

Get a Node in the Document

document.getElementsByTagName('h1')[0]

Get the Element type from the Node

document.getElementsByTagName('h1')[0].nodeType; // 1

Node Types Constants

Get the NodeList from the Document

document.getElementsByTagName('ul')[0].childNodes
document.getElementsByTagName('ul')[0].childNodes instanceof NodeList // true

Get the NamedNodeMap from the Document

document.getElementsByTagName('h1')[0].attributes

Get the Attribute from the Element

document.getElementsByTagName('h1')[0].attributes[0] instanceof Attr
document.getElementsByTagName('h1')[0].attributes[0].name
document.getElementsByTagName('h1')[0].attributes[0].value

Modifying the DOM

Changing the backgroundColor of the Document

document.body.style.backgroundColor = "yellow"

Changing the text for H3 Element in the Document

document.getElementsByTagName('h3')[0].innerHTML = "bonsaiilabs Team Members"

Removing a Node from the Document

document.getElementsByTagName('ul')[0].firstElementChild.remove()
/** 
Example 01 
Goal: filter userNames that are valid strings
**/
let userNames = ['harry22', 'albert12', 'bonsaii24', 'deeksha25', undefined, null];
let filtered = userNames.filter((name) => typeof name === 'string')
console.log(filtered)


/** 
Example 02 
Goal: filter userNames that are atleast 7 characters long
**/
let userNames = ['harry22', 'albert12', 'bonsaii24', 'deeksha25', undefined, null];
let filtered = userNames.filter((name) => typeof name === 'string' && name.length >= 7)
console.log(filtered)


/** 
Example 03 
Goal: Filter all users and their salaries where salary is > 3000
Note: This will also contain users that are null
**/
let userSalaries = [
  { user: "harry22", salary: 2000 },
  { user: null, salary: 3300 },
  { user: "bonsaii24", salary: NaN },
  { user: "deeksha25", salary: 3500 },
  { user: "", salary: 4000 },
];

let filtered = userSalaries.filter((item) => item.salary > 3000);
console.log(filtered)

/** 
Example 04 
Goal: Filter all users where salary is > 3000 and user exists
**/
let userSalaries = [
  { user: "harry22", salary: 2000 },
  { user: null, salary: 3300 },
  { user: "bonsaii24", salary: NaN },
  { user: "deeksha25", salary: 3500 },
  { user: "", salary: 4000 },
];

let filtered = userSalaries.filter((item) => item.user && item.salary > 3000);
console.log(filtered)


/** 
Example 05 
Goal: Filter all the item where name doesnot exist
**/
let userSalaries = [
  { user: "harry22", salary: 2000 },
  { user: null, salary: 3300 },
  { user: "bonsaii24", salary: NaN },
  { user: "deeksha25", salary: 3500 },
  { user: "", salary: 4000 },
];

let filtered = userSalaries.filter((item) => !item.user && item.salary > 3000);
console.log(filtered)

A simple For loop

for (var i = 0; i < 10; i++) {
  console.log(i);
}

The for loop with var creates variable in global scope

for (var i = 0; i < 10; i++) {
  console.log(i);
}

console.log(i); // 10

The for loop with let create the variable in block scope.

for (let i = 0; i < 10; i++) {
  console.log(i);
}

console.log(i); // ReferenceError

The for loop with var jumping over 2 numbers

for (let i = 0; i <= 10; i = i + 2) {
  console.log(i);
}

The variable in for loop initialization cannot be a const, as you are updating a variable

for (const i = 0; i <= 10; i = i + 2) {
  console.log(i);
}

The for .. in loop

Get all the peoperties in the object

let weekDays = {
    'Sunday': 0,
    'Monday': 1,
    'Tuesday': 2,
    'Wednesday': 3,
    'Thursday': 4,
    'Friday': 5,
    'Saturday': 6,
}

for (let property in weekDays) {
    console.log(property)
}

Get all the enumerable properties and values associated to the properties in the object

let weekDays = {
    'Sunday': 0,
    'Monday': 1,
    'Tuesday': 2,
    'Wednesday': 3,
    'Thursday': 4,
    'Friday': 5,
    'Saturday': 6,
}

for (let property in weekDays) {
    console.log(property, '=>', weekDays[property])
}

The for .. in loop does not iterate on non-enumerable properties

let weekDays = {
    'Sunday': 0,
    'Monday': 1,
    'Tuesday': 2,
    'Wednesday': 3,
    'Thursday': 4,
    'Friday': 5,
    'Saturday': 6,
}

Object.defineProperty(weekDays, 'SomeOtherDay', {
    value: -1,
    enumerable: false,
})

for (let property in weekDays) {
    console.log(property, '=>', weekDays[property]) // SomeOtherDay will not be printed
}

The for .. of loop

Iterate over a String

let company = 'bonsaiilabs';

for (let character of company) {
    console.log(character)
}

Iterate over an Array

let tweetWords = ["bonsaiilabs", "content", "is", "fantastic!"];

for (let words of tweetWords) {
    console.log(words)
}

Iterate over a Map

let foodTastes = new Map();
foodTastes.set('cake', 'sweet')
foodTastes.set('pizza', 'salty')
foodTastes.set('vinegar', 'sour')

for (let foodTaste of foodTastes) {
    console.log(foodTaste[0], foodTaste[1])
}

Using Destructuring assignment

let foodTastes = new Map();
foodTastes.set('cake', 'sweet')
foodTastes.set('pizza', 'salty')
foodTastes.set('vinegar', 'sour')

for (let [food, taste] of foodTastes) {
    console.log(food, taste)
}

Iterate over an Set

let userIds = new Set(["bonsaiilabs", "meTheLearer", "internetBrowser"])

for (userId of userIds) {
    console.log(userId)
}
function add(a, b) {
    let c = a + b
    return c
}

console.log(add(10, 20))

Example 01

let studentData = ["John Doe", "Some School", 6, 7, 8, 7, 9, 9,-1, "Some School"];
let numbers = studentData.reduce((newArray,cur) => {
    if(typeof cur === "number") newArray.push(cur);
    return newArray
}, []);

console.log(numbers)

Example 02

let transcript = ['hello', 'there,', 'how', 'is', 'it', 'going?']
let finalTranscript = transcript.reduce((acc, cur) => acc+' '+cur)
console.log(finalTranscript)

Exanple 03

let realEstate = [
	{
        id: '3c5f4c26-f048-11e9-81b4-2a2ae2dbcce4',
		name: 'Vancouver Luxury Apartments',
        price: 450000
	},
	{
        id: '3c5f4e9c-f048-11e9-81b4-2a2ae2dbcce4',
		name: 'Calgary Housing',
        price: 330000
	},
	{
        id: '3c5f52d4-f048-11e9-81b4-2a2ae2dbcce4',
		name: 'AGM Apartments',
        price: 300000
	}
];

let total = realEstate.reduce((acc, cur) => acc+cur.price, 0);
let average = total/realEstate.length; 
console.log(average);

Pre ES6

let reminder = "Drink Water! "


let count = 0;
let result = '';
while (count < 10) {
    result += reminder;
    count += 1;
}

console.log(result)

ES6 Method

console.log("Drink Water! ".repeat(100))

console.log(reminder.repeat('100'))

console.log(reminder.repeat(3.5))

console.log(reminder.repeat(1/0))

console.log(reminder.repeat(-1))

console.log('*'.repeat(20))
'use strict';

let s = "I love JavaScript"
let splitResult = s.split("love")

let s = "I love JavaScript"
let splitResult = s.split("like")

let s = "bonsaiilabs"
let splitResult = s.split()

let s = "|JavaScript"
let splitResult = s.split("|")

let s = "|JavaScript|"
let splitResult = s.split("|")

let s = "bonsaiilabs"
let splitResult = s.split("")

let s2 = "bonsaiilabs,british columbia,BC,Canada"
let splitResult = s.split(",", 2)
let splitResult = s.split(",", 0)
let splitResult = s.split(",")
let splitResult = s.split(",", -1)
/**
 * Goal: Insert english2Gpa in the middle of english1Gpa
 */
let english1Gpa = [2.3, 2.80, 2.82];
let english2Gpa = [2.42, 2.47, 2.77];
let middleIndex = Math.floor(english1Gpa.length/2);
english1Gpa.splice(middleIndex, 0, ...english2Gpa);

console.log(english1Gpa);
const x = 10
console.log(x)
x = 60

const y = "Hello"
console.log(y)
y = "World"

const z = true
console.log(z)
z = false


const o = {"one": 1}
console.log(o)

//o = {"two": 2} // enable to fail
o["two"] = 2
console.log(o)
let name = "Deeksha"
typeof name
typeof name === "string" 

name = undefined
typeof name
typeof name === "undefined"

name = Symbol()
typeof name
typeof name === "symbol"

let isEmpty = true
typeof isEmpty
typeof === "boolean"

let salary = 1000
typeof salary
typeof salary === "number"

salary = 1000.14
typeof salary

let bigInteger = 8007199267890991n;
typeof bigInteger

let user = {id: 123, name: "Deeksha"}
typeof user
'use strict'

let person = {
    name: "Tony Stark",
    phone: "500-124-9900",
    emails: ["tony@stark.com", "ceo@stark.com"]
}

person["location"] = "California"
console.log(person)

let freezedPerson = Object.freeze(person)
freezedPerson.emails.push("investors@stark.com")
console.log(freezedPerson)
let emailTemplate = `
We, at <company>, believe in 
providing the best online education on JavaScript

If you like our content, please hit the like and 
subscribe to our YouTube channel

Thank you
<Company> team
`;

let replaced = emailTemplate.replace("<company>", "bonsaiilabs");
console.log(replaced)

let regex = /<company>/gi
let replacedRegEx = emailTemplate.replace(regex, "bonsaiilabs");
console.log(replacedRegEx)
var colors = ["#1AB399", "#66E64D", "#6666FF", "#E666B3", "#FF3380", "#B3B31A",
    "#FF4D4D", "#33991A", "#809980", "#4DB3FF", "#999933", "#99E6E6", "#CC9999",
    "#E666FF", "#CCCC00", "#4DB380", "#4D8066", "#991AFF", "#E6FF80", "#00E680",
    "#9900B3", "#4D80CC", "#66664D", "#1AFF33", "#E64D66"];

let changeColor = function () {
    let newColorIndex = Math.floor(Math.random(colors.length) * 10)
    let newColor = colors[newColorIndex]
    document.body.style.backgroundColor = newColor
}

let intervalId = setInterval(changeColor, 1000)
// clearInterval(intervalId) // to clear the interval

Spread An Array

let userNames = ['amy24', 'sam67', 'tero99', 'bonsaii', 'deeksha25'];
let allUserNames = [...userNames, 'tazo', 'rama01']
console.log(allUserNames);

Spread A String

let message = 'I love JS';
let spreadMessage = [...message];
console.log(spreadMessage);

Spread A Set

let toolSet = new Set();
toolSet.add('hammer');
toolSet.add('nails');
toolSet.add('driller');

let spreadToolSet = [...toolSet];
console.log(spreadToolSet)

Spread A Map

let idToName = new Map();
idToName['12hj3']= 'Deeksha';
idToName['445fg']= 'Bonsaii';
idToName['99hjy']= 'Amy';
let newIdToName = {...idToName};
console.log(newIdToName);

Spread An Object

let user = {
    name: 'Deeksha',
    username: 'deeksha25',
    interests: ['sketching', 'code', 'videos', 'book-reading']
}
let newUser = {...user};
console.log(newUser);

Avoid Making Mistakes

An attempt to create a variable in the global object

"use strict" // try with and without this line
a = 2;
console.log(a)

Qualifying this in strict mode

"use strict" // try with and without this line
function whoIsThis () {
    console.log(this === global)
}
whoIsThis()

Silent About Error to Throwing Error

Deleting a Variable

"use strict" // try with and without this line
let b = 2;
console.log(b);
delete b;

Deleting a Function

"use strict" // try with and without this line
function echo (me) {
    console.log(me)
}
echo("bonsaiilabs")
delete(echo)

Deleting an argument of a Function

"use strict" // try with and without this line
function echo (me) {
    delete me
    console.log(me)
}
echo("bonsaiilabs")
delete(echo)

Deleting the property of an Object

"use strict" // try with and without this line

let ironMan = {}
Object.defineProperty(ironMan, "name", {
    value: "Tony Stark",
    enumerable: true,
    configurable: false // also the default value
})

console.log(ironMan)

delete ironMan.name
console.log(ironMan)
const data = ["Jesenia Downard",
"200-677-0045",
"4716 3558 2962 8986",
"Phylis Sansom",
"434-642-3827",
"4532 0252 3274 0270",
"Chrissy Parsley",
"620-637-7861",
"3766 9798 5170 2343",
"Yoshiko Bernardi",
"936-433-5071",
"5186 4586 2667 8788",
"Myrtle Yoon",
"698-349-7435",
"3461 6706 6163 3320",
"Benny Coppage",
"844-291-9937",
"5361 6979 7003 8092",
"Hilde Garvin",
"275-219-1054",
"3791 5243 6221 2833",
"Liberty Goucher",
"278-451-7877",
"4539 1831 8210 9047",
"Nannie Lipka",
"515-274-7232",
"4916 5089 1053 5522",
"Lindsy Salais",
"241-378-3493",
"3764 9429 3142 8329"]

Matching the name - attempt 01

data.forEach(entry => {
    console.log('entry => ', entry);
    
    let regex = /[a-z]+/i;
    let result = entry.match(regex)
    
    console.log('result => ', result)
    console.log('-'.repeat(20))
})

Matching the name - attempt 02

let regex = /[a-z]+/gi;

Matching the name - attempt 03

let regex = /[a-z ]+/gi;
let regex = /[a-z \s]+/gi;

Matching Phone Numbers

data.forEach(entry => {
    console.log('entry => ', entry);
    console.log('matching phone number')
    let result = entry.match(/[0-9]{3}-[0-9]{3}-[0-9]{3}/g)
    console.log('result => ', result)
    console.log('-'.repeat(20))
})

Matching Credit Cards

data.forEach(entry => {
    console.log('entry => ', entry);
    console.log('matching phone number')
    let result = entry.match(/[0-9]{4}\s[0-9]{4}\s[0-9]{4}\s[0-9]{4}/g)
    console.log('result => ', result)
    console.log('-'.repeat(20))
})
let message1 = 'hello world!';
console.log('message1: ', message1)
console.log('type of message1: ',typeof message1)
console.log(message1.toUpperCase())


let message2 = String('hello world!');
console.log('message2: ', message2)
console.log('type of message2: ',typeof message2)
console.log(message2.toUpperCase())


let message3 = new String('hello world!');
console.log('message3: ', message3)
console.log('type of message3: ',typeof message3)
console.log(message3.toUpperCase())
let fruits = 'Banana,Strawberry,Apple,Peach';

//Length of fruits
let length = fruits.length;
console.log('Length of fruits: ', length);

//Without endIndex (default endIndex = length - 1)
console.log('Without endIndex => ', fruits.substring(2));

//startIndex and endIndex are same (returns empty string)
console.log('Same startIndex & endIndex => ',fruits.substring(3,3));

//index > length of the string (returns the length of the string)
console.log('startIndex > length => ',fruits.substring(length+1));
console.log('endIndex > length => ',fruits.substring(1,length+2));

//startIndex > endIndex (indexes are swapped)
console.log('startIndex > endIndex => ',fruits.substring(10, 2));

//startIndex || endIndex === NaN (index is treated as 0)
//startIndex || endIndex < 0 (index is treated as 0)
console.log('Invalid indexes => ',fruits.substring(-1));
console.log('Invalid indexes => ',fruits.substring(NaN));
let weather = "rainy"

// Using if statement
if (weather === "sunny") {
    console.log("Happy")
} else {
    console.log("Meh!")
}

// using ternary operator
weather === "sunny" ? console.log("Happy") : console.log("Meh!")
let text = `YOU might not make it to the TOP, but if you are doing what you love, 
there is much more happiness there than being RICH or FAMOUS`;

let upper = text.toUpperCase()
console.log(upper)
let lower = text.toLowerCase()
console.log(lower)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment