Javascript
Comments
// single line comment
/*
* multi line comment block
*/
Printing to Console
console.log("some string")
console.log(123)
Datatypes
- Total 7 Datatypes in Javascript
- Primitive Datatypes (6)
undefined:- variables are
undefinedafter initialization - numerical operations on
undefinedcauseNaN - stringoperations on
undefinedcause"undefined"-String as result
- variables are
nullbooleanstringsymbolnumber
- Complex Datatypes (1)
object: complex datatype!
- Get Datatype (Code Example):
typeof("hello"); // returns datatype as string
Checking Datatypes
Number.isInteger("2017"); // false
Number.isInteger(2017); // true
Variables
// declaring variables
// variable names can also contain $ and _
var varName; // function scope, heusted!
let varName; // ES06 Standard, blockscope
const varName = "initialValue"; // variables which cannot be reassigned,
// must be initialized during declaration
// VARIABLE SCOPE:
/* 1 functionscope VS blockscope!
* ..if declared in function it is not availible outside of it
* ..if declared in block (loops for example)
* var is availible outside of the block/loop
* let is NOT availible outside of the block/loop
* 2 local vs global scope!
* ...it is possible to have the same variable name as global and local scope,
* in this case the local scope is precedenced over the global!!
*/
short circuit assignments
- assigns
myVariablethe value ofmyNamein casemyNameis truthly and"no-name-selected!"in case of falsly. - In the below example the empty string will be evaluated falsly and the string
"no-name-selected!"will be assigned!
let myName = "";
let myVariable = myName || "no-name-selected!";
Type-Conversions
// convert not-numeric values to numeric ones
+3 // 3
+'3' // 3
+true // 1
+false // 0
+null // 0
// unary plus/negation operator
var str = "4" // "4" (String)
var num = +str // -4 (Number)
// TYPE CONVERSIONS
let num1 = parseInt("1"); // converts string to number (float or int)
parseInt(string, radix); // radix=2 -> converts from binary
Comparison Operations
// COMPARISON OPERATORS
/* different datatypes are converted so the match!
* equality operator: == (datatype conversion is done)
* identity operator: === (datatypes must be the same) -> MORE STRICT!
*/
1=="1" // true
"str"=="str" // true
let num = 1; // saved as number
num==="1" // FALSE!!
num.toString()==="1" // true
true === 1 // false
false === 0 // false
true == 1 // true
false == 0 // true
== // equality operator
=== // identity operator
!= // inequality operator
!== // strictly inequality operator
> // greater than (converts datatypes)
>= // greater or equal than (converts datatypes)
< // less than (converts datatypes)
<= // less or equal than (converts datatypes)
// identity vs equality operator
"test" === ['test'] // false
"test" == ["test"] // true (typeconversion done)
"3" === 3 // false
"3" == 3 // true (typeconversion done)
&& // inclusive AND
|| // inclusive OR
! // not operator (reverses value of a boolean)
!true // false
Truthly and Falsly
- As well as a type, each value also has an inherent boolean value, generally known as either truthy or falsy.
- Some of the rules are a little bizarre so understanding the concepts and effect on comparison helps when debugging JavaScript applications.
- The following values are always falsy:
false0(zero)''or""(empty string)nullundefinedNaN(e.g. the result of 1/0)
- Everything else is truthy. That includes:
'0'(a string containing a single zero)'false'(a string containing the text “false”)[](an empty array){}(an empty object)function(){}(an "empty" function)
Code Example
The assigned truthly and falsly values can be used to check if a variable exists, but be aware, sometimes a variable exists but has a value assigned that is represented by falsly (for example the Number 0 and any empty String). See example below:
// STRINGS
// truthly (any not empty string)
const strTruthly = "I exist!";
if (strTruthly) {
console.log("String strTruthly was evaluated truthly");
} else {
console.log("String strTruthly was evaluated falsly");
}
// falsly
const strFalsly = "";
if (strFalsly) {
console.log("String strFalsly was evaluated truthly");
} else {
console.log("String strFalsly was evaluated falsly");
}
// NUMBERS
// truthly (any number not 0)
const numTruthly = -1;
if (numTruthly) {
console.log("Number numTruthly was evaluated truthly");
} else {
console.log("Number numTruthly was evaluated falsly");
}
// falsly
const numFalsly = 0;
if (numFalsly) {
console.log("Number numFalsly num was evaluated truthly");
} else {
console.log("Number numFalsly num was evaluated falsly");
}
Strings
// string concatenation
consol.log("Hello " + "World!");
// string interpolation (ES06)
console.log(`my name is "${thomas}"`); // no escaping, better readibility
// escaping
var s = "this is how you escape doublequotes: \"YAY\"";
var s2 = "this is how you escape backslash: \\";
x = "\'"; // single quote
x = "\"" // double quote
x = "\\" // backslash
x = "\n" // newline
x = "\r" // carriage return
x = "\t" // tab
x = "\b" // backspace
x = "\f" // form feed
// basic string functions
string.length // retursn length of string (integer)
str.toUpperCase() // all characters to upper case
str.toLowerCase() // all characters to lower case
// chosing characters of string
str.charAt(index); // returns char at index (dot notation)
str[index] // returns char at index (bracket notation)
str[string.length-1] // returns last character of string
// substr (second argument = maximum lengt of returned string)
str.substr(index, maxLength) // length of returned string <= maxLength
str.substr(1) // omitt first character of string
// substring (second argument = index to stop at but not include)
str.substring(index, endPos)
str.substring(1, str.lenght) // omitt first character of string
str.substring(1) // omitt first character of string
// split -> return array
str = "this is an example!"
str.split(delimitter, maxSplits); // maxSplits <= returned array length
str.split(" ") // ["this", "is", "an", "example"]
str.split(" ", 2) // ["this", "is"] -> last two cases are thrown away
str.split(""); // separate each character
// split -> get same result as in java "str.split(' ', 2);"
sameResultAsInJava = [str.split(' ')[0], str.split(' ').slice(1).join(' ')]
// check first character
str.startsWith("H"); // returns true or false
Arrays
Array Example
// initialize and assign empty array
var myArray = []
// fill array
myArray = ["stringinput", 23, "hey"];
// initialize and fill in one step
var matrix = [[1,2,3],
[4,5,6],
[7,8,9]];
// ARRAY LENGTH
myArray.length // no curly braces! (same syntax as with strings)
// LAST ELEMENT
myArray.push(content); // pushing to end of array
myArray.pop() // takes away last element and returns it
// FIRST ELEMENT
myArray.unshift(content); // pushing to beginning of array
myArray.shift(); // takes away first element and returns it
Important: Arrays mutated inside of a function will keep that change even outside the function
function myFunc (arr) {
arr.push("pushed element!"); // change also visible outside function!
}
Nested Arrays (Matrices)
const matrix = [[1,2],[3,4]]; // matrix
// call matrix
console.log(matrix[1][0]); // row:1, col:0 -> 3
Array Functions
- Functions
- Iterators
- .forEach(): do for each element
- .map(): do for each element and return new array
- .filter(): return filtered array
- .findIndex(): find first index where a condition is met
- .reduce(): operates with 2 elements of array in each step
- .some(): returns T or F if at least one arrayelement meets a given condition
- .every(): returns T or F it all arrayelements meet a given condition
.sort()
// sorts array (only alphabetically, numbers wont sort numerically)
// manipulates the array itself (object manipulation)
// arraymanipulation works also on const arrays
["a","f","c"].sort(); // returns ["a", "c", "f"]
[5,43,1].sort(); // returns [1,43,5] (!!!)
.sort()
.concat()
// does NOT manipulate original array
// returns new array!
[1,2,3].concat([4,5,6]) // returns [1,2,3,4,5,6]
.slice()
// like a substring, just with arrays
// returns a new array!
.slice(firstIndex) // lastIndex automatically the end!
.slice(firstIndex, lastIndex) // first index included, last index excluded
// EXAMPLES
const array = [0,1,2,3,4];
array.slice(2); // returns [2,3,4] -> subarray starting at index 2
array.slice(2,4) // returns [2,3] -> last index not included
array.slice(0,2) // returns [0,1] -> first 2 elements of array
array.slice(-2) // returns [3,4] -> last 2 elements of array
.splice()
// delets some elements and injects n new ones
// manipulates the object and returns removed elements as new array
.splice(startingIndex, deleteCount, item1, item2, item3, ..., item n)
// EXAMPLEX
const array = [0,1,2,3,4];
array.splice(0,2, -1,0,1); // first two elements are removed [0,1]
// injected elements are [-1,0,1]
// array after functioncall: [-1,0,1,2,3,4]
// removed elements [0,1] are returned as new array
.forEach()
// does NOT manipulate original array
// not returning anything
const artists = ['Picasso', 'Kahlo', 'Matisse', 'Utamaro'];
artists.forEach(artist => {
console.log(`${artist} is one of my favorite artists.`);
});
.map()
// does NOT manipulate original array
// returns new array!
const numbers = [1, 2, 3, 4, 5];
const squareNumbers = numbers.map(number => {
return number * number;
});
.filter()
// does NOT manipulate original array
// returns new array!
array.filter(element => {
return (condition); // returns the array element when truthy!
})
// EXAMPLE
const things = ['desk', 'chair', 5, 'backpack', 3.14, 100];
const onlyNumbers = things.filter(thing => {
return typeof thing === 'number';
});
.findIndex()
// finds FIRST index where given condition is true
// does not manipulate original array
// returns one number (index)
const numbers = [99, 25, 100, 78, 5, 9];
const biggerThan100 = numbers.findIndex(num => {
return num > 100;
});
// returns 2 (because element with index 2 is the first one to be >100)
.reduce()
const array1 = [1, 2, 3, 4];
const reducer = (inp1, inp2, inp3, inp4) => inp1 + inp2;
// inp1 = accumulator -> variable that is assigned 0 at start
// and is passed over to each iteration
// inp2 = currentValue (of the current element)
// inp3 = currentIndex (of the array)
// inp4 = array (full array is passed)
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5)); // 5 is the second argument of .reduce()
// expected output: 15 // -> assigns start value for accumulator
.some()
// returns true or false
// no object manipulation
// checks if a condition is true for at least one element of the array!
var array = [1, 2, 3, 4, 5];
array.some(element => {
return element >3;
});
// expected output: true (because 2 elements are bigger than 5)
.every()
// returns true or false
// no object manipulation
// checks if a condition is true for ALL elements of the array!
var array = [1, 2, 3, 4, 5];
array.every(element => {
return element >5;
});
// expected output: false (because not all elements are bigger than 5)
Math
// MATHEMATICS
// random float between (0,1)
Math.random();
// random whole number from [1,max]
Math.floor(Math.random()*(max))+1)
// random whole number between [min,max]
Math.floor(Math.random()*(max-min+1))+min)
// round
Math.round(); // rounds to nearest integer
myNum.toFixed(2); // converts to string + rounded to 2 dec-places
Math.floor(); // rounds down to next integer
Math.ceil(); // dounds up to next integer
// exponentiation
Math.pow(2,3); // 2^3
2**3; // 2^3
Arithmetic Operators
/* arithmetic operators
+ // addition
- // substraction
* // multiplication
/ // division
% // remainder (NOT MODULO) -> works with positive numbers only!
// incrementing / decrementing
x++; // first action, then increase by 1
++x; // increase by 1, then action
x--; // first action, then decrease by 1
--x; // decrease by 1, then action
// augmented operations (short assignment)
var y += 10 // y = y+10
var y -= 10 // y = y-10
var y *= 10 // y = y*10
var y /= 10 // y = y/10
Loops
there are different loops:
For-Loop
for (let i=0; i<10; i++) {
// do something
}
For-Each
let arr = [1,2,3,4,"hello",6];
for (let a of arr) {
console.log(a);
}
- not limited to arrays. Also looping through objects possible!
- for arrays you can also use the
forEach()method (see "Iterator: .forEach()")
Looping through Objects
myObject = {
name: "arthur",
age: 78
}
// loop through object and display all property names and values
for (let props in myObject) {
console.log(`${props}: ${myObject[props]}`)
};
// outputs:
// name: arthur
// age: 78
While/Do-While
while (condition) {
// do something!
}
do {
// do something
} while(condition); // DO NOT FORGET SEMICOLON AT END
If Else
if (true) {
// do something
} else if (false /*another condition*/) {
// do something
} else {
// do something
}
Ternary If-Else
- semicolon only at the end of the line
(condition) ? (do if true) : (do if false);
age>=18 ? "adult" : "child"; // returns "adult" or "child"!
// also works with function-calls inside
age>=18 ? console.log("over 18") : console.log("under 18");
Switch
break / default
- do not forget to
breakafter each statement, otherwise the cases that follow will also be run! (If you omit the break statement, the next case will be executed even if the evaluation does not match the case.) - It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway
- The
defaultcase does not have to be the last case in the block (but if so don't forget to end the default case with a break!)
matching and choosing cases
- Switch cases use strict comparison
(===) - The values must be of the same type to match.
- If multiple cases matches a case value, the first case is selected.
- If no matching cases are found, the program continues to the default label.
Example
switch (variable_type) {
case "string":
// do something
break;
case "number":
// do something
break;
case "undefined":
// do something
break;
case "object"
// do something
break;
default
// do default
break; // "break" not mandatory
}
Functions
- Function Declaration
- Function Expression / Anonymous Function
- Arrow Function (ES06)
- Default Parameters (ES06)
Function Declaration
Start Keyword function
- 4 elements of functions:
- function keyword
function - function identifier (name)
add - function parameters (inside the
()brackets) - function body (whats inside the
{}brackets)
- function keyword
- default return value is
undefined(if not overwritten)
function add(a,b) {
console.log("Adding " + a + " and " + b);
return a+b;
}
Function Expression / Anonymous Function
- anonymous functions -> have no function identifier (no name)
- can be stored in variables!
- use case: to pass functions into other functions we can use function expressions
const x = function (a, b) {
return a * b
};
console.log(x(2,3)); // 6
Self-Evoking Functions
- anonymous function is created and instead of stored in a variable directly evoked (called)
(function(a,b) { // anonymous function
return a+b // adds 2 numbers
})(1,2); // enclosed in () makes it self-evoking.
// last () are here to pass parameters
Arrow Function
const x = (a, b) => {
return a * b
};
console.log(x(2,3)); // 6
concise body arrow functions
- functions that take only one parameter don't need to be enclosed in parentheses!
- zero or multiple parameters have to be enclosed in parentheses
- single line blocks do not neet curly braces
{}! returnstatement is skipped!- do NOT use arrowfunctions in classes, since
this.
// one parameter
const increase = input => input++; // be aware, increased value gets returned only!
const squareNum = num => num*num; // no manipulation on the passed parameter/object
// zero or multiple parameters
const add = (a, b) => a + b;
const pi = () => 3.14;
Default Parameters
Default Parameters (since ES06)
// one default parameter
function items(item = "myDefaultItem") {
console.log(`Item in List: ${item}`);
}
items("pen") // Item in List: pen
items() // Item in List: myDefaultItem
// multiple parameters
function items(item1 = "pen", item2 = "coffee") {
console.log(`item1: ${item1}, item2: ${item2}`);
}
items("cup"); // item1: cup, item2: coffee
items("cup", "bag") // item1: cup, item2: bag
items(undefined, "bag") // item1: pen, item2: bag
items(); // item1: pen, item2: coffee
OOP
- OOP = Object Oriented Programming
- way of organizing code and the overall programm
- real world things can be represented as objects and objects can have different relations to each other
- basically a simplification of complex relationsships as we know them from reality
Content of this Chapter
Objects
Object Example (with Getters/Setters and Methods)
// OBJECT LITERAL (= variable thats holding an object)
let myObjectLiteral = {}; // empty object
// CAT OBJECT EXAMPLE
var cat = { // underscore indicates private fields
_name: "Whiskers", // only an agreed form of syntax
_age: 5, // -> js doesn't treat them differently!
// OBJECT METHODS (ES06 style)
makeSound () {
console.log("miau");
}, // dont forget comma
attack () {
console.log("grrr!");
},
/* OBJECT METHODS old style:
* makeSound: function() {
* console.log("miau");
* },
* attac: function() {
* console.log("grrr!");
* },
*/
// GETTERS (starting with keyword "get")
get name() {
return this._name;
},
get age() {
return this._age;
},
// SETTERS (starting with keyword "set")
set name(newName) {
this._name = newNane;
},
set age(newAge) {
this._age = newAge;
} // no comma at end
};
console.log("my cats name: " + cat.name); // DOT NOTATION
console.log("my cats name: " + cat["name"]) // BRACKET NOTATION
console.log("nbr of legs: " + cat.legs); // DOT NOTATION
console.log("nbr of legs: " + cat["legs"]; // BRACKET NOTATION
// USING OBJECT METHODS
cat.makeSound();
cat.attack();
cat.age(); // getter method
cat.age; // shortform!
cat.age = 12; // setter method (looks like assigning a value)
// -> but its using the set method to assign
// the variable _age!
to see how you can loop through objects check out the section Loops - ForEach.
Add Properties to Object
// with the assign operator (=) we can create new object-properties
// if the propery name is already existant, it gets overriden.
var myObject = {
prop1: "something";
}
myObject.prop2 = "something else"; // create new prop (dot notation)
myObject["prop3"] = "a third property added"; // create new prop (bracket notation)
myObject.prop1 = "another change"; // updates / overrides prop2!
delete myObject.prop3; // third property deleted!
// Check if Property exists
myObject.hasOwnProperty("property");
Brackets vs Dot Notation
// bracket notation allows the use of characters
// that can't be used with dot notation:
var foo = myForm.foo[]; // incorrect syntax
var foo = myForm["foo[]"]; // correct syntax
// Secondly, bracket notation is useful when dealing
// with property names which vary in a predictable way:
for (var i = 0; i < 10; i++) {
someFunction(myForm["myControlNumber" + i]);
}
Const Objects
Objects initialized with const can be mutated (add and remove properties as well as assign new propery-values). But they can't be reasigned.
const cat = {
id: 1,
name: "kitty",
age: 23
};
// SOME ACTIONS
cat.age = 24; // works, updates propery-value
cat.gender = "female"; // works, creates new property
delete cat.id; // works, deleted ip-property
cat = {} // error! const can't be reassigned!
Destructed Assignments
const animal = {
type: "cat",
name: "whiskas",
preferences: {
food: "mouses",
activity: "sleep"
}
};
// assign to new constant variable "type" and "name"
const { type } = animal;
const { name } = animal;
// you can also assign nested objects
// and also multiple destructured assignments!
const { food, activity } = animal.preferences;
console.log(type); // "cat"
console.log(name); // "whiskas"
console.log(food); // "mouses"
console.log(activity); // "sleep"
Build In Object Methods
see MDN web docs from mozilla for further dokumentation.
Object.keys()
const obj = {
a: 'somestring',
b: 42,
c: false
};
console.log(Object.keys(obj));
// expected output: Array ["a", "b", "c"]
Object.entries()
const obj = {
a: 'somestring',
b: 42,
c: false
};
console.log(Object.entries(obj));
// expected output:
// [ Array ["a", 'somestring'], Array ["b", 42], Array ["c", false] ]
// Iterating through Objects:
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
Object.assign()
// reassigns "key: value" pairs of target object
// input: one or multiple source objects
// if key exists in target: will be reassigned
// if key does not exist in target: will be created
const target = { a: 1, b: 2 };
const source1 = { b: 5, c: 6 };
const source2 = { d: -1 };
// returns new Object...
const returnedObj = Object.assign(target, source1, source2);
console.log(returnedObj);
// expected output: Object { a:1, b:5, c:6, d:-1}
// ...but also manipulates original object!!
console.log(target);
// expected output: Object { a:1, b:5, c:6, d:-1}
Object.freeze()
- does not work in chrome...!
- create immutable (read only objects)
"use strict"; // throws errors when bugs in code
const obj = Object.freeze({
a: 42
});
obj.a = 33;
// Throws an error in strict mode -> read-only!
console.log(obj.a);
// expected output: 42 -> initial assignment
Factory Functions
- function that creates instances of objects!
- comparison classes vs factory functions (ff)
- classes use
constructor()function andnewkeyword for instantiation. - classes use
thiskeyword to reference fields, while ff have local scope of all variables defined insied them. - classes can inherit from other classes (more complex structures possible)
- factoryFunctions are encapsuled -> you can define what you export with
Object.freeze({method1, method2})(not sure how that works). See this blogpost
- classes use
Factory Function (with Function Expression)
const createAnimal = (name, age, sound) => {
return {
name: name,
age: age,
makeSound () {
console.log(sound);
}
}
}
const cat = createAnimal('whiskers', 2, 'miau');
cat.makeSound();
const dog = createAnimal('Honigkuchen', 5, 'wuff');
dog.makeSound();
Factory Function (with Function Declaration)
function createAnimal(name, age, sound){
var name = name;
var age = age;
function makeSound(){
console.log(sound);
}
return Object.freeze({ // export object
makeSound // only export function makeSoun, no fields!
});
}
Property Value Shorthand in Factory Functions
const createAnimal = (name, age) => {
return {
name,
age
}
}
Classes
class Animal {
constructor() {
}
}
JSON
Example
var myMusic = [ // myMusic is an Array with objects!
{ // {} -> Object
"artist": "Billy Joel", // property-value - pairs
"title": "Piano Man",
"release_year": 1973,
"formats": [ // value can also be an array
"CD",
"8T",
"LP"
],
"gold": true
}, // objects are seperated with comma
{
"artist": "Billy Joel",
"title": "Piano Man",
"release_year": 1973,
"formats": [
"CD",
"8T",
"LP"
],
"gold": true
}
];
ES06
// STRICT MODE
"user strict"; // put at the beginning of script or inside a function
throws errors when...
- variables are not being initialized properly
- trying to assigne value to a non-writable property (instead of ignoring it!)
- trying to delete objects that are not created (instead of ignoring it)
- function "myFunc(a,a,b)" is not allowed! -> without strict mode it will be ignored!
- "with" and "eval" something.. (dont know yet)
QUESTIONS
- Indendation 4 or 2 spaces? (lol)