Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Aphorismen
Applications
Business Economics & Admin.
My Computers
Cooking
Devices
Folders
Food
Hardware
Infos
Software Development
Sports
Operation Instructions
Todos
Test
Help
Glossary
Community portal
adaptions
Sidebar anpassen
Wiki RB4
Search
Search
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
JavaScript/JScript
(section)
Page
Discussion
English
Read
Edit
View history
Toolbox
Tools
move to sidebar
hide
Actions
Read
Edit
View history
General
What links here
Related changes
Special pages
Page information
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Language== JS is case-sensitive language. ===HTML embedding=== <script type="text/javascript"> <javascript code> </script> ===Comments=== // einzeilig /* mehrzeilig */ ===Variables=== Although not required, it is considered good practice to declare variables before using them. You do this using the '''var''' statement. The only time you must use the '''var''' statement is if you want to declare variables that are local to a function. Local variables are those that are only within the function. Re-declaring a variable will not change the value the variable already had. You can declare a variable implicitly (without using '''var''') by assigning a value to it. The first character must be a letter or an underscore (_), or a dollar sign ($). Variable names are case sensitive. In instances in which you want to declare a variable and initialize it, but without giving it any particular value, you may assign it a special value, null. If you declare a variable without assigning any value to it, it exists but is undefined. The types are: *String (can be treated as object) *Number (can be treated as object) *Boolean (can be treated as object) *Array (internally object) *Object *Null *Undefined. The type of a variable can be checked by: typeof(<var>); JS supports both integer and floating-point numbers. Integers can be positive, 0, or negative; a floating-point number can contain either a decimal point, an "e" (uppercase or lowercase), which is used to represent "ten to the power of" in scientific notation, or both. These numbers follow the IEEE 754 standard for numerical representation. Last, there are certain number values that are special: *NaN *positiv infinity *negativ infinity *positiv 0 *negativ 0 ====Declaration==== var x; var y = 10; // function scope, redeclaration allowed let a; let b = 10; // block scope, redeclaration not allowed As JS is a loosely-typed language, variables in JS technically have no fixed type. Instead, they have a type equivalent to the type of the value they contain. It is possible, under some circumstances, to force the automatic conversion (or coercion) of a variable or a piece of data into a different type. Numbers can easily be included in strings, but strings cannot be included directly in numbers, so explicit conversion functions, parseInt() and parseFloat(), are provided. var theFrom = 1; var theTo = 10; var doWhat = "Count from "; doWhat += theFrom + " to " + theTo + "."; After this code is executed, the ''doWhat'' variable contains "Count from 1 to 10." The number data have been coerced into string form. var nowWhat = 0; nowWhat += 1 + "10"; // In this case, because "10" is a string, // the "+=" operator concatenates. After this code is executed, the ''nowWhat'' variable contains "0110". The following steps are followed to arrive at this result: *Look at the types of 1 and "10". The "10" is a string, the 1 is a number, so the number is coerced into a string. *As the values on either side of the '''+''' operator are both strings, do a string concatenation. This results in "110" *Look at the types of the values on either side of the +=. ''nowWhat'' contains a number, and "110" is a string, so convert the number to a string. *As there are now strings on either side of the += operator, do a string concatentation. This results in "0110". *Store this result in ''nowWhat''. var nowThen = 0; nowThen += 1 + parseInt("10"); // In this case, "+=" performs addition. After this code is executed, the ''nowThen'' variable contains the integer 11. Um zu testen ob eine Variable x den Wert ‘undefined’ besitzt sind mir z.Z. zwei Verfahren bekannt. if (String(x) == "undefined") ... if (typeof(x) == "undefined") ... ===Datatypes=== ====Conversion==== * + unary operator converts to number ===Operatoren=== {| border=1 cellpadding=2 cellspacing=0 |- |== |Value Comparison |- |=== |Value and Type Comparison |- |&& |logical AND |- ||| |logical OR |} ===Conditional Statements=== if (<Expression) { <statements> } [else { <statements> }] ===Arrays=== Arrays sind Objekte which can contain different objects. Arrays werden durch var arr = '''['''[( <Number> | <Element> {,<Element>})]'''];''' var arr = '''new Array('''[( <Number> | <Element> {,<Element>})]''');''' var arr = '''new Array<'''<TYPE>'''>(....)''' deklariert. In JavaScript, arrays always use numbered indexes. Die Indizierung ist 0-based. Arrays haben eine member variable '''length'''. JavaScript does not support associative arrays. If you use a named index, JavaScript will redefine the array to a standard object. After that, all array methods and properties will produce incorrect results. To empty an array you can: x.length = 0; // empties an existing array x = []; // creates a new array To delete an array element without leaving holes use: x.splice(<index>, <length of array section to delete>); ====Methoden der Array-Klasse==== =====push()===== adds an element at the end =====pop()===== removes the last element =====splice()===== splice(i,n) removes n elements starting at i =====shift()===== removes the first element =====unshift()===== The unshift() method adds new items to the beginning of an array, and returns the new length. var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.unshift("Lemon","Pineapple"); ===Function Definition=== Internally functions are objects ([http://www.permadi.com/tutorial/jsFunc/index.html good explanation]). There are multiple ways of defining a function. Die Definition von Funktionen kann überall im Quellcode erfolgen und muss nicht vor der Verwendung erfolgen. function <FunctionName>(<ParameterList>) // only declaration, no execution { <StatementList>; return <Value|Parameter>; } <FunctionName>(); // execution or var foo = function() // only declaration, assigning variable to unnamed function object { <StatementList>; return <Value|Parameter>; } foo(); // execution or var add=new Function("a", "b", "return a+b;"); // very special, not recommended Functions can be properties of an object. ====ASEF/IIFE==== Another way is to create and execute a function created with function expression at once ('''anonymous self-execting function ASEF''') ([http://markdalgleish.com/2011/03/self-executing-anonymous-functions/ good explanation]), also better named IIFE ('''Immediately Invoked Function Expression, IIFE''')) by adding the parantheses following the function declaration: (function() { ... })'''()'''; // function() { ... })() missing brackets give a syntax error because it is a // function declaration instead of a function expresssion, only the latter can be executed (function(aParameter) { alert(aParameter); })'''("an argument")'''; // ASEF with parameter, will alert "an argument" (function($){ alert($(window).jquery); })'''(jQuery)'''; // avoids conflict with another library defining the '''$''' global variable All variables and functions defined within the anonymous function aren’t available to the code outside of it, so there is no naming conflict. The parameters are somehow passed by value and are available even if functions within are called later: // will alert two times with value 2 var f = (function (p) { alert(p); var x = function () { alert(p); }; return { y: x }; })(2); f.y(); ====Arrow Function==== Arrow Functions can remove the need of function, return and {} when defining functions. They are one-liners, similar to Lambda Expressions in Java or Python. ====Async Funtion==== An async function is a function declared with the async keyword, and the '''await''' keyword is permitted within it. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style. Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected. E.g.: function resolveAfter2Seconds() { return new Promise(resolve => { setTimeout(() => { resolve('resolved'); }, 2000); }); } '''async''' function asyncCall() { console.log('calling'); const result = '''await''' resolveAfter2Seconds(); console.log(result); } asyncCall(); console.log("asyncCall() called"); prints > "calling" > "asyncCall() called" > "resolved" ===Namespacing=== A good explanations of the patterns can be found [http://www.codethinked.com/preparing-yourself-for-modern-javascript-development here]. The standard is to define a new namespace or use the existing one (and not overwrite it) and ASEF style by: var my_namespace = my_namespace || { }; my_namespace.sub_namespace = (function () { var func1 = function () { ... }; var public = { func1 : func1, ... }; return public; } (); ===Classes=== Classes are just special functions added to ES6 that are meant to mimic the class keyword from these other languages. We can have class declarations and class expressions. Classes are just normal JavaScript functions and could be completely replicated without using the class syntax. It is special syntactic sugar added in ES6 to make it easier to declare and inherit complex objects. Each class can only have one constructor method in it. class Person { // class declaration constructor(firstName, lastName) { this.firstName= firstName; this.lastName = lastName; } } let Person = class [<Classname>] { // class expression constructor(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } } * Getter, Setter and Static Methods * inheritance and super() ====Class Object Creation==== var x = new <ClassName>(<Ctor Parameter>); ===Object Declaration=== In JavaScript nearly everything is an object. Objects are complex variables with properties and methods. Each property has a name and a value. In JavaScript, all values except primitive values are objects. Primitive values are: * strings ("John Doe"), * numbers (3.14), * true, * false, * null, and * undefined. There multiple ways to declare and to instantiate objects // by ctor function, which is a normal function but used with the new operator '''function''' <ClassName>'''('''<ParameterList>''')''' '''{''' // declaration of a member/property '''this.'''<MemberName> '''=''' <ParameterListElement>; // declaration of a method '''this.'''<MethodName> '''= function() { ...}'''; ... '''}''' // object instantiation '''var''' <NewVar> '''= new''' <ClassName>'''('''<ActualParamterList>''');''' or var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; // creates an object with 4 properties or var person = new Object(); person.firstName = "John"; person.lastName = "Doe"; Existing objects can be extended by using the predefined prototype property: person.prototype.doSomething = function() { ... }; ===Object Usage=== name = person.lastName; name = person["lastName"]; ===this=== * In JavaScript, the thing called '''this''', is the object that "owns" the JavaScript code. * The value of this, when used in a function, is the object that "owns" the function. * The value of this, when used in an object, is the object itself. * The this keyword in an object constructor does not have a value. It is only a substitute for the new object. * The value of this will become the new object when the constructor is used to create an object. ===Promises=== The Promise object represents the eventual (irgendwann) completion (or failure) of an asynchronous operation and its resulting value. At their most basic, [https://web.dev/promises/ promises] are a bit like event listeners except: * A promise can only succeed or fail once. It cannot succeed or fail twice, neither can it switch from success to failure or vice versa. * If a promise has succeeded or failed and you later add a success/failure callback, the correct callback will be called, even though the event took place earlier. A promise can be: * '''fulfilled''' - The action relating to the promise succeeded * '''rejected''' - The action relating to the promise failed * '''pending''' - Hasn't fulfilled or rejected yet A promise is said to be '''settled''' if it is either fulfilled or rejected, but not pending. The eventual state of a pending promise can either be fulfilled with a value or rejected with a reason (error). When either of these options occur, the associated handlers queued up by a promise's then method are called: * The '''.then()''' method takes up to two arguments; the first argument is a callback function for the fulfilled case of the promise, and the second argument is a callback function for the rejected case. Each .then() returns a newly generated promise object The '''Promise.resolve()''' method "resolves" a given value to a Promise. ===Modules=== * some recommend to use *.mjs for modules * export items by export ...; * import items by import {<ItemList> } from './modules/square.js'; <script type="module" src="main.js"></script> * can define multiple classes
Summary:
Please note that all contributions to Wiki RB4 may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
Uwe Heuer Wiki New:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Toggle limited content width