Skip to content

Instantly share code, notes, and snippets.

@raihan71
Last active December 31, 2020 04:15
Show Gist options
  • Save raihan71/78073bcc1fae4851e0f963313683143f to your computer and use it in GitHub Desktop.
Save raihan71/78073bcc1fae4851e0f963313683143f to your computer and use it in GitHub Desktop.
This is about my notes and gists about course from Brad Traversy - "Modern JS From The Beginning"

Modern javascript from the beginning

Useful Syntax

  • console.table(data) = visualized data with ta
  • typeof data = get to know type data of the variable
  • Number(string) = convert number any type to type of number
  • String(number) = convert number any type to type of string
  • toFixed(decimal) = to add custom decimal number
  • parseInt(string or number) = just parse to the integer
  • parseFloat(string or number) = parse to the float type
  • append shorthand = data+=val

Math Object

  • Math.PI = 3.14
  • Math.E = 2.32
  • Math.floor = to remove decimal 2.10 = 2
  • Math.random() * maxNumber + startNumber = to get randomize number
  • Math.abs = to get absolute number

Concatenation

  • Append value to a variable = val = rai; val+=han

Escaping

  • How to espace making normail string in single quote with backslash = val = 'let's split up';

Length

  • How to know exact length of variable = val = 'yes'; alert(val.length);

Concatenation with concat

  • Alternate concat with built-in js concatenation = val = name.concat(' ',lastname);

Change case

  • Uppercase = example.toUpperCase();
  • Lowercase = example.toLowerCase();

Indexing

  • How to know first index of the variable = example = 'yes'; val = example.indexOf('y'); // 0
  • How to know last index of the variable = example = 'yees'; val = example.lastIndexOf('e'); //1

CharAt

  • How to find or indexing in between of variable = example = 'yes'; val = example.charAt(1);
  • How to get last character of variable = example = 'yes'; val = example.charAt(example.length - 1);

Substring

  • How to get custom value from variable = example = 'yes'; val = example.substring(0,2);

Slice

  • Meaning you can slice or cut one variable to make new one variable = example = 'yes'; val = example.slice(-1);

Split

  • When you need making an array from string or object = example = 'sport code sleep'; val = example.split(''); // sport,code,sleep you can change split parameter related to special string of variable such as spaces,comas,so on.

Replace

  • When you want to find value in variable and want replace it = example = 'yes'; val = example.replace('yes','no'); // example = no

Includes

  • How to get boolean true or false in something variable = example = 'yes'; val.includes('yes'); otherwise you want to make false just search value that didnt exist.

Template Literals

  • You can making conditional in template literals doing calculation calling function = hello 2*2 you

Arrays and arrays methods

  • How to get length of array = example = [9,1,234,7]; val = example.length;
  • How to identify array or not = val = Array.isArray(example);
  • How to get single value from array = val = example[3];
  • Insert value with custom postion to an array = example[0] = 1;
  • Find index of value an array = val = example.indexOf(1);
  • Added value to the end of array = example.push(90);
  • Added value to the first of array = example.unshift(80);
  • Take off value from an array = val = example.pop();
  • Take off value from front of an array = val = example.shift();
  • slice array = example.splice(start position,how many element you want to remove, your value); //example.splice(1,1,"four")

Object Literals

  • Create object = let animal = {name:'Kimmy',type:'dog'};
  • Get spesific value of the object = console.log(animal.name,animal.type) or console.log(animal['name']);
  • Create function in object literal = let.getBirth = function(){};

Date

  • Create new date = let today = new Date();
  • Set new date = let birthday = new Date("May 10 1999") new Date("05-10-1999");
  • Get day = today.getDay();
  • Get month = today.getMonth();
  • Get date = today.getDate();
  • Get full year = today.getFullYear();
  • Get hours = today.getHours();
  • Get minutes = today.getMinutes();
  • Get seconds = today.getSeconds();
  • Get milliseconds = today.getMilliseconds();
  • Get fulltime = today.getTime(); Otherwise you can manipulate date like setDate, setMonth, setSeconds

Statement & Comparison

  • create val = 20; if(val == 20){return false};
  • using else val = 20; if(val == 20){return true}else{return false};
  • value not defined, val = 20; if(typeof val !== 'undefined'){return val}else{return false};
  • logical operator val = 20; if(val == 20 && val == 1){return true}else{return false};
  • or operator val = 20; if(val == 20 || val != 20){return true};
  • ternary operator console.log(val === 20 ? true : false);
  • switch conditional = switch(val){case '20': return true; break; case '11': return false; break; default: return true; break;}

Functional Declarations & Expressions

  • Create function declarations = function getName(){console.log('name Raihan');}
  • Create function expressions = const alert = function getAlert(){alert('yeahh');};
  • Create immediately invokable function express = (function((){ console.log('invoke here')})();
  • Create function with property and methods = const animal = {add: function(){console.log('animal added')},edit:function(){}}

Loops & Iterations

  • For loop = for(let i = 0; i < 10; i++){if(i === 3){console.log('you got me');continue;}console.log(i);}
  • While loop
  • Do while loop
  • Loop through array
  • Foreach loop
  • Map loop
  • For in loop

Window Object

  • window.alert();
  • console.log(window) // to see another built-in method of window;

Mouse event

  • btn.addEventListner('click', function(() e => {{console.log(e)}}); //its triggered when clicked
  • btn.addEventListner('dbclick', doSomething); //its fired up when double clicked
  • btn.addEventListner('mousedown', doSomething); //its trigged we when hold mouse
  • btn.addEventListner('mouseup', doSomething); //its fired up
  • btn.addEventListner('mouseenter', doSomething);

Keyboard & Input Events

  • e.preventDefault() // to prevent form redirect to action page
  • addEventListener('keydown', runSomething); // fired up when typing
  • addEventListener('keyup', runSomething); // fired up when release of typing some words
  • addEventListener('keypress', runSomething); // same like keydown
  • addEventListener('focus', runSomething); // when mouse/cursor focus to own its element
  • addEventListener('blur', runSomething); // when mouse/cursor focus then leave its element
  • addEventListener('cut') // when cut text or value from its element
  • ('paste') // when paste something text or value to its element
  • ('input') // === ['cut','paste']
  • ('change') // fired up on change input such for select

Scope and Block Scope

  • let, var, const

Local vs Session Storage

  • localStorage.setItem('item', 'value') // to set an item and value
  • localStorage.getItem('name') // to get item
  • localStorage.removeItem('name') // to remove an item name
  • localStorage.clear() // to delete entire item on storage set to clear
  • sessionStorage.setItem('item', 'value') // to set an item and value with sessionstorage rest of sessions method same as localstorage. What makes different is.. when you set session it'll save for while or temporary when browser still active or opened. For localstorage is different case which means, it save forever otherwise come with expired time.

Export & Import Modules

  • default export = const person = {raihan} export default person;
  • named export = const person = {raihan} const car = {bmw} export person; export car;
  • import all object from module = import * as all from 'profile.js';
  • import { person } from named export, single import object;
  • import { person, car } from named export for importing more than one object;

Classes

  • constructor(){} //default method function that fired up first time when js file executed.
  • super() // method function for accessing parent class from children classes.
  • const person = new Person(); // to activate or using the class.

Spread && Rest Operators

  • ... // spread operator = is to add all value from an array to new array; const numbers = [1,2,3,4]; const newNumbers = [...numbers,5] = 1,2,3,4,5
  • ... for object // it's also can be using by object; const numbers = {first:1,second:2}; const new = {...numbers,fourth:4} = {first:1,second:2,fourth:4}
  • (..args) // rest operator = to add & collect all params in one arguments;

Destructuring

  • const numbers = [1,2,3];

New keyword

  • new Array(1,2,3);
  • new Object({name:'Raihan'})
  • new Number(1);
  • new String('raihan');
  • new Function('param','return param');

ES6 Classes

  • class Person { constructor(){ const data } staic }
  • static method/function is used for static outside function from parent

Async JavaScript, Fetch API

  • XMLHttpRequest
  const http = new XMLHttpRequest();
  http.open('GET', url, true);
  • Ajax Request
  • Fetch Request
  fetch(url)
    .then((res) => res.json())
    .then((res) => {
      if (!res.ok) throw new Error(res.error);
      return res;
    }).catch((err) => alert(err));
  • Third party library http request:
  • Axios
  • Simplified

ES6

  • Promises
  function set(param){
    return new Promises((resolve, reject) => {
      setTimeout((){
       resolve();
       if (!param) reject('err idk');
       else resolve();
      }, 3000);
    });
  }
  
  set({data:'promises}).then(alert('we did it!').catch(() => { console.log(err); });
  • Fetch API Create class first
 post(url, data) {
   return new Promise((resolve, reject) => {
     fetch(url, {
       method: 'POST',
       headers: {
         'Content-Type': 'application/json'
       };
       body: JSON.stringify(data)
     })
     .then(res => res.json())
     .then(data => resolve(data))
     .catch(err => reject(err));
   });
 }
 const http = new ExampleClass();
 http.post(url, data).then(data => console.log(data)).catch(err => console.log(err));
  • Async/Await Async return actual promise Await hold next action or resolve from promise to call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment