javascript

javascript-logo


Features

  • ursprünglich für interaktive Websites entwickelt
  • Browser besitzen JS-Engine, welche Script ausführt
  • Node.js ⟹ JS ohne Browser ⟹ Server
  • React Native ⟹ JS mobile Apps
  • Electron ⟹ JS Desktopapps
  • JS vor 2015 << JS2015+

Engine

javascript-engine


node.js

node.js-engine


use strict

'use strict';
"use strict";
  • sollte die erste Zeile fast jeder .js-Datei sein
  • zwingt die Engine zu modernen Modus
  • hilft, blöde Fehler zu vermeiden
  • module- und class-Deklarationen implizieren 'use strict'

Variablen

let
Standardzuweisung, Variable veränderbar

        let x = 42;
        x = 'Code smell';
    
const
Variable unveränderbar, final

        const 
        let template = `${name} seit ${year} top!`;
    
var
👎 alt, nicht empfohlen 👎

Typen

number

        let year = 2015;
        let pi = 3.1415926;
    
string

        let name = 'JavaScript'; // "Javascript"
        let template = `${name} seit ${year} top!`;
    
boolean

        let important = true;
    
null

        let nothing = null;
    

undefined

        let unassigned;
        console.log(unassigned); // -> undefined
    
object

        let webDev = {
            content: 'html',
            style: 'css',
            action: 'js',
            since: 1995,
            oop: true
        };
    

Typumwandlung

Number(null)        -> 0
Number(undefined)   -> NaN
Number(true)        -> 1
Number(false)       -> 0
Number("")          -> 0
Number("text")      -> NaN
Number("3.1415")    -> 3.1415
"2" / "3"           -> 0.6666666666666666

Mathematische Operationen konvertieren implizit

Boolean(0, '', null, undefined, NaN) -> false
Boolean(others) -> true

Operationen

wie Java/C

2 ** 3  -> 8

let n = 5;
n %= 2  -> 1
n++     -> 2
0 == false // true
0 === false // false

=== checkt ohne Typumwandlung 👍


if/else/?

wie Java/C

if (truthy) {
    //
} else if (!something && other || thing){
    
} else {
    
}

let even = n % 2 == 0 ? true : false;

??

let result;
if (optional != null && optional != undefined)
    result = optional;
else
    result = defaultValue;
let result = optional ?? defaultValue;
let name = lastName ?? firstName ?? nickName ?? "Anonymous";

switch/case

wie oldschool Java/C

let result;
switch(grade) {
    case 5:
        result = 'Nicht genügend';
        break;
    case 4:
        result = 'Genügend';
        break;
    case 3:
        result = 'Befriedigend';
    // ...    
    default:
        throw new RangeError('Invalid grade: ' + grade);
}

⚠️ Fallthrough ⚠️


Schleifen

while (n) {
    console.log(n--);
}
for (let i = 0; i < n; i++) {
    console.log(i);
}

Funktionen

function lengthUntilFirstLineEnding(string, ending = '\n') {
    for(let i=0; i < string.length; i++)
        if (string.substring(i, i + ending.length) === ending)
            return i;
    return Infinity;
}

Callbacks

Parameter einer Funktion können Funktionen sein

function ifPresent(object, consumer) {
    if (object)
        consumer(object);
}
function log(object) {
    console.log(object);
}
ifPresent(42, log);
ifPresent({name: 'callback'},
        function (object) {
        console.log(object);
    });
ifPresent({name: 'callback'},
        object => console.log('Present: ', object));

OOP

Initialisierung wie dictionary in Python

let person = {   
    name: 'Bob', 
    age: 42       
};
person.profession = 'Developer';
person.profession -> 'Developer'
person['age'] -> 42
delete person.name
person.name -> undefined

Konstruktoren/Factory-Methoden

function createUser(name, email) {
    return {
        name,   // name: name
        email,  // email: email
        role: 'user'
    };
}
function User(name, email, role='user') {
    this.name = name;
    this.email = email;
    this.role = role;
}

new User("Jeff", "jeff@htlstp.at");
new User("Cäsar", "cesar@htlstp.at", 'admin');

Methoden

Werden wie Felder definiert

let calculator = {
    left: 5,
    right: 3,
    add() {
        return this.left + this.right;
    },
    divide() {
        if (this.right === 0)
            throw new RangeError('Invalid divisor: ' + right);
        return this.left / this.right;
    }
};

for in

iteriert über member eines objects

let webDev = {
    content: 'html',
    style: 'css',
    action: 'js',
    since: 1995,
    oop: true,
    log() {
        console.log(this);
    }
};
for (let property in webDev)
    console.log(`${property}\t${webDev[property]}`)
content html
style   css
action  js
...

Arrays

Sammlung beliebiger Daten

array = [42, obj => console.log(obj), 3.14, 'HTL'];

array[1](array);   -> [ 42, [Function (anonymous)], 3.14, 'HTL' ]
console.log(array.pop());   -> HTL
console.log(array.length);  -> 3
array.push('new');
console.log(array); -> [ 42, [Function (anonymous)], 3.14, 'new' ]