0% found this document useful (0 votes)
35 views40 pages

Technikum Wien - Scripting - Basics 2

The document discusses functions, arrays, objects, and variables as part of a scripting introduction. It provides examples and explanations of function declarations, expressions, and anonymous functions. It also covers array methods and properties as well as object keys, properties, and methods.

Uploaded by

Marlene Riethus
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views40 pages

Technikum Wien - Scripting - Basics 2

The document discusses functions, arrays, objects, and variables as part of a scripting introduction. It provides examples and explanations of function declarations, expressions, and anonymous functions. It also covers array methods and properties as well as object keys, properties, and methods.

Uploaded by

Marlene Riethus
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Functions

Arrays
Objects
Variables
Scripting Introduction
Functions
▪ Encapsulate actions for _later_ invocation
▪ Can be invoked multiple times
▪ Wrapped in curly brackets
▪ Can have return values
▪ Parameters passed on in parenthesis
▪ Can also be a parameter
▪ Integral part of inheritance
▪ No methods, are functions as well (see Object section)

© UAS Technikum Wien


2
Functions
– Function declaration (loaded before code execution (hoisting))
function say( name ) {
console.log( name );
}
– Function expression (loaded when interpreter reaches code)
say = function( name ) {
alert( name );
}
– Anonymous Function (a function without a name)
function( name ) {
alert( name );
}
– Array Function ([ES6] shortcut with special scoping, talked about later)
function ( name ) => {
alert( name );
}
© UAS Technikum Wien
3
Example Functions
factoral = function( number ) {
result = 1;
var ix = 1;
while( ix <= number ) {
result = result * ix;
ix++;
}
return result;
}
result = factoral ( 5 );
result = factoral ( 10 );
result = factoral ( 15 );

[code]

© UAS Technikum Wien


4
Functions - Examples
Examples

▪ Factoral function
▪ Mask credit card numbers as function

© UAS Technikum Wien


5
Composite “complex” Data Types
▪ Arrays
▪ Objects

© UAS Technikum Wien


6
Arrays
▪ A comma-separated list of values wrapped in square braces.
▪ Values are accessed by their index starting from 0.
▪ Arrays can be nested inside other arrays.
▪ Assigment
numbers = [ 1, 2, 3 ];
names = [ "John", "Peter", "Jane" ];
something = [ 1, "Hi", -12.35 ];
coordinates = [ [ 1, 2 ], [ 2, 3 ], [ 3, 4 ] ];
▪ Getting values
name = names[ 1 ]; // "Peter"
xCoordiate = coordinates[ 1 ][ 0 ]; // 2
▪ Setting values
names[ 1 ] = "Sepp";
coordinates[ 1 ][ 0 ] = 3;
[code]
© UAS Technikum Wien
7
Arrays - Useful methods (1)
names = [ "John", "Peter", "Jane" ];

▪ push( element ) Adds new element to the end


names.push( "Joan" ); // 4;
console.log( names ); // [ "John", "Peter", "Jane", "Joan" ];

▪ pop() Removes last element and returns its value


name = names.pop(); // "Jane";
console.log( names); // [ "John", "Peter" ];

▪ unshift( element ) Adds new element at beginning


names.unshift( "Joan" );
console.log( names ); // [ "Joan", "John", "Peter", "Jane" ];

▪ shift() Returns & removes first element and returns its value
name = names.shift(); // "John"
console.log( names ); // [ "Peter", "Jane" ];
© UAS Technikum Wien [code]
Arrays - Useful methods (2)
▪ length; number of elements
names.length; // 3

▪ sort(); sorts an array


names.sort() // [ "Jane", "John", "Peter" ];

▪ reverse(); reverts ordering


names.revert() // [ "Jane", "Peter", "John" ];

▪ indexOf( s ) Return position of element


ixPeter = names.indexOf( "Peter" ); //2
ixSepp = names.indexOf( "Sepp" ); // -1

▪ join( s ) Joins all elements of an array into a string


allNames = names.join( "->" ); // "John->Peter->Jane"
[code]

© UAS Technikum Wien


(example_3_3, example_3_4, example_3_5)9
Arrays - Examples
Examples

▪ User-friendly month
▪ European countries

© UAS Technikum Wien


10
Arrays - Useful methods (3)
▪ splice( start, howMany ) cuts elements
name = names.splice( 1, 1 );
console.log( name ); // "Peter"
console.log( names ); // [ "John", "Jane" ];

▪ concat( l2 ) Merges arrays and returns result


browsers = [ "Chrome", "Edge" ];
merged = names.concat( browsers );
console.log( merged ); // [ "John", "Peter", "Jane", "Chrome", "Edge" ]

▪ forEach( function( element, ix ) ) Iterates array and calls function with element and index
names.forEach( function( name, ix ) { // <- anonymous function
console.log( ix + " : " + name );
} );

[code]
© UAS Technikum Wien
11

https://www.w3schools.com/jsref/jsref_obj_array.asp
Anonymous Functions (1)
numbers = [ 1, 2, 3, 4 ];
numbers.forEach( function( number ) {
result = 1; ix = 1;
while( ix <= number ) {
result = result * ix;
ix++;
}
console.log( result );
}
);

[1,2,3].forEach( (num, ix) => {


console.log( `index: ${ix}, value:${num}` );
} );
12

© UAS Technikum Wien


[code]
Anonymous Functions (2)
▪ Pro
– Less code
– Code self-contained
– Improved code readability

▪ Con
– Not reusable
– Not unit testable
– Not accessible at runtime

© UAS Technikum Wien


13
Anonymous Functions - Example
Example

▪ Alert a sentence word by word


▪ A conjugation quiz

Exercise

▪ Re-write previous example “European Countries” using forEach

© UAS Technikum Wien


14
Truthy/falsy values
▪ In JS any value is either “truthy” or “falsy”
▪ “Truthy” does not mean a value is really [true]
▪ It means in boolean context (comparison) the value is forced (coerced)
to [true]
isTruthy = function( x ) { falsy truthy (everything else)
if( x ) {
alert( x + " is truthy" );
} false true
else {
alert( x + " is falsy" );
null {}
} 0 []
} "" "some string"
isTruthy( 1 ); // 1 is truthy
isTruthy( 0 ); // 0 is falsy
'' 3.14
isTruthy( ls[ 3] ) undefined function()
isTruthy( "" ); // 0 is falsy NaN
isTruthy( { a: 1 } ); // [object Object] is truthy
isTruthy( isTruthy ); // func[..] is truthy
© UAS Technikum Wien
[code]
15
Objects
▪ A comma-separated list of colon-separate key-value pairs wrapped in
curly braces. (Object Literal)
Person = {
name : "John Doe"
, age : 35
, phoneNumbers : [ 123345, 123345 ]
}
▪ Creates its own “namespace” encapsulating functions and variables
▪ Get
name = Person.name; // "John Doe"
age = Person[ "age" ]; // 35
▪ Set
Person.name += " Poe";
Person.phoneNumbers[ 0 ] = 234234;
[code]
© UAS Technikum Wien
16
Objects - useful methods
▪ delete object[ key ] deletes key/value pair (attribute or method)
delete Person.name;

▪ array = Object.keys( object ) get keys of an object


l = Object.keys( Person ); // ["name", "age", "phoneNumbers" ]

▪ hasOwnProperty( property) returns true if in the prototype chain of "object"


more on this when dealing with inheritance

▪ isPrototypeOf( object ) returns true if in the prototype chain of "object"


more on this when dealing with inheritance

[code]

© UAS Technikum Wien


17
Iterate through an object
▪ “for in” loop
▪ Loops through all properties of an object
▪ property is exposed as string

for( property in Person ) {


value = Person[ property ]; // Person.property raises exception!
result = "key: " + property;
result += " value: " + value;
console.log( result );
}

[code]

© UAS Technikum Wien


18
Typical uses of objects in JS
▪ Object Maps (hashtable, associative array)
▪ Setting objects (manifest files)
▪ Result lists (database output)
▪ Simple "class" (fake singleton)
▪ Base object for inheritance (covered later)
▪ Anything we get from the server

© UAS Technikum Wien


19
Object Maps
▪ aka Dictionary, associative arrays, hashtable
▪ Like an array but with a name (string) as key rather than an index
(integer)
▪ In JS mostly created as simple object

cards = {
Ace : 11
, King : 5
, Queen : 4
, Jack : 3
, "The Joker" : 15
}

© UAS Technikum Wien


20
Object Maps - use cases
▪ One way to lookup/search for element

deck = [ "Ace", "The Joker", "Jack", "Jack", "Jack" ];


result = 0;
deck.forEach( function( card ) {
result += cards[ card ];
} );
console.log( result ); // 35;

[code]

© UAS Technikum Wien


21
Object Maps - use cases
▪ Fast way to aggregate unique key structures by testing for existence of
a key in a map and filling it up.

stack = {};
deck.forEach( function( card ) {
if( ! stack[ card ] ) {
stack[ card ] = 0;
}
stack[ card ]++;
} );
console.log( stack ); // {"Ace":1,"The Joker":1,"Jack":3}

[code]

© UAS Technikum Wien


22
Object maps - Example
Example

▪ Card deck report

© UAS Technikum Wien


23
Settings objects
▪ Excerpt of a browser extension manifest file
manifest = {
app : {
background : {
scripts : [ "background.js", "uus.js" ]
}
},
manifest_version : 2,
name : "TimesTable",
version : "1.0.1",
default_locale : "en",
description : "An extension to annoy your kid for a good cause"
}
}

© UAS Technikum Wien


24
Result lists
▪ Results of queries against a database or web service.
result = {
from : 11
, to : 20
, total : 312
, events : [
{
bookingCode : "UP004"
, event : "MS - SharePoint 2016"
, venue : "Plaza Hotel"
, speakers : [
"Mr. John Wayne", "Ms. Holly Johnson"
]
}
,{
bookingCode : "AX209"
, event : "OT - Content Server 16"
, venue : "Hotel Regent"
, speakers : [
"Mr. John Wayne", "Ms. Julia Roberts"
]
}
]
}

© UAS Technikum Wien


25
Simple "class" (fake singleton)
▪ Technically it is just a (global) variable
▪ Practically we have attributes and methods
▪ It is one of the most commonly used constructs
Popup = {
title : "default title"
, width : 300
, height : 200
, color: {
titleBar : "blue"
, titleText : "white"
}
, create : function( config ) {
// implementation
}
, moveTo( x,y ) { // <- shortcut
// implementation
}
}

[code]

© UAS Technikum Wien


26
JavaScript Object Notation
▪ aka JSON
▪ Prevalent in JS
▪ Used as
– Data structure in JS
– Interchange format like XML
▪ Difference to pure JS Object
– Keys wrapped in double quotes
– No functions allowed

© UAS Technikum Wien


27
JSON methods
▪ JSON.stringify( o ) convert an object to string

▪ JSON.parse( s ) convert a string to an object

[code]

© UAS Technikum Wien


28
Naming of variables

▪ JavaScript is loosely typed and applies type coercion


▪ hard to know type of variable at times
▪ “Hungarian notation” can help
▪ Two types of HN (system, application)
▪ Use of HN is controversial
▪ Hungarian notation in a nutshell:
▪ prefix of kind of variable in lowercase
▪ type can be inferred from prefix
▪ prefix followed by variable name

© UAS Technikum Wien


29
Naming of variables - Examples
sManager = “John Wayne” name of a manage string

mailManager = “[email protected]” email of a manager string

cManager = 15 count of mangers number

ixManager =3 index of number

lsManagers = [ “John Wayne”, “Clint Eastwood” ] list of manager names array (of strings)

oManager ={ manager object object


sName : “John Wayne”
, mail : “[email protected]
, nAge : 34
}

loManagers = [ { sName : … } list of manager objects array (of objects)


, { sName : … } ]

dnManagerMenu = document.querySelector( “#Manager” ) DOM node of manager’s menu DOM node

[more examples]
© UAS Technikum Wien
30
The “window” object (a first visit)
▪ The “window” object is the top most object in JS
▪ In JS nothing exists outside “window”
▪ “self” is an equivalent of “window”
▪ There is a lot to say about it, but for now we are interested in:
– It is parent to “window” methods like alert, prompt, console
– It is parent to all global variables
– We can omit preceding “window” in front of above two (we did
this until now and will continue to do so).
▪ alert( “Hi” ) == window.alert( “Hi” )
▪ alert( s ) == alert( window.s )

© UAS Technikum Wien


31
Variable scope
▪ Two types of scopes
– Local
▪ Created inside functions using "var" (function scope)
▪ [ES6] Created inside blocks using "let" (block scope)
▪ Passed on as functions argument
▪ Accessible only inside the function/block
– Global
▪ Created outside of functions
▪ Created inside function without "var" keyword
▪ Accessible from everywhere
▪ In case of ambiguity accessible via “windows”
© UAS Technikum Wien
32
Variable scope example
sky = "blue"; // <- global func( "red" );
eyes = "brown"; // <- global
func= function( blood ) { // <- local console.log( 8, sky ); // blue
var sky = "grey"; // <- local console.log( 9, eyes ); // green
var coffee = "black"; // local console.log( 10, sun ); // yellow
if( sky == "grey" ){ console.log( 11, blood ); // ReferenceError: blood is not defined
let sky = "cloudy"; // <- local (block scope) console.log( 12, coffee ); // ReferenceError: coffee is not defined
let sun = "hidden"; // <- local (block scope)
console.log( 0, sky );
console.log( 1, sun );
}
console.log( typeof sun )
eyes = "green"; // <- global
sun = "yellow"; // <- global
console.log( 2, sky ); // grey
console.log( 3, window.sky ); // blue
console.log( 4, eyes ); // green
console.log( 5, blood ); // red
console.log( 6, sun ); // yellow
[code]
console.log(
© 7, coffee ); // black
UAS Technikum Wien
33
}
The “this” keyword (1)
▪ inside an object's function (method)
– "this" points to the object
▪ inside an event handler's function
– "this" points to the trigger element (covered later)
▪ Rest
– "this" points to "window"
– that includes nested functions (covered in a minute)

© UAS Technikum Wien


34
The “this” keyword (2)
▪ inside an object's function (method)
str = "global variable";
obj = {
str : "object attribute"
, func : function() {
let str = "inside parent function";
console.log( 1, str ); // "inside parent function"
console.log( 2, this.str); // "object attribute" .. “this” points to the object
console.log( 3, window.str ); // "global variable"
}
};
obj.func();
console.log( 4, this.str ); // “global variable” (Rest)

[code]

© UAS Technikum Wien


35
Examples

Event management - event report


Event management - list of speakers

Exercise

Credit card masking as object


The “that” keyword (normal functions)
▪ Is not a keyword, it’s a local variable set in an object’s function
(method) used inside its nested functions to access the parent object.

var s = "global variable";
var o = {
s : "object attribute"
, fn : function() {
let that = this;
let normalFunction = function() {
console.log( "normal function (that.s): " + that.s );
console.log( "normal function (this.s): " + this.s );
console.log( "normal function (window.s): " + window.s );
};
normalFunction();
}
};
o.fn()
[code]
37

© UAS Technikum Wien


Arrow functions and “this”/”that”
▪ Arrow functions “lexically” bind their context. “this” refers to the
originating context, e.g. the Object.
var s = "global variable";
var o = {
s : "object attribute"
, fn : function() {
let arrowFunction = () => {
console.log( "arrow function (this.s): " + this.s );
console.log( "arrow function (window.s): " + window.s );
};
arrowFunction();
}
};
o.fn();
[code]

38

© UAS Technikum Wien


Function shortcut in objects
▪ Shortcut object functions, pure syntactic sugar, no difference in
behaviour.
let obj = {
s : "attribute"
, oldSchool : function() {
// do sg
}
, newSchool() {
// do sg
}
};

39

© UAS Technikum Wien


Examples

Event management - Improve output

Excercise
Event management - Improve output 2

You might also like