JavaScript

basics

Created by Adam Nagy / blog

You can find this presentation here:

https://github.com/nagyadam2092/AngularJS-presentation-Frankfurt

or here:

http://nagyadam2092.github.io/work/angularjs_presentation/js_basics/#/

History

  • Brendan Eich (1995) --> NetScape 2 in 1996
  • originally "LiveScript" --> JAVA is popular --> JavaScript..
  • Several months later Netscape submitted JavaScript to Ecma International
  • EcmaScript standard that year (EcmaScript3 in 1999)
  • EcmaScript 5 in 2009 (!)
  • 6th edition (or EcmaScript2015) in June of 2015

JavaScript

  • "JavaScript is a high-level, dynamic, untyped interpreted programming language"
  • - not compiled
  • mostly interpreted by the browser, but also
    • Adobe Acrobat, Photoshop
    • SVG images
    • server-side (Node.js)
    • NoSQL databases (CouchDB)
    • etc..

Overview

  • JavaScript is
    • an object-oriented
    • dynamic language
    • with types and operators
    • standard built-in objects, and methods
  • syntax is based on C/C++/JAVA - differences
    • no classes (ehm.. ES6)
    • object prototype
    • functions are objects

Very important note

JavaScript:

  • functional
  • prototypical

Types

Comparison

== VS ===

  • ==
    not aware of type
  • ===
    aware of types

in general: == is bad

Numbers

There's no such thing as Integer in JS. --> Be careful!

0.1 + 0.2 == 0.30000000000000004

String to Integer with parseInt

parseInt("010", 10); // 10

parseInt("11", 2); // 3

+"010" // 10

1/0 //Infinity

isFinite(1/0) //false

Strings

sequences of Unicode characters

Single characters by strings as well ("a")

"hello".length; // 5

Strings have methods as well

"hello".charAt(0); // "h"

"hello".toUpperCase(); // "HELLO"

Other types

difference between null and undefined

null indicates a deliberate non-value

undefined indicates an uninitialized value

Booleans

true and false

but... any value can be converted to boolean

  • falsy values
    • false
    • 0
    • ""
    • NaN
    • null
    • undefined
  • truthy values
    • all other values

Variables

new variables with the var keyword

var a;
                var name = "adam";
            

if you declare a variable without assigning any value to it, its type is undefined

no block scopes (..ES6?)

Hoisting

in JS a variable can be declared after it's been used

x = 5; // Assign 5 to x
                elem = document.getElementById("demo"); // Find an element
                elem.innerHTML = x;                     // Display x in the element, which is 5
                var x; // Declare x
            

moving all declarations to the top of the current scope

(to the top of the current script or the current function)

Objects

like HashMaps in Java

key-value pairs

var obj = new Object();
                var obj = {}; //preferred
                var obj = {
                name: "Carrot",
                "for": "Adam",
                details: {
                color: "orange",
                size: 12
                }
                };
                obj.details.color; // orange
                obj["details"]["size"]; // 12

Arrays

special type of object

like regular objects, with a magic property

length

var a = ["dog", "cat", "hen"];
                a.length; // 3
                ["dog", "cat", "mouse"].forEach(function(currentValue, index, array) {
                // Do something with currentValue or array[index]
                });

Functions

function add(x, y) {
                var total = x + y;
                return total;
                }
                add.variable = 'a variable'; //valid

function add() {
            var sum = 0;
            for (var i = 0, j = arguments.length; i < j; i++) {
            sum += arguments[i];
            }
            return sum;
            }

            add(2, 3, 4, 5); // 14

var avg = function() {
            var sum = 0;
            for (var i = 0, j = arguments.length; i < j; i++) {
            sum += arguments[i];
            }
            return sum / arguments.length;
            };

Scopes in JS

  • global scope - ew
  • local (function) scopes - yay

Global scope

pollution is bad

use it as less as possible!

it's variables are reachable inside functions

Function scope

a function has it's own variables

these are local variables

- not reachable from the outside

var myFunction = function() {
            var myVariable = 'just a var';
            };
            //myVariable is undefined here

IIFE and scopes

Immediately Invoked Function Expression

var a = 1;
                var b = 2;

                //IIFE
                (function() {
                var b = 3;
                a += b;
                })();

                a; // 4
                b; // 2

Module pattern

"private" and "public" variables

var module = (function module() {
                var privateVar = 1;
                var publicVar = 10;

                function privateFunc() {
                console.log('privateFunc');
                privateVar++;
                publicVar++;
                return privateVar * 2;
                }

                function publicFunc() {
                console.log('publicFunc');
                privateFunc();
                }

                return {
                publicVar: publicVar,
                publicFunc: publicFunc
                };
                })();

this in JS

  • by default it's referencing to it's scope
    var obj = {
                        x: 81,
                        getX: function() {
                        console.log(this.x);
                        return this.x;
                        }
                        };
                        obj.getX(); //81
                    

bind, call, apply

But we can change the reference of this!

var otherObj = {
                x: 99
                };
                obj.getX.call(otherObj); //99
                obj.getX.apply(otherObj); //99
                var myGetXFunction = obj.getX.bind(otherObj); //returns a function
                myGetXFunction(); //99

more on this topic on my blog here: http://nagyadam2092.blogspot.hu/2015/02/javascript-difference-between-bind-vs.html

OO JavaScript

as we've seen before - no classes ehm.. ES6

instead we have functions, which are holding the functionalities like classes

Functional inheritance

//class Animal
                var Animal = function(_feet) {
                this.feet = _feet;
                };
                Animal.prototype.eat = function() {
                console.log("I am eating, omnomnom..");
                };
                Animal.prototype.info = function() {
                console.log("I have this amount of feet: " + this.feet);
                };

                //class Cat extends Animal
                var Cat = function(_feet, _miceHaveEaten) {
                Animal.call(this, _feet);
                this.miceHaveEaten = _miceHaveEaten;
                var privateVariable = "This is not available outside the class!";
                };
                Cat.prototype = new Animal();
                Cat.prototype.purr = function() {
                console.log("Purrrrrr.........");
                };
                //polymorphism
                Cat.prototype.info = function() {
                console.log("I have eaten this amount of mice so far: " + this.miceHaveEaten + ", also I have " + this.feet + " feet.");
                };

                var unicellular = new Animal(0);
                unicellular.eat();
                unicellular.info();

                var garfield = new Cat(4, 9001);
                garfield.eat();
                garfield.purr();
                garfield.info();

more here

Let's override String!

var s = "Adam";
                s.reversed(); // TypeError on line 1: s.reversed is not a function

                String.prototype.reversed = function reversed() {
                var r = "";
                for (var i = this.length - 1; i >= 0; i--) {
                r += this[i];
                }
                return r;
                };

                s.reversed(); // madA

                "This can now be reversed".reversed(); // desrever eb won nac sihT

Closures

function makeAdder(a) {
                return function(b) {
                return a + b;
                };
                }
                var fiveAdder = makeAdder(5);
                var twentyAdder = makeAdder(20);
                fiveAdder(6); // ?
                twentyAdder(7); // ?

Problems

  1. Create a function (add) which adds two numbers
  2. Create a function (caller), which will call it's first argument (function) on the 2nd and 3rd argument: caller(add, 2, 3);
  3. Create a function: add(2)(3); //5
  4. Create a function (mul) which multiplies two numbers
  5. same, but mul(2)(3); //6
  6. Create a function which works like the following: applyf(add)(2)(3); //5
    applyf(mul)(2)(3); //6