Skip to content

Instantly share code, notes, and snippets.

@mayfer
Last active August 29, 2015 14:10
Show Gist options
  • Save mayfer/20a1ed624eba0f5b672f to your computer and use it in GitHub Desktop.
Save mayfer/20a1ed624eba0f5b672f to your computer and use it in GitHub Desktop.
Introduction to JS

Global vs. local variables

  • Local variables are defined with the var keyword.
  • Variables defined without var are automatically global.

Function declaration and calling

  • Two ways to define functions:
    • function someFunc(arg1, arg2) {}
    • var someFunc = function(arg1, arg2) {}
  • All arguments are inherently optional. Calling someFunc() without arguments will NOT error out. The arguments will have undefined values.
  • Functions must return explicitly. There is no implicit return.
  • Default return value is undefined.
  • Functions can be referred to without calling them. Brackets are used for calling the functions.

Loops

  • There is no .each
  • You will find yourself using for(var i=0; i<arr.length; i++) a lot when looping through arrays.

Anonymous functions

  • Functions can be declared without names. This is useful when a function needs to be passed in as an argument to another function, but doesn't need to be used anywhere else.
    • example 1:

        setTimeout(function(){  
            console.log("three seconds later")  
        }, 3000);
      
    • example 2:

        function map(array, operation) {
            var new_arr = [];
            for(var i=0; i<arr.length; i++) {
                new_arr[i] = operation(arr(i));
            }
            return new_arr
        }
        
        var results = map([1, 4, 7] function(elem) {  
            return elem * 2;
        });
      

Javascript in the browser

  • Script gets executed when browser parses it from top to bottom of the HTML source.

  • Three important built-in global variables:

    • document, the parsed, in-memory HTML document
    • window, the "tab"
    • navigator, the whole browser
  • Javascript runs a continuous event loop. Constantly checks for new events. Events can be "listened" on, and tied to functions they can call.

      document.addEventListener("click", function(){
          console.log("YOU CLICKED OMGXOR");
      })
    
  • Javascript is embedded into the browser with the script tag.

      <script type="text/javascript">
          console.log("Hello World");
      <script>
    
  • or linked to from a file

      <script type="text/javascrscript" src="path/script.js"></script>
    

Order of operations

  • Any elements that javascript accesses must be loaded on the page. So if javascript is executed Before an HTML element is loaded, it won't be able to access the element.
  • Events can be used to time actions appropriately. Hint: document.onload
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment