Javascript ES6+ Cheatsheet

Javascript ES6+ Cheatsheet

·

8 min read

If you just got into programming there would be so many javascript scripts or syntaxes that need to familiarize yourself with, below are the most common syntaxes which you would need to know to start.

  1. Conditional Statement

    iF - Else Statement

     let status;
     let age = 20;
    
     if (age >= 65) {
       status = "Elder";
     } else if (age >= 19) {
       status = "Adult";
     } else if (age >= 13) {
       status = "Teen";
     } else if (age >= 6) {
       status = "Child";
     } else if (age >= 2) {
       status = "Toddler";
     } else {
       status = "Baby";
     }
    

    Switch

     switch (
       new Date().getDay() // input is current day
     ) {
       case 6: // if (day == 6)
         text = "Saturday";
         break;
       case 0: // if (day == 0)
         text = "Sunday";
         break;
       default:
         // else...
         text = "Whatever";
     }
    
  2. Variable

     var globalVariable = 10;
     const finalVariable = 10;
     let localVariable = 10;
    
     let a,
       b,
       c = 10;
    
  3. Data Types

     // Number: an integer or floating point
     let numbers_type = 23;
     // String: Contextual data
     let string_type = "This is string";
     // Boolean: Any of two value
     let boolean_type = true || false;
    
     // Object: Key-value pair collective data
     let object_type = {
       number_type: 23,
       string_type: "This is string",
       boolean_type: true || false,
     };
    
     // Undefined: a variable which haven't been initialized
     let undefined_type;
    
     // Null: denotes a null value
     let null_type = null
    
  4. Arrays

     let fruit = ["Banana", "Apple", "Pear"];
    

    Array Methods

     const java = ['j', 'a', 'v', 'a']
     const script = ['s', 'c', 'r', 'i', 'p', 't']
    
     // concat(): Join several arrays into one
     const concat = concat()java.concat(script) //["j", "a", "v", "a", "s", "c", "r", "i", "p", "t"]
    
     // indexOf(): Returns the first position at which a given element appears in an array
     const indexOf = java.indexOf('a') // 1
    
     // join(): Combine elements of an array into a single string and return the string
     const join = java.join() // "j,a,v,a"
     const join_with_seperator = java.join('-') // "j-a-v-a"
    
     // lastIndexOf(): Gives the last position at which a given element appears in an array
     const last_index_of = java.lastIndexOf('a') // 3
    
     // pop(): Removes the last element of an array
     java.pop() // java = ["j", "a", "v"]
    
     // push(): Add a new element at the end
     java.push('new value') // java = ["j", "a", "v", "a", "new value"]
    
     // reverse(): Reverse the order of the elements in an array
     java.reverse() // java = ["a", "v", "a", "j"]
    
     // shift(): Remove the first element of an array
     const removed_value = java.shift() // j and java = ["a", "v", "a"]
    
     // slice(): Pulls a copy of a portion of an array into a new array
     const second_to_end = script.slice(1) // ["c", "r", "i", "p", "t"]
     const second_to_fifth = script.slice(1, 5) // ["c", "r", "i", "p"]
    
     // sort(): Sorts elements alphabetically
     java.sort() // java = ["a", "a", "j", "v"]
    
     // splice(): Adds elements in a specified way and position
     java.splice(2, 0, 'One', 'two') // java = ["j", "a", "One", "two", "v", "a"]
     const removeElements = java.splice(2, 1) // ["v"] and java = ["j", "a", "a"]
    
     // unshift(): Adds a new element to the beginning
     const new_array_length = java.unshift('One', 2) // 6 and java = ["One", 2, "j", "a", "v", "a"]
    
  5. Operators

    Basic Operators

     const addition              = 1 + 1         // 2
     const subtraction           = 2 - 1         // 1
     const multiplication        = 2 * 2         // 4
     const division              = 4 / 2         // 2
     const grouping_operator     = 1 + (2 * 3)   // 7
     const modulus_or_remainder  = 5%2           // 1
     const increment_numbers     = 5++           // 6
     const decrement_numbers     = 5--           // 4
    

    Comparison Operators

     const equal_to                  = (10 == '10')                  // true
     const equal_value_and_type      = (10 === '10')                 // false
     const not_equal                 = (10 != 11)                    // true
     const not_equal_value_or_type   = (10 === '10')                 // false
     const greater_than              = (10 > 11)                     // false
     const less_than                 = (10 < 11)                     // true
     const greater_than_or_equal_to  = (10 >= 11)                    // false
     const less_than_or_equal_to     = (10 <= 11)                    // true
     const Ternary_operator          = (10 == 11 ? 'true' : 'false') // 'false'
    

    Logical Operator

     const logical_and     = (true && false)       // false
     const logical_or      = (true || false)       // true
     const logical_not     = (!false)              // true
    
  6. Global Function

     // isNaN(): Determines whether a value is NaN (Not a Number)
     isNaN(123) //false
     isNaN('123') //false
     isNaN('Hello') //true
    
     // parseFloat(): Parses a string and returns a floating point number
     let a = parseFloat("10") // 10
     let b = parseFloat("10.00") // 10
     let c = parseFloat("10.33") // 10.33
    
     // parseInt(): Parses a string and returns an integer
     let a = parseInt("10") // 10
     let b = parseInt("10.00") // 10
     let c = parseInt("10.33") // 10
    
     // String(): Converts an object's value to a string
     let x1 = String(false); // 'false'
     let x2 = String(true);  // 'true'
     let x3 = String(new Date()); // 'Tue Jun 01 2021 22:29:05 GMT+0700 (Western Indonesia Time)'
     let x4 = String("12345"); // '12345'
     let x5 = String("12345"); // '12345'
    
     // eval(): Evaluates a string and executes it as if it was script code
     var a = eval("10 * 10"); // 100
     var b = eval("10 + 10"); // 20
    
  7. Loop

     let java = ['j', 'a', 'v', 'a']
     let person = {firstname: 'Java', lastname: 'Script'}
    
     // For: Loops through a block of code a number of times
     let text = '' // Java
     for (i = 0; i < java.length; i++) {
       text += java[i]
     }
    
     // For In: Loops through the properties of an object
     let text = ""; // Java Script
     for (let x in person) {
       text += person[x] + " ";
     }
    
     // For Of: Loops through the values of an iterable object
     let text = '' // Java
     for (let x of java) {
       text += java[x]
     }
    
     // While: loops through a block of code while a specified condition is true
     let evenNumbers = [] // [0, 2, 4, 6, 8]
     let i = 0
    
     while (i < 10) {
       if (i%2 == 0) {
         evenNumbers.push(i)
       }
       i++;
     }
    
     // Do While: Loops through a block of code while a specified condition is true
     let evenNumbers = [] // [0, 2, 4, 6, 8]
     let i = 0;
    
     do {
       if (i%2 == 0) {
         evenNumbers.push(i)
       }
       i++;
     }
     while (i < 10);
    
     // Break: Is used to jumps out of the loop
     let text = '' // Ja
     for (i = 0; i < java.length; i++) {
       if (i === 2) { break; }
       text += java[i]
     }
    
     // Continue: Is used to jumps over the loop
     let text = '' // Jaa
     for (i = 0; i < java.length; i++) {
       if (i === 2) { continue; }
       text += java[i]
     }
    
  8. String Methods

     let java = "Java";
     let script = "Script";
     let javaScript = "Java Script"
    
     // charAt: Returns the character at the specified index in a string
     const firstCharacter = java.charAt(0); // J
    
     // concat: Is used to join two or more strings.
     const firstCharacter = java.concat(" ", script); // Java Script
    
     // indexOf: Returns the position of the first occurrence of a specified value in a string
     const index = java.indexOf(a); // 1
    
     // lastIndexOf: Returns the position of the last occurrence of a specified value in a string.
     const index = java.lastIndexOf(a); // 3
    
     // replace: Returns a new string where the specified values are replaced.
     const newJava = java.replace("Ja", 'newJa'); // newJava
    
     // slice: Returns the extracted parts in a new string
     const second_to_end = script.slice(1) // cript
     const second_to_fifth = script.slice(1, 5) // crip
    
     // split: Is used to split a string into an array of substrings, and returns the new array
     const jsArray = javaScript.split(" "); // ["Java", "Script"]
    
     // substr: Returns a portion of the string from given start and end index
     const fifth_to_end = script.substr(5) // Script
     const fifth_to_ninth = script.substr(5, 4) // Scri
    
     // toLowerCase
     const lowerCaseJava = java.toLowerCase() // java
    
     // toUpperCase
     const upperCaseJava = java.toUpperCase() // JAVA
    
  9. Number Methods

     // toFixed: Rounding to a specified number of decimals
     const decimalNum = 1.23456;
     const n = decimalNum.toFixed(2); // 1.23
    
  10. Math Methods

    const decimalNumber = 1.4
    
    // ceil: Rounds a number UPWARDS to the nearest integer
    const upWardsRounded = Math.ceil(decimalNumber) // 2
    // floor: Rounds a number DOWNWARDS to the nearest integer
    const downWardsRounded = Math.floor(decimalNumber) // 1
    // max: returns the number with the highest value
    const maxNumber = Math.max(5, 10) // 10
    // min: returns the number with the lowest value
    const minNumber = Math.min(5, 10) // 5
    
  11. Dealing with Dates

    const today = new Date()
    // Mon Jul 20 2020 10:20:30 GMT+0700 (Western Indonesia Time)
    const specificDate = new Date(2020, 6, 20, 10, 20, 30, 0)
    // Mon Jul 20 2020 10:20:30 GMT+0700 (Western Indonesia Time)
    const specificStringDate = new Date("2020-06-20")
    // Sat Jun 20 2020 07:00:00 GMT+0700 (Western Indonesia Time)
    

    Pulling Date and Time Values

    const d = new Date(2020, 6, 20, 10, 20, 30, 0);
    // Mon Jul 20 2020 10:20:30 GMT+0700 (Western Indonesia Time)
    
    // getFullYear(): Get the year as a four digit number (yyyy)
    const fullYear = d.getFullYear() // 2020
    // getMonth(): Get the month as a number (0-11)
    const month = d.getMonth() // 6
    // getDate(): Get the day as a number (1-31)
    const date = d.getDate() // 20
    // getHours(): Get the hour (0-23)
    const hour = d.getHours() // 10
    // getMinutes(): Get the minute (0-59)
    const minutes = d.getMinutes() // 20
    // getSeconds(): Get the second (0-59)
    const seconds = d.getSeconds() // 30
    // getMilliseconds(): Get the millisecond (0-999)
    const milliseconds = d.getMilliseconds() // 0
    // getTime(): Get the time (milliseconds since January 1, 1970)
    const time = d.getTime() // 1595215230000
    // getDay(): Get the weekday as a number (0-6)
    const day = d.getDay() // 1
    
  12. Error

    try {
      // Block of code to try
      throw "My error message";    // throw a text
    }
    catch(err) {
      // Block of code to handle errors
    }
    finally { // This block is optional
      // Block of code to be executed regardless of the try / catch resul
    }
    
  13. JSON(JavaScript Object Notation)

    const jsonObject = {"firstName":"John", "lastName":"Doe"};
    
    const jsonArray = {
       "employees":[
         {"firstName":"John", "lastName":"Doe"},
         {"firstName":"Anna", "lastName":"Smith"},
         {"firstName":"Peter", "lastName":"Jones"}
       ]
    };
    
    // parse(): Convert JSON text into a JavaScript object
    const jsonString = '{"firstName":"John", "lastName":"Doe"}';
    const jsonObject = JSON.parse(jsonString) // {"firstName":"John", "lastName":"Doe"}
    
    // stringify(): Convert JavaScript object into a JSON text
    const jsonObject = {"firstName":"John", "lastName":"Doe"};
    const jsonString = JSON.stringify(jsonString) // '{"firstName":"John", "lastName":"Doe"}'