ECMAScript/Beispiele
aus GlossarWiki, der Glossar-Datenbank der Fachhochschule Augsburg
Kommentare
// Einzeiliger Kommentar
/* Das ist ein langer,
* mehrzeiliger Kommentar
*/
/* Man kann keine Kommentare, /* Verschachteln */ SyntaxError */
Werte
// Zahlen
5; -3.21; 0.255e+3; NaN; +Infinity; -Infinity; 0xff /* Hex */
// BigInt
BigInt(9007199254740991); BigInt("9007199254740991")
typeof 1n === 'bigint' // true
typeof BigInt('1') === 'bigint' // true
// NULL
null; undefined; NaN; null !== undefined; null == undefined
// Boolean
true; false
(5 < 2) == null
(5 < 2) == undefined
(5 < 2) == NaN
(5 < 2) == 0
(5 < 2) == -0
(5 < 2) == 0n
(5 < 2) == -0n
// String
''; 'a'; 'abc'; "abc"; `abc`
// Array
[1]; [1,2]; []; ['a', 2, true, []]
// Object
{a: 1}; {a: 1, b: 7}; {}; {"name": "Wolfgang", "geb": 1961, "HSA-Dozent": true, urenkel: []}
Quotes
let a = 5;
console.log(`aabc`) => aabc
console.log(`a${a}bc`) => a5bc
console.log(`a${a+2}bc`) => a7bc
console.log(`a${a}+2bc`) => a5+2bc
`{x: ${this.x}, y: ${this.y}, vx: ${this.vx}, vy: ${this.vy}}`
=>
{x: 258, y: 400, vx: 80, vy: -200}
'{x: ' + this.x + ', y: ' + this.y + ', vx: ' + this.vx + ', vy: ' + this.vy + '}'
=>
{x: 258, y: 400, vx: 80, vy: -200
var select =
`SELECT *
FROM haendler
`;
Deklarationen
let a // a === undefined
let a: number // TypeScript
a = 5; // a === 5
a = 'abc'; // a === 'abc', TypeScript: Error
let b = 7 // b === 7, TypeScript: b ist vom Typ number
b = 13.33; // b === 13.333
const c // Error
const c = 'abc' // c === 'abc'
c = 'def'; // Error
Scope
if (true) { var x = 5 }
console.log(x); // 5
if (true) { let y = 5 }
console.log(y); // ReferenceError: y is not defined
if (true) { const z = 5 }
console.log(z); // ReferenceError: z is not defined
Objekte
let o
o = {}; // leeres Objekt
o = { a: 1, b: 2, "Attributname mit Leerzeichen": 3};
o = { x: 100,
y: 200,
moveTo(p_x, p_y) { this.x = p_x; this.y = p_y; },
moveBy(p_x, p_y) { this.x += p_x; this.y += p_y; },
};
o = { a: 5 };
console.log(o.a);
o.a = 6;
console.log(o.a);
o = { _a: 0,
get a() { return this._a },
set a(p_a) { this._a = p_a },
};
o.a = 6;
console.log(o.a);
Kurzschreibweise
let
a = 5, b = 'abc',
o = { a, b } // = { a: a, b: b } // = { a: 5, b: 'abc' }
// a und b dürfen Variablen, Konstanten und Parameter sein;
// sie dürfen beliebige Werte, Objekte und auch Funktionen enthalten
Spread-Operator
let
o1 = { a: 1, b: 2 },
o2a = { a: 3, c: 4, b: o1 }, // { a: 3: b: { a: 1, b: 2 }, c: 4}
o2b = { ...o1, a: 3, c: 4 }, // { a: 3, b: 2, c: 4}
o2c = { a: 3, c: 4, ...o1 }, // { a: 1, b: 2, c: 4}
o3 = { a: 3, b: 2, a: 1 } // { a: 1, b: 2 }