Back

Table of contents

  1. Type the following in your HTML file:
    <script>
    //should be in your "head" tag
    console.log("Hello world")
    //in the console, the message "Hello world" will be printed out
    </script>
  2. Type the following in your HTML file:
    <script src = "script.js">
    </script>
  3. Javascript syntax:
    <script>
    // this is a comment
    /*
    this is also a comment
    */
    
    //you declared variable 'a' and its value is 10
    let a = 10;
    
    // this is what a javascript function looks like
    let function_a = (param)=>{
      let result = param * 2
      return result
    }
    </script>
  4. These are the following types of outputs:
    • // this is what it looks like in your JS file or tag
      //please go to your developer console or inspect element to see it in action!
      console.log(output)
    • // this is what it looks like in your JS file or tag
      alert(output)
  1. To declare a variable, type the following in your javascript file/tag:
    let var_1 = "Hello world"
    // the value of variable 'var_1' is "Hello world"
    To check the data type of a variable, type the following:
    typeof var_1
    //this returns the data type of given variable
    //it returns "string" in this case
  2. Similar to python, but take note of these too:
    1. ++ (increase by 1; also used in for-loops)
      let a  = 1
      let b = a++
      value of b is 1
    2. -- (decrease by 1; also used in for-loops)
      let c  = 1
      let d = c--
      value of d is 0
  3. This is how you can write a function:
    let funct_name = (param1)=>{
    output = param1 ** 2
    return output
    //output is the square of the value of variable 'param1'
    }
                            
    You can try it here:

    Expected output:

  4. There are 2 types of loops:
    • A for loop ends when the counter is greater or less than a certain value. Here is an example:
      // format is: for(i = startingValue, i < endingValue ; i ++ )
      // ending value can be less than i,a nd i ++ should be replaced with i -- if so.
      for(let i = 0, value,i++){
      //meant to 'print out the number'
      console.log(i)
      }
      You can try it here:

      Expected output:

    • A for loop ends when the counter is greater or less than a certain value. Here is an example:
      // format is: while( condition )
        // ending value can be less than i,a nd i ++ should be replaced with i -- if so.
        while(i > value){
        //meant to 'print out the number'
        i ++
      }
      You can try it here:

      Expected output:

  5. Below is an exmaple of a code where conditionals are used:
    // > means greater than
    // < means less than
    // === means equal to
    // || means 'or':
    // eg: (a< 10) || (a>20) means a has to be less than 10 or greater than 20 
    
    // && means 'and':  
    // eg: (a< 10) && (b>20) means a has to be less than 10 and b has to be greater than 20 
    if(value < 10){
     console.log("too low") 
     //first condition
    }
    else if(value < 20){
      console.log("still alright")
      //second condition (if conditions on top fails)
    } 
    else{
      // if all else fails!
      console.log("excellent")
    }
    You can try it here:

    Expected output:

  6. Here are the following data types + their functions:
    1. They can be used for text data.
      Here are the following functions and property that are currently used:
      1. This tells us the number of characters in the string like len() in Python, like this:
        let str = "test"
        let string_length = str.length 
        //string_length = 4
      2. Checks if a substring is inside a string
        let stringg = "omg"
        stringg.includes("o")
        //returns true
        
        string.includes("gg")
        //returns false
      3. .concat() joins strings together like this:
        let first = "Hello" 
        let second = "world"
        console.log(first.concat(second))
        //output is "hello world"
      4. This splits a string into an array of substrings like this:
        let string = "O M G"
        console.log(string.split(" ")) 
        //output:O,M,G
        //returns ["O","M","G"]
      5. Converts every letter in the string to uppercase and lowercase respectively like:
        let string = "I Love Javascript"
        
        let lowered = string.toLowerCase() 
        //lowered = i love javascript
        
        let uppered = string.toUpperCase()
        //uppered = I LOVE JAVASCRIPT
    2. They can be used to carry out math(aka arithmetic).
      Here are the following common uses:
      • This converts a number into a string like this:
        let num = 12
        num_1 = num.toString()
        //num_1 = "12"
      • It rounds off the number into n given decimal places. if "n" is blank, the number is rounded off to the nearest whole number
        let num = 5.6789
        console.log(num.toFixed(2))
        //displays 5.68
        
        console.log(num.toFixed())
        //displays 6
      • It rounds off the number to the nearest integer.
        Math.round(5.66) //this will return a 6
      • It rounds off the number to the next integer.
        Math.ceil(5.11) //this will return a 6
      • They work the same way as min() and max() in Python. below shows how they work.
        Math.min(3,5,6,8,2,1,9) 
        // returns 1
        Math.max(3,5,6,8,2,1,9) 
        // returns 9
      • This takes the integer part of a number like this:
        Math.trunc(7.99) 
        //returns 7
      • We can generate random numbers like this:
        //the format is Math.floor(Math.random()*higher_number) + lower_number
        console.log(Math.floor(Math.random()*11))
        //returns a random number from 0 to 11
        
        console.log(Math.floor(Math.random()*111)) +2
        //returns a random number from 2 to 111
    3. Boolean types are either "true" or "false", similar to Python, and they are usually involved in conditionals.
      • It can be done via the following:
        let arr = []  
        //arr = []
        
        let arr = new Array("a","b","c") 
        //arr  = ["a","b","c"]
      • Returns the number of items inside the array
      • Sorts the array. Used like this:
        let arr = [3,2,6,4]
        arr.sort()
        //now arr = [2,3,4,6]
      • Converts array into a string like this:
        let arr = ["abc","bcd","cde"] 
        arr = arr.toString()
        // now arr = "abc,bcd,cde"
                                              
      • You can use ".forEach()" to loop through an array like this:
        let arr = ["a","b","c"]
        arr.forEach((item)=> console.log(item))
        //displays each item in the console
      • You can use this to add an item into the array, similarly to how .append() works in python!
        let arr = [1,2,3] 
        arr.push(4)
        //arr = [1,2,3,4]
      • One way you can remove a specific element is:
        let target = 10
        let arr = [2,4,6,8,10,12,14]
        arr = arr.filter((item)=> item !== 10)
        //arr = [2,4,6,8,12,14]
    4. You can create Javascript objects like:
      const new_object = {
      //u can think of attribute as variable
      attribute_1:value_1,
      attribute_2:value_2,
      attribute_3:value_3,
      // you can think of method as functions, but usable only by occurrences of the object
      method_1:function(){
        //whatever u want it to do
      },
      method_2:function(){
        //whatever u want it to do
      },                                 
      
      }
      
      //to initialise an instance of object
      let new_instance = new_object()
      
      //to access an object's attribute
      new_instance.attribute_1 
      //this will return whatever the value of "attribute_1" of the instances is
      
      //this will make the instance call the function method_1
      //method_1 will run whatever that is inside it
      new_instance.method_1()
    5. The following data types are:
      • undefined:variable w/o value
      • empty(" "):a string but its EMPTY
      • null: means no value (equivalent to None in Python)
  1. Here are the selectors of the DOM and how they work:
    //selects element(s) with ID of "haha"
    let get_by_id = document.getElementById("haha")
    
    //selects elements by tag name; all anchor tags are chosen
    let get_by_id = document.getElementByTagName("a")
    
    //selects elements by class name; all element(s) with class "card" is/are chosen
    let get_by_id = document.getElementsByClassName("card")
    
    //selects elements by css selectors; all element(s) with CSS selector "a .item" are chosen
    let get_by_id = document.querySelectorAll("a .item")
    
  2. Here are the following events that can be handled:
    • onclick: user clicks on element
    • onchange: data in input forms change
    • onmouseover: when the user's mouse enters the element
    • onmouseout: when the user's mouse leave the element
    This is how events are handled:
    <!-- In your html file: -->
    <!-- In your element: event = function-->
    <!-- When this button is clicked, the function "clickMe()" is triggered -->
    <button onclick = "clickMe()"> Click Me! </button>  
    
    //in your JS file:
    //a common format is: target.addEventListener(event,function)
    let target = document.getElementById("haha")
    target.addEventListener("click",clickMe)

this.readyState

These are the following states:
  • 0:request not initialised
  • 1:server connected
  • 2:request received
  • 3:request is processing
  • 3:request completed and response is ready

this.status

These are the following status codes:
  • 200:"OK
  • 403:"Forbidden"
  • 404:"Page not found"
  • More can be found here.

Request types

These are the following states:
  • GET:to get data from the server
  • POST:to post data from the server
//here is an example of an ajax request:
let request = new XMLHttpRequest();       
request.onreadystatechange = function(){
  if(this.readyState == 4 && this.status ==200){
//means if responder is ready

//this.responseText is the response data in string form
console.log(this.responseText)

let url = "//this be a random url"
//request.open(request_type,url,is_asynchronous)
request.open("GET",url, true) //specify the type of request
request.send()
  }
}
This is what a json object would look like:
 let item = {key_1:value_1,
key_2:value_2}
These are the ways which we access JSON object properties:
item[key_1] // accesses value_1
item.key_1 //accesses value_1
JSON parse and Stringify This is how we parse and stringify json objects:
let a = {item:"a",no:"1",
  item:"b",no:"2",
  item:"c",no:"3"
}
//NOTE: both only works if the string/object are in JSON format
let stringed_JSON = JSON.stringify(a) //converts JSON to string
let parsed =JSON.parse(stringed_JSON) //converts string to JSON