DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 964,423 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Javascript in's & outs 1
Vukani Gcabashe
Vukani Gcabashe

Posted on

Javascript in's & outs 1

Based on the books i have read through - I made this summary.

My Javascript Cheatsheet:

Javascript Strings

Access:

  • Accessing characters .chartAt(), 'dog'.chartAt(1) returns 0.

  • .chartAt(index); takes an index which starts at 0 and returns the character at that index.

  • .chartAt(start, finish) will returns character at start to finish position.

Search:

  • .indexOf(searchValue[fromIndex]) will help you search for for sub string within a string.

  • this function takes string to be searched and optional parameter for the starting index for the search & -1 if nothing is found.

  • the function .startsWith(?) will help you find out what the string starts with.

  • the function .endsWith(?) will returns true if the string ends with the parameter string.

  • to replace a string we use the function ' .replace('str1','str2')'

  • To check the occurance of a search string simply check if -1 was returned from .indexOf(?).

    var str = 'hey there Batch';
    var count = 0;
    var pos = str.indexOf('a');
    while(pos != -1){
        count++;
        pos = str.indexOf('a', pos + 1)
    }
Enter fullscreen mode Exit fullscreen mode

Regular Expressions:

Basic Regex:

  • ^ start of a string
  • \d: finds any digit
  • [abc] finds an character between the brackets
  • [^abc] finds character not in the bracket
  • [0 - 9] finds digit between the bracket
  • [^0 - 9] finds digit not between the bracket
  • (x|y) finds any of the alternatives specified

RegExp functions:

  • search(?) test for matches in a string and returns the index of the match.
  • match(?) test for matches in a string and returns all the matches.
  • exec(?) returns the first match.
  • test(?) returns true of false.
    var str = 'hey there Batch';
    var cn = str.search(/here/);
    console.log(cn);

Enter fullscreen mode Exit fullscreen mode

Objects:

Base64 Encoding:

  • The btoa(?) function creates a base64 encoded ASCII string from the string.
  • The atob(?) function will decode the base64 encoded string.

String Shortening:

var Dictionary = "sjhlksafhjksdhfjkdsflsdjlifhisdoncmx.nvmcx,grdj".split("");
Enter fullscreen mode Exit fullscreen mode
    function encoded(num) {
        var base = DICTIONARY.length
        var encoded="";

        if(num == 0){
            return DICTIONARY[0];
        }else{
            while(num > 0){
                encoded += DICTIONARY[(num % base)];
                num = Math.floor(num /base);
            }
        }

        return reverseWord(encoded);
    }

    function reverseWord(str){
        var reversed ="";
        for ( var i= str.length - 1; i >=0; i-- ){
            reversed +=str.charAt(i);
        }

        return reversed;
    }

    function decodeId(){
        var base = DICTIONARY.length;
        var decoded = 0;
        for (var index =0; index < id.split('').length; index++ ){
            decoded = decoded*base + DICTIONARY;
            indexOf(id.chartAt(index));
        }

        return decoded;
    }

Enter fullscreen mode Exit fullscreen mode

Javascript Arrays:

var arr = [1, 2, 3 . 4].

  • To access array elements we use its index arr[?]

  • To insert an array element arr.push(?)

  • To remove an element at the end arr.pop(?) another option to remove is arr.shift(?)

Iteration:

  • this method of iteration will call indices individually, and you will access the data inside it.
    var arr = [1,2,3];

    for(var index in arr){
        console.log(arr[index]);
    }

Enter fullscreen mode Exit fullscreen mode
  • this method will allow you to access and use the objects of the array individually each time you get one, you can do your checks this way.
    var arr = [1,2,3];

    for(var element of arr){
        console.log(element);
    }

Enter fullscreen mode Exit fullscreen mode

forEach():

  • this method is better than the other iteration methods because it can break out of the iteration or skip certain elements of the array.
    var arr = [1,2,3];

    arr.forEach((el, in) => {
        console.log(el);
    }
    )
Enter fullscreen mode Exit fullscreen mode

Array Helper Functions:

  • .slice(begin,end) will return us a portion of a given array taking the begining and end index of what you selecting.
    var arr = [1, 2, 3, 4, 5];
    arr.slice(1, 2); // returns [2] 
    arr.slice(2, 4); // returns [3, 4]
Enter fullscreen mode Exit fullscreen mode
  • .from() function will help us to create a new array from an existing one.
    var arr = [1, 2, 3, 4, 5];
    var arr2 = Array.from(arr);
Enter fullscreen mode Exit fullscreen mode
  • .splice() takes three params: begining & end index with number of things in the middle.After aplying the method the added other items will change the array.
    var arr = [1, 2, 3, 4, 5];
    arr.splice(); // returns [] 
    arr.splice(1, 2); // returns [2, 3], modifying arr = [1,4]
    arr.splice(1,2,5,6,7) // returns [2, 3], arr = [1, 5, 6, 7, 4] 
Enter fullscreen mode Exit fullscreen mode
  • .concat(?) will be used to add another array into an existing one. The method will return a modified array but stull the original one remains untouched.
    var arr = [1, 2, 3, 4, 5];
    arr.concat([1, 2]); // returns [1, 2, 3, 4, 5, 1, 2] and arr still remains the same
Enter fullscreen mode Exit fullscreen mode

Spread Operator:

  • this operator will allow use to access all elements individually.
    var arr = [1, 2, 3, 4, 5];

    function printNumz(a, b, c, d){
        return a + b + c + d;
    }
    console.log(printNumz(...arr))
Enter fullscreen mode Exit fullscreen mode

Array functional methods:

  • The .filter() method is used for filtering elements or checking a condition like the following example:
    var arr = [1, 2, 3, 4, 5];
    arr.filter(function (item) {
        return item > 2;
    }); // returns [3,4,5] 

Enter fullscreen mode Exit fullscreen mode
  • This method can allow you to perform other operations to the elements as you reach them in the erray.

  • We also have the .reduce() function that will combine all the elements in the erray into one value, using the passed function.

    var sum = [1, 2, 3, 4, 5].reduce(function(prevVal, currVal, index, array){
        return prevVal + currVal;
    });

Enter fullscreen mode Exit fullscreen mode

Cookies:

  • to check if cookies are enabled we use the pattern with corresponding code to set the cookie, note that it might not work for older browsers.
    if(navigation.cookieEnabled === False) {
        // Do something...
    }

    var COOKIE_NAME = 'Example cookie'; // naming the cookie.
    var COOKIE_VALUE = 'Something '; // the value of the cookie.
    var COOKIE_PATH = '/foo/bar'; // GIVE THE COOKIE A PATH.
    var COOKIE_EXPIRES;

    COOKIE_EXPIRES = (new Date(Date.new() + 6000 )). toUTCString();

    document.cookie += COOKIE_NAME + "=" + COOKIE_VALUE + "; expires=" + COOKIE_EXPIRES + "; path=" + COOKIE_PATH;
Enter fullscreen mode Exit fullscreen mode

Reading the cookie:

    var name = name + "=" + cookie_array = document.cookie.split(';'),
    cookie_value;
    for (var i = 0; i<cookie_array[i].length; i++){
        var cookie = cookie_array[i];
        while(cookie.charAt(0) == ''){
            cookie = cookie.substring(1, cookie.length);
        }
        if(cookie.indexOf(name) == 0){
            cookie_value = cookie.substring(name.length, cookie.length);
        }
    } 

Enter fullscreen mode Exit fullscreen mode
  • LocalStorage, sessionStorage are like js objects, so we can use them like they are:
   localStorage.greet = 'hey there'; // window.localStorage.setItem('')

   localStorage.greet; // window.localStorage.getItem('')

   delete localStorage.greet; // Same as: window.localStorage.removeItem('')

Enter fullscreen mode Exit fullscreen mode
  • sessionStorage uses the same storage as the localStorage but it will only be avaliable per session or for that window.

Web Workers:

  • a web worker is a way to run scripts in background threads var webworker = new Worker("./path/to/webworker.js");

  • you can also inject a script as a worker in a string the string is used in URL.createObjectURL():


    var workerData = "function someFunction() {}; console.log('More code');";
    var blobURL = URL.createObjectURL(new Blob(["(" + workerData + ")"], { type: "text/javascript" }));
    var webworker = new Worker(blobURL);

Enter fullscreen mode Exit fullscreen mode
  • service worker is a event-driven worker bound to the original site, it can control the site, and use its resources.

  • ITS A PROGRAMMABLE NETWORK PROXY,

  • IT WILL BE TERMINATED WHEN NOT IN USE.

  • IT HAS A LIFE CYCLE UNBOUND TO THE WEB PAGE.

  • IT NEEDS HTTPS.

Top comments (0)

πŸ‘‹ Welcome the newest DEV members

Head over to our Welcome Thread and say hello!