Skip to content

Instantly share code, notes, and snippets.

@hhimanshu
Last active September 5, 2019 17:27
Show Gist options
  • Save hhimanshu/dfe2669b70a1f6234c792a818fc4338a to your computer and use it in GitHub Desktop.
Save hhimanshu/dfe2669b70a1f6234c792a818fc4338a to your computer and use it in GitHub Desktop.
Web Development Phase 01 Code Samples (for Mentoring Sessions)

for loop

let numUsers = 0;
for(let num = 0; num < 22; num++){
  numUsers = numUsers+1;
}
console.log('Number of users are: '+ numUsers); //implicit coercison from number to string
let numUsers = 0;
for(let num = 10; num >= 0; num--){ 
  console.log(num)
}
let num = 0;
  for(let num = 0; num < 22; num += 2){
     console.log(num)
  }

for..in loop to iterate on objects

let appUser = {
    name: 'bonsaii',
    id: '123efg',
    isNew: false,
    interest: 'technology',
    score: 120
}
for (let property in appUser) {
    console.log(appUser[property])
}
let appUser = {
    name: 'bonsaii',
    id: '123efg',
    isNew: false,
    interest: 'technology',
    score: 120
}
for (const property in appUser) { //with const
    console.log(appUser[property])
}

while loop

let counter = 0;

while (counter < 10) {
  counter++;
  console.log(counter);
}
const counter = 0; //with const

while (counter < 10) {
  counter++;
  console.log(counter);
}

Function Declaration

'use strict'
function add(a, b) {
    let c = a + b;
    return c;
}

console.log(add(10, 20));

Undefined Parameters

function add(a, b) {
    console.log(a, "|", b)
}
add(10, 20)
add()
add(10)
add(undefined, 10)

Without Default Parameters

'use strict';
function add(a, b) {
    let aValue = a !== undefined ? a: 0;
    let bValue = b !== undefined ? b: 0
    return aValue + bValue;
}
console.log(add(10, 20))
console.log(add()) // both a and b are undefined
console.log(add(10)) // b is undefined
console.log(add(undefined, 10)) // a is undefined

With Default Parameters

// ES6 - with default parameters
'use strict';
function add(a = 0, b = 0) {
    return a + b;
}
console.log(add(10, 20))
console.log(add()) // both a and b are undefined
console.log(add(10)) // b is undefined
console.log(add(undefined, 10)) // a is undefined

Without Rest Parameters

'use strict';
function userAccounts(userName, socialAccount1, socialAccount2) {
    let message = userName + ' has 2 social accounts - ' + socialAccount1 + ', ' + socialAccount2;
    console.log(message);
}

userAccounts("Sam", "Facebook", "Twitter");
userAccounts("Amy", "LinkedIn", "Reddit");

With Rest Parameters

'use strict';
function userAccounts(userName, ...socialAccounts) {
    let allUserAccounts = '';
    for (let index=0; index<socialAccounts.length; index++) {
        allUserAccounts += socialAccounts[index] + ', ';
    }
    console.log(userName + ' has ' + socialAccounts.length + ' social accounts - ' + allUserAccounts);
}

userAccounts("Sam", "Facebook", "Twitter");
userAccounts("Amy", "LinkedIn", "Reddit");

userAccounts("Cindy", "Facebook");
userAccounts("Dan", "Facebook", "LinkedIn", "Twitter", "Reddit");

Rest Parameters Error

'use strict';
function userAccounts(...socialAccounts, userName) {
    let allUserAccounts = '';
    for (let index=0; index<socialAccounts.length; index++) {
        allUserAccounts += socialAccounts[index] + ', ';
    }
    console.log(userName + ' has ' + socialAccounts.length + ' social accounts - ' + allUserAccounts);
}

userAccounts("Sam", "Facebook", "Twitter");

Function Expressions

with Function Declaration

'use strict'
function add(a, b) {
    return a + b;
}

console.log(add(10, 20));

with Expression

'use strict'
let z = function add(a, b) {
    return a + b;
}

console.log(typeof z); // function

let sum = z(10, 20);
console.log(sum);

Function Declaration and Hoisting

'use strict'

console.log(add(10, 20));

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

Function Expression and Hoisting

'use strict'

console.log(z(10, 20));

let z = function add(a, b) {
    return a + b;
}

Anonymous Functions

'use strict'

let z = function add(a, b) {
    return a + b;
}

console.log(z(10, 20));
'use strict'

let z = function add(a, b) {
    return a + b;
}

console.log(z(10, 20));
Anonymous functions with stacktraces

You get the name of function in the stacktrace

'use strict'

let z = function add(a, b) {
    throw new Error('blow up!')
}

console.log(z(10, 20));

You don't thet the name of the function in the stacktrace

'use strict'

let z = function(a, b) {
    throw new Error('blow up!')
}

console.log(z(10, 20));

Arrow Function Expressions

'use strict'

let z = function add(a, b) {
    return a + b
}
'use strict'

let z = (a, b) => {
    return a + b
}

console.log(z(10, 20))

Function Expression in one-line

'use strict'

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

function decl(a, b) {return a + b};
let namedExpr = function add(a, b) {return a + b}
let anonExpr = function(a, b) {return a + b}
let arrowExpr = (a, b) => {return a + b}
let arrowExprSlim = (a, b) => a + b
let arrowExprSlimUndef = (a, b) => {
    a + b
}

console.log("decl ->", decl(10, 20))
console.log("namedExpr ->", namedExpr(10, 20))
console.log("anonExpr ->", anonExpr(10, 20))
console.log("arrowExpr ->", arrowExpr(10, 20))
console.log("arrowExprSlim ->", arrowExprSlim(10, 20))
console.log("arrowExprSlimUndef ->", arrowExprSlimUndef(10, 20))

First-Class Functions

let bonsaiiLabs = {
    location: 'Victoria, BC',
    teamSize: () => 2
}
console.log(bonsaiiLabs.teamSize())

Functions as argument

function execFunction(callerName, callerAge) {
    console.log('Caller Name: ' + callerName);
    console.log('Caller Age: ' + callerAge);
}

execFunction("James", 42);
function execFunction(callerName, callerAge, func) {
    console.log('Caller Name: ' + callerName);
    console.log('Caller Age: ' + callerAge);
    func();
}

const f = () => console.log('I was passed as an argument!!!');

execFunction("James", 42, f);

Function as a Value

function greeter(userName) {
    console.log('Welcome ', userName);
}

greeter("Ana");
greeter("James");
function globalGreeter(userName) {
    const func = (lang) => console.log(lang + " " + userName);
    return func;
}

const greetAna = globalGreeter("Ana");
console.log(typeof greetAna);

greetAna("Welcome");
greetAna("Bienvenue")
greetAna("Hola")

Recursion

While Loop

'use strict';

function countDownToZero(number) {
    while(number >= 0) {
        console.log(number);
        number = number - 1;
    }
    console.log("Countdown Over!");
}

countDownToZero(4);

with Recursion

'use strict';
function countDownToZero(number) {
    if(number < 0) {
        console.log("Countdown Over!");
        return;
    }
    console.log(number);
    return countDownToZero(number - 1);
}

countDownToZero(10);

Variables Accessing the Outer Scope

'use strict';

const currencyConversionFromUSD = {
    'CAD': 1.32,
    'USD': 1.0,
    'NZD': 1.59,
    'INR': 72.20
};

const currencyService = (userName) => {
    let conversionRateFor = (currencySymbol) => {
        console.log("Hello " + userName + ", the rate from USD ->", currencySymbol, "is", currencyConversionFromUSD[currencySymbol]);
    }
    return conversionRateFor;
};

let amy = currencyService("Amy");
amy("CAD");
amy("NZD");

let sam = currencyService("Sam");
sam("INR");
sam("USD");

Information Hiding/Encapsulation using Closure

'use strict';

const bank = (accountHolderName, initialDeposit) => {
    let balance = initialDeposit;
    const add = (amount) => {
        balance += amount;
    }

    let subtract = (amount) => {
        balance -= amount
    }

    let printBalance = () => {
        console.log(accountHolderName, "has balance of", balance, "dollars");
    }

    return {
        credit: add,
        debit: subtract,
        balance: printBalance
    }
}

let amy = bank("Amy", 1000);
amy.balance();
amy.credit(100);
amy.balance();
amy.debit(10);
amy.balance();

let sam = bank("Sam", 50);
sam.balance();
sam.credit(50);
sam.balance();
sam.debit(100);
sam.balance();

a is not available outside.

'use strict';

(function () {
    let a = 10;
    console.log(a);
})();
console.log(a);

assigning result of IIFEs to variables

'use strict';

let x = (function () {
    let a = 10;
    return a;
})();
console.log(x);

Pass Arguments to IIFEs

'use strict';

let sum = (function(a, b) {
    return a + b;
})(10, 20);

console.log(sum);

IIFEs accessing parent scope

  • Also, reusing the variable name.
  • Helps in avoiding global namespace pollution.
  • Also, write is as arrow function. See teamSize below.
'use strict';

let obj = {};

(function() {
    let result = "bonsaiilabs";
    obj.name = result;
})();

(function() {
    let result = "Victoria, BC";
    obj.location = result;
})();

(() => obj.teamSize = 2)(); // arrow function

console.log(obj);

IIFEs help you namespace and modularize

'use strict';

const theCompany = (() => {
 return {
     name: 'bonsaiilabs',
     location: 'Victoria, BC',
     teamSize: () => 2
 };
})();

console.log(theCompany.name);
console.log(theCompany.location);
console.log(theCompany.teamSize());

Function Exercises

Write a function that concatenate 2 strings

let concat = (s1, s2) => s1 + ","  + s2
console.log(concat("Hello", "World!"))
  • Write a function that multiplies 3 numbers. Write using function declaration, named function expression, anonymous function and arrow function
  • Change this function implementation such that if the user does not provide any input, the function does not return undefined. Rather, it uses 1 as a reasonable default for product.

function declaration

function multiply(a, b, c) {
    const result = a * b * c;
    return result
}
console.log(multiply(1, 2, 3));
console.log(multiply(20, 30, 40));

named function expression

const multiply = function product(a, b, c) {
    return a * b * c;
}
console.log(multiply(1, 2, 3));
console.log(multiply(20, 30, 40));

anonymous function

const multiply = function (a, b, c) {
    return a * b * c;
}
console.log(multiply(1, 2, 3));
console.log(multiply(20, 30, 40));

arrow function

const multiply = (a, b, c) => a * b * c;
console.log(multiply(1, 2, 3));
console.log(multiply(20, 30, 40));

Using 1 as default value

const multiply = (a = 1, b = 1, c = 1) => a * b * c;
console.log(multiply());
console.log(multiply(2));
console.log(multiply(2, 3));
console.log(multiply(2, 3, 0));

Write a function called greet that takes 1 parameter called name. If the name is empty, it return "Hello Anonymous" else it returns "Hello" with the name appeneded. Write all form of functions - Function Declaration, Named Function Expression, Anonymouns Function, Arraor Function

function declaration

function greet(name) {
    const nameToUse = !name ? 'Anonymous': name;
    console.log("Hello, " + nameToUse);
}

greet("Amy")
greet("")
greet()
greet(0)
greet(null)
greet(undefined)
greet("James")

named function expression

const greet = function say(name) { 
    const nameToUse = !name ? 'Anonymous': name;
    console.log("Hello," + nameToUse);
}
greet("Amy")
greet("")
greet()
greet(0)
greet(null)
greet(undefined)
greet("James")

anonymous function

const greet = function(name) { 
    const nameToUse = !name ? 'Anonymous': name;
    console.log("Hello," + nameToUse);
}
greet("Amy")
greet("")
greet()
greet(0)
greet(null)
greet(undefined)
greet("James")

arrow function

const greet = (name) => { 
    const nameToUse = !name ? 'Anonymous': name;
    console.log("Hello," + nameToUse);
}
greet("Amy")
greet("")
greet()
greet(0)
greet(null)
greet(undefined)
greet("James")

Fix the following function so that it only add numbers. For now, it adds anything that it wants. It should return NaN if the inputs cannot be converted to a Number.

'use strict';
function add(a, b) {
    let c = a + b;
    return c;
}

console.log(add("Hello", ", World"))

Solution

'use strict';
function add(a, b) {
    let c = Number(a) + Number(b);
    return c;
}

console.log(add("Hello", ", World"))
console.log(add("2", 3))
console.log(add(12, "3"))
console.log(add(99, 1))

Consider the following function. Answer the questions below

const f = (key) => {
    let obj = {
        name: 'bonsaiilabs',
        location: 'Victoria, BC',
        size: () => 2
    };
    return obj[key];
}
  • What is the output of f(name)?
  • What is the output of f('name')?
  • What is the output of f('size')?
  • How can you execute the size function by calling f such that the output of that call is 2?
// Answer
ReferenceError: name is not defined
bonsaiilabs
[Function: size]
2

What's the output of the following code?

console.log(concat("Hello", "World!"))
let concat = (s1, s2) => s1 + ","  + s2
// Answer
ReferenceError: concat is not defined
    at Object.<anonymous> (/Users/harit/Downloads/a.js:1:13)
    at Module._compile (internal/modules/cjs/loader.js:816:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
    at Module.load (internal/modules/cjs/loader.js:685:32)
    at Function.Module._load (internal/modules/cjs/loader.js:620:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:877:12)
    at internal/main/run_main_module.js:21:11

What's the output of the following code?

console.log(f(10, 30));

let f = (a, b) => a + b;
function f(a, b) { return a * b };
// Answer
SyntaxError: Identifier 'f' has already been declared

What's the output of the following code?

let f = (a, b) => {
    a + b
};
console.log(f(10, 30));
// Answer
undefined

What's the output of the following code?

function func(number1, number2, functionToCall) {
    return functionToCall(number1, number2);
}

let f = (a, b) => a + b;
console.log(func(10, 2, f()));
//Answer
TypeError: functionToCall is not a function

Why?
console.log(func(10, 2, f())); <-- 
you are making a function call instead of passing the function. the functionToCall returns a number, which is not a function.

[intermediate] Implement the helloWorld such that the console statement prints true

const f1 = () => {
    const f = () => "Hello";
    return f;
}

const f2 = () => {
    const f = () => "World";
    return f;
}

let helloWorld = 'Not Implemented Yet!'
console.log(helloWorld === "Hello World");
// Answer
let helloWorld = f1()() + " " + f2()();

Write a function that takes a userName and the list of socialAccounts. The number of socialAccounts must be at least 1. If there are no socialAccounts, throw a new Error with a message "You must give at least 1 account". Otherwise, print the user name and the list of socialAccounts separated by comma.

Write a function called addUntil that takes an input number called num. Then add the numbers from 1 all the way up to the num. Then, finally return the result to the caller. If the function receives anything other than a number, it should throw an error - "You must provide a valid number".

Write a function called addEvenOdd that takes an input number called num. Then it calculates 2 sums - First one called valueOfoddSum, which adds all the odd numbers from 1 until num. - Second one called valueOfEvenSum, which adds all the odd numbers from 1 until num. The function addEvenOdd, then, returns an object {oddSum: valueOfOddSum, evenSum: valueOfEvenSum}.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment