JavaScript Basics

January 28th, 2019 / Faktor E Multimedia GmbH


copy and paste from StackOverflow

No
copy and paste from StackOverflow

Understanding the fundamental principles of JavaScript

About what we are NOT talking today...

  • Frameworks

  • Libraries (almost)

  • Syntax basics (almost)

What we'll talk about...

How to
structure simple JavaScript code

Disclaimer:

ECMAScript 5

What are Classes?

A construction plan

How would it look like in PHP?

<?php

class MyClass {
  /* Nothing else
     here... */
}

What are Objects?

An instance of a class

A concrete object

How would it look like in PHP?

<?php

$myObject =
  new MyClass();

Classes in JavaScript?

Classes in JavaScript?

Don't get me wrong!

There're classes in JavaScript.

E.g. React.js makes usage of classes in its concepts.

But classes are not in the scope of today's workshop.

Always concrete objects

How to declare an object in JavaScript?

How to instantiate an object in JavaScript?

How to define an object literal in JavaScript?!

var myObject = {};

Make let not var

let myObject = {};

let myObject = {
    name: "Larissa Küpper",
    gender: "f"
    position: "JavaScript developer"
};

  • Always concrete objects

  • Data structures (mostly)

  • Dynamic (still on runtime)

  • Modifiable at any time

  • Key-Value-Pairs

  • Values can be any data type known by the JavaScript engine

Which kinda data types could this be?

Methods

How would it look like in PHP?

<?php

class MyClass
{
  public function myMethod(
    int $a, int $b
  ):int
  {
    return $a + $b;
  }
}

What's the difference between attributes and methods?

NONE

let myObject = {
  name: "Garvin Hicking",
  children: 0,
  increaseChildren: function(amount) {
    if(typeof amount === "undefined") {
      amount = 1;
    }
    this.children += amount;
  }
};

Object hierarchies

var application = {
  name: "Christoph's Application",
};

application.moduleOne = {
  name: "Tom's Module",
  provideAppInfo: function () {
    return
        this.name + " is part of "
        + application.name + "!";
  }
};

application.moduleOne.provideAppInfo();
// Tom's Module is part of Christoph's Application!

Scopes

  • Function block scopes

  • Enclosing block scopes

  • Scope chain

  • Local scopes

  • Scope overloading

Function block scopes
vs.
enclosing block scopes

Make let not var

function functionBlockScope() {

  let foo = 'bar';
  // function block scoped

  var bar = 'foo';
  // function block scoped

}

function functionBlockScope() {

  for (var i = 0; i < 5; i++) {

    // i is visible to
    // the whole function

  }

  //i *is* visible out here

}

function enclosingBlockScope() {

  for (let i = 0; i < 5; i++) {

    //i is only visible in here
    //(and in the for() parentheses)
    //and there is a separate
    //i variable for each
    //iteration of the loop!

  }

  //i *is not* visible out here

}

let and var

Redeclaration of variables

'use strict';

var me = 'foo';
var me = 'bar';

// No problem, 'me' is replaced.

'use strict';

let me = 'foo';
let me = 'bar';

// SyntaxError:
// Identifier 'me' has
// already been declared

var foo = 'bar';
// globally scoped

let bar = 'foo';
// globally scoped

console.log(window.foo);
// 'bar'

console.log(window.bar);
// undefined

Scope chain

Access to all variables within the function
and to all of its parents!

let globalVar = 1;
let outer = function () {
  let outerVar = 2
  let inner = function () {
    let innerVar = 3;
    let core = function () {
      let coreVar = 4;
      return coreVar + innerVar + outerVar + globalVar;
    };
    return core();
  };
  return inner();
};
outer(); // Result: 10

Local scope

The local scope always wins

Scope overloading

Scope overloading

Closures

Closures

  • A function embraced by another function
  • Used for data encapsulation
  • Access by reference


Don't forget:

  • A function can be the return value of another function

var application = function () {
  var name = "Jörg's Application";
  var version = "v0.0.1";

  var init = function () {
    var msg = "Successfully launched: ";
    return msg + name + ", " + version;
  };

  return init;
};

var initApp = application();

initApp();
// Successfully launched: Jörg's Application, v0.0.1

Immediate Functions

Immediate
Functions

  • Will be executed on definition

Why?

  • Initiate processes
    before anything else
  • Defining namespaces

(function (name) {

  return 'Hello ' + name;

})('Lars Goossens');


// 'Hello Lars Goossens'

Module Pattern

Global
Import

var application = (function (global) {

  var name = "Werner's Application";
  var version = "v0.2.0";

  return {
    getVersion: function () {
      global.alert(
        "Version " + version
      );
    }
  };

}(window));

var application = (function (window, $) {
  var name = "Lisa's Application";

  return {
    changeContent: function () {
      $(".my-container").html(
        "New content"
      );
      window.alert(
        "The content has changed!"
      );
    }
  };

}(window, jQuery));

Module
export

// Expose module as global variable
var Module = function(){
  // Inner logic
  function sayHello(){
    console.log('Hello');
  }
  // Expose API
  return {
    sayHello: sayHello
  }
}
var module = new Module();
module.sayHello(); // Hello