JavaScript 101

  1. What is javascript

  2. JavaScript is a programming language. It is currently the only programming language that your browser can execute natively. (There are efforts to change that.) Therefore if you want to make web sites interactive, you must use JavaScript: There are no other options. Created in 1995 by Brendan Eich JavaScript has nothing to do with Java
    • Literally named that way for marketing reasons
    • The first version was written in 10 days
  3. Javascript in browser

  4. HTML can embed JavaScript files into the web page via the <script> tag. You can print log messages in JavaScript by calling console.log(). This JavaScript's equivalent of Java's System.out.println, print, printf, etc. First javascript to print Hello, world on console
    Create html file called helloWorld.html
                  
    <!DOCTYPE html>
    <html>
    <head>
    <title>First JS Example</title>
    <script src="script.js"></script>
    </head>
    <body>
    </body>
    </html>
                  
                
    Create a javascript file called script.js with the single line
                  
    console.log("Hello, world!");
                  
                
  5. JavaScript execution

  6. There is no "main method" The script file is executed from top to bottom. There's no compilation by the developer, JavaScript is compiled and executed on the fly by the browser.
  7. JavaScript language features

  8. Same as Java/C++/C-style langs
    for-loops:
                  
    for (let i = 0; i < 5; i++) { ... }
                  
                
    while-loops:
                  
    for (let i = 0; i < 5; i++) { ... }
                  
                
    while-loops:
                  
    while (notFinished) { ... }
                  
                
    comments:
    
    // comment or /* comment */
                
    conditionals (if statements):
                  
    if (...) {
    ...
    } else {
    ...
    }
                  
                
  9. Functions

  10. Functions
    One way of defining a JavaScript function is with the following syntax:
                  
    function foo() {
    statement;
    statement;
    ...
    }
                  
                
    Create a file called script.js. Write the following code in it:
                  
    function hello() {
      console.log('Hello!');
      console.log('Welcome to JavaScript');
    }
    hello();//call the function
    hello();
        
    function printMessage(message, times) {
      for (var i = 0; i < times; i++) {
        console.log(message);
      }
    }
                  
                
    Function parameters are not declared with var, let, or const
  11. Variables: var, let, const

  12. Declare a variable in JS with one of three keywords:
                  
    // Function scope variable
    var x = 15;
    // Block scope variable
    let fruit = 'banana';
    // Block scope constant; cannot be reassigned
    const isHungry = true;
                  
                
    You do not declare the datatype of the variable before using it ("dynamically typed")
  13. Understanding var

  14.             
    function printMessage(message, count) {
        for (var i = 0; i < count; i++) {
    console.log(message);
        }
        console.log('Value of i is ' + i);
      }
    printMessage('hello', 3);
                
                
    What happens? The value of "i" is readable outside the for-loop because variables declared with var have function scope.
                  
    function foo (){
      var x=0;
      if (x>0){
        var y =10;
      }
      console.log('y is ' + y);//prints as expected
    }
    foo();
    console.log('y is ' + y); // error
                  
                
  15. Understanding let

  16.             
    function printMessage(message, count) {
      for (let i = 0; i < count; i++) {
        console.log(message);
      }
      console.log('Value of i is ' + i);
    }
    printMessage('hello', 3);
              
            
    What happens? let has block-scope so this results in an error
  17. Understanding const

  18. Understanding const
                  
    let x = 10;
    if (x > 0) {
      const y = 10;
    }
    console.log(y);
    // error!
                  
                
    Like let, const also has block-scope, so accessing the variable outside the block results in an error
                
    const y = 10;
    y = 0; // error!
    y++; // error!
    const list = [1, 2, 3];
    list.push(4); // OK
                
              
    const declared variables cannot be reassigned. let can be reassigned, which is the difference between const and let.
  19. Variables best practices

  20. Use const whenever possible. If you need a variable to be reassignable, use let, not var. There is a lot of code on Internet using var, but you must avoid it

    Types

    JS variables do not have types, but the values do. There are six primitive types (mdn):
    Boolean : true and false
    Number : everything is a double (no integers)
    String: in 'single' or "double-quotes"
    Null: null: a value meaning "this has no value"
    Undefined: the value of a variable with no value assigned
    There are also Object types, including Array, Date, String (the object wrapper for the primitive type), etc.

    Numbers

    All numbers are floating point real numbers. No integer type.
    Operators are like Java or C++.
    Precedence like Java or C++.
    A few special values: NaN (not-a-number), +Infinity, -Infinity
    There's a Math class: Math.floor, Math.ceil, etc.

    Strings

    Can be defined with single or double quotes Many style guides prefer single-quote, but there is no functionality difference Immutable No char type: letters are strings of length one Can use plus for concatenation Can check size via length property (not function)

    Boolean

    There are two literal values for boolean: true and false that behave as you would expect
    Can use the boolean operators: && || ! Non-boolean values can be used in control statements, which get converted to true or false
    • null, undefined, 0, NaN, '', "" evaluate to false
    • Everything else evaluates to true

    Equality

    JavaScript's == and != show strange behaviour
                      
    '' == '0' // false
    '' == 0 // true
    0 == '0' // true
    NaN == NaN // false
    [''] == '' // true
    false == undefined // false
    false == null // false
    null == undefined // true
                      
                    
    ECMAScript standard kept the existing behavior but added === and !==
                      
    '' === '0' // false
    '' === 0 // false
    0 === '0' // false
    [''] === '' // false
    false === undefined // false
    false === null // false
    null === undefined // false
                      
                    
    Always use === and !== and don't use == or !=

    Null and Undefined

    null is a value representing the absence of a value, similar to null in Java and nullptr in C++.
    undefined is the value given to a variable that has not been assigned a value.
                    
    let x = null;
    let y;
    console.log (x)// prints null
    console.log (y)// prints undefined
                    
                  

    Arrays

    Arrays are Object types used to create lists of data.
                      
    // Creates an empty list
    let list = [];
    let snacks = ['chips', 'alu bonda'];
    snacks[1] = 'masala dosa';
                      
                    
    0-based indexing Mutable Can check size via length property (not function)

    Events

    Event-driven programming Most JavaScript written in the browser is event-driven The code doesn't run right away, but it executes after some event fires.
                    
    function onClick() {
    ...
    }
                    
                  
    Any function listening to that event now executes. This function is called an "event handler."

    Using event listeners

    Suppose we want to print "Clicked" to the browser Console when the user clicks a particular button: We need to add an event listener to the button... How do we talk to an element in HTML from JavaScript?

    The DOM

    Insert image Every element on a page is accessible in JavaScript through the DOM: Document Object Model.The DOM is the tree of nodes corresponding to HTML elements on a page.Can modify, add and remove nodes on the DOM, which will modify, add, or remove the corresponding element on the page

    Getting DOM objects

    We can access an HTML element's corresponding DOM object in JavaScript via the querySelector function:
                    
    let element = document.querySelector('#button');
    // Returns the element with id="button"
                    
                  

    Adding event listeners

    Each DOM object has the following function:addEventListener(event name, function name); event name is the string name of the JavaScript event you want to listen to Common ones: click, focus, blur, etc function name is the name of the JavaScript function you want to execute when the event fires.
    Write html code as follows
                    
    <!DOCTYPE html>
    <html>
    <head>
    <script>
      function onClick() {
        console.log("You clicked")
      }
      const but = document.querySelector('button');
      button.addEventListener('click', onClick);
    </script>
    </head>
    <body>
    <button>Click me</button>
    </body>
    </html>