DEV Community 👩‍💻👨‍💻

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


  • 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.


  • .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){
        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 =;

Enter fullscreen mode Exit fullscreen mode


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];
            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;

        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(?)


  • 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){

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){

Enter fullscreen mode Exit fullscreen mode


  • 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) => {
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;
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


  • 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.

    COOKIE_EXPIRES = (new Date( + 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(';'),
    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.





Top comments (0)

Timeless DEV post...

How to write a kickass README

Arguably the single most important piece of documentation for any open source project is the README. A good README not only informs people what the project does and who it is for but also how they use and contribute to it.

If you write a README without sufficient explanation of what your project does or how people can use it then it pretty much defeats the purpose of being open source as other developers are less likely to engage with or contribute towards it.