SlideShare a Scribd company logo
1 of 122
Download to read offline
JavaScript for ABAP Programmers
Syntax
Chris Whealy / The RIG
ABAP
Strongly typed
Syntax similar to COBOL
Block Scope
No equivalent concept
OO using class based inheritance
Imperative programming

JavaScript
Weakly typed
Syntax derived from Java
Lexical Scope
Functions are 1st class citizens
OO using referential inheritance
Imperative or Functional programming
Syntax
Syntax: Keywords and Reserved words
As with any other language, JavaScript has a list of words that may not be used as variable names
because they are keywords of the language. These are:
break, case, catch, continue, debugger, default, delete, do, else, false, finally, for,
function, if, in, instanceof, new, null, return, switch, this, throw, true, try, typeof,
var, void, while, with

However, the ECMAScript specification also excludes the following words from implementations
because they have been reserved for future use. These are:
class, enum, export, extends, import, super, implements, interface, let, package, private,
protected, public, static, yield

© 2013 SAP AG. All rights reserved.

4
Syntax: Code Blocks
A code block is formed by enclosing a set of logically related JavaScript statements in curly braces.
Code blocks are used to define functions, or to delimit a set of instructions used for flow control.
// A stand-alone code block
{
// Everything inside the curlies belongs
// to this code block
}

© 2013 SAP AG. All rights reserved.

A standalone code block is not very
useful in JavaScript because it can
neither be referenced nor reused

5
Syntax: Code Blocks
A code block is formed by enclosing a set of logically related JavaScript statements in curly braces.
Code blocks are used to define functions, or to delimit a set of instructions used for flow control.
// A stand-alone code block
{
// Everything inside the curlies belongs
// to this code block
}

// Here's a more useful code block
function doThis(someParameter) {
// This code block becomes the executable
// part of a function object.
}

A standalone code block is not very
useful in JavaScript because it can
neither be referenced nor reused

Preceding a code block with the keyword
function() (and an optional name)
creates a function object
A function is executed by using the
invocation operator () after the function
name with zero or more parameters

doThis("a value");

© 2013 SAP AG. All rights reserved.

6
Syntax: Flow Control: Selection
A selection statement determines which code block should be performed based on the outcome of a
condition. Selections are either simple left/right branches or multi-way branches.
// Left/Right branch:
// Is this condition true?
if (someCondition == true) {
// Yup, so do this code block
}
else {
// Nope, do this code block instead
}

© 2013 SAP AG. All rights reserved.

A simple left/right branch is performed
using an if/else construct.

7
Syntax: Flow Control: Selection
A selection statement determines which code block should be performed based on the outcome of a
condition. Selections are either simple left/right branches or multi-way branches.
// Left/Right branch:
// Is this condition true?
if (someCondition == true) {
// Yup, so do this code block
}
else {
// Nope, do this code block instead
}

// Multi-way branch:
switch (someValue) {
case "a":
alert("Bang!");
break;
case "b":
alert("Fizz!");
break;
default:
alert("None of the above!");
}
© 2013 SAP AG. All rights reserved.

A simple left/right branch is performed
using an if/else construct.

Multi-way branch is performed
using a switch/case construct

8
Syntax: Flow Control: Iteration
"Iteration" is the name given to the repeated execution of a code block whilst a condition remains true.
// Iterate using 'while'
while (someCondition == true) {
// Do this code block
}

© 2013 SAP AG. All rights reserved.

The condition is tested first. If it evaluates to true, then the
code block is executed and the condition tested again.
As long as the condition remains true,
the code block will be executed

9
Syntax: Flow Control: Iteration
"Iteration" is the name given to the repeated execution of a code block whilst a condition remains true.
// Iterate using 'while'
while (someCondition == true) {
// Do this code block
}

// Iterate using 'for'
for (var i=0; i<someLimit; i++) {
// Do this code block
}

© 2013 SAP AG. All rights reserved.

The condition is tested first. If it evaluates to true, then the
code block is executed and the condition tested again.
As long as the condition remains true,
the code block will be executed
A for loop executes a code block a specific number of times
and is controlled by providing:
• A start value for the loop control variable
• A continuation condition
• An instruction to modify the loop control variable

10
Syntax: Flow Control: Iteration
"Iteration" is the name given to the repeated execution of a code block whilst a condition remains true.
// Iterate using 'while'
while (someCondition == true) {
// Do this code block
}

// Iterate using 'for'
for (var i=0; i<someLimit; i++) {
// Do this code block
}

// Iterate using 'for ... in'
for (var prop in someObject) {
// Perform this code block on each
// property belonging to someObject
}

© 2013 SAP AG. All rights reserved.

The condition is tested first. If it evaluates to true, then the
code block is executed and the condition tested again.
As long as the condition remains true,
the code block will be executed
A for loop executes a code block a specific number of times
and is controlled by providing:
• A start value for the loop control variable
• A continuation condition
• An instruction to modify the loop control variable
The for in construct allows you to
iterate through all the properties
belonging to an object

11
Syntax: Statement Terminators
In JavaScript the statement terminator is a semi-colon. However, be careful; its use is optional!
// Be careful with the optional statement terminator in JavaScript!
var someVariable = "Some value" // The semi-colon is missing, but that's OK because there's nothing ambiguous here...

© 2013 SAP AG. All rights reserved.

12
Syntax: Statement Terminators
In JavaScript the statement terminator is a semi-colon. However, be careful; its use is optional!
// Be careful with the optional statement terminator in JavaScript!
var someVariable = "Some value" // The semi-colon is missing, but that's OK because there's nothing ambiguous here...

// This is also OK. The invisble carriage return after the 'return n * n' statement automatically terminates the expression.
function good_sqr(n) {
return n * n
}

© 2013 SAP AG. All rights reserved.

13
Syntax: Statement Terminators
In JavaScript the statement terminator is a semi-colon. However, be careful; its use is optional!
// Be careful with the optional statement terminator in JavaScript!
var someVariable = "Some value" // The semi-colon is missing, but that's OK because there's nothing ambiguous here...

// This is also OK. The invisble carriage return after the 'return n * n' statement automatically terminates the expression.
function good_sqr(n) {
return n * n
}
// NASTY SURPRISE!! This function always returns the special value 'undefined'!
function bad_sqr(n) {
// The 'return' statement used with no parameters means 'return undefined'. If 'return' is immediately followed by a
// carriage return, then JavaScript assumes that you meant to write 'return undefined'.
// The expression 'n * n;' on its own is valid, but will never be executed because the function has already terminated
return
n * n;
}

© 2013 SAP AG. All rights reserved.

14
Syntax: Statement Terminators
In JavaScript the statement terminator is a semi-colon. However, be careful; its use is optional!
// Be careful with the optional statement terminator in JavaScript!
var someVariable = "Some value" // The semi-colon is missing, but that's OK because there's nothing ambiguous here...

// This is also OK. The invisble carriage return after the 'return n * n' statement automatically terminates the expression.
function good_sqr(n) {
return n * n
}
// NASTY SURPRISE!! This function always returns the special value 'undefined'!
function bad_sqr(n) {
// The 'return' statement used with no parameters means 'return undefined'. If 'return' is immediately followed by a
// carriage return, then JavaScript assumes that you meant to write 'return undefined'.
// The expression 'n * n;' on its own is valid, but will never be executed because the function has already terminated
return
n * n;
}

IMPORTANT!
A missing statement terminator sometimes results in a carriage return being misinterpreted as the end of the statement. Therefore:
•

JavaScript statements should always be terminated explicitly

•

Only split JavaScript statements across multiple lines at points where statement termination is not syntactically possible
© 2013 SAP AG. All rights reserved.

15
Syntax: Comments
Comments can be single line

Or multi-line

// this is a single line comment

/* this is
a multi-line
comment */

The comment syntax in JavaScript is exactly the same as that used in Java, C and C++
Unlike the full line comment delimiter "*" in ABAP, the single line JavaScript comment delimiter //
does not need to start in column 1 of the source code; it can appear anywhere on the line.

© 2013 SAP AG. All rights reserved.

16
Basic Operators
Unary Operators 1/4
A unary operator is an operator that requires only one operand.
Some unary operators can be specified either before (prefix) or after (postfix) their operand.
var value1 = 1;
var value2 = 0;

© 2013 SAP AG. All rights reserved.

18
Unary Operators 1/4
A unary operator is an operator that requires only one operand.
Some unary operators can be specified either before (prefix) or after (postfix) their operand.
var value1 = 1;
var value2 = 0;
// Unary increment ++
// Unary decrement -// The (in/de)crement
value2 = value1++;
value1;
value2;

© 2013 SAP AG. All rights reserved.

operator can be used as either a prefix or a postfix!
// First, assign value1 to value2 then increment value1
// 2
// 1

19
Unary Operators 1/4
A unary operator is an operator that requires only one operand.
Some unary operators can be specified either before (prefix) or after (postfix) their operand.
var value1 = 1;
var value2 = 0;
// Unary increment ++
// Unary decrement -// The (in/de)crement
value2 = value1++;
value1;
value2;

operator can be used as either a prefix or a postfix!
// First, assign value1 to value2 then increment value1
// 2
// 1

value2 = ++value1;
value1;
value2;

// First, increment value1 then assign the result to value2
// 3
// 3

© 2013 SAP AG. All rights reserved.

20
Unary Operators 2/4
The arithmetic operators for addition and subtraction can be used as prefix unary operators.
var value1 = -1;
var value2 = "cat";
-value1; //  1.
+value1; //  -1.
//

Return the negative numeric value
Return the numeric value, not the positive numeric value!
Notice, the minus sign is not flipped!

-value2; //  NaN. A string has no numeric representation, so the result is 'Not a number'
+value2; //  NaN. A string has no numeric representation, so the result is 'Not a number'

© 2013 SAP AG. All rights reserved.

21
Unary Operators 3/4
There are two unary logical NOT operators.
“!” performs a Boolean NOT operation and “~” performs a bitwise NOT operation.
var value1 = false;
var value2 = 2;

// "!" coerces its operand to type Boolean (if necessary), then negates it
!value1;
//  true.
!value2;
//  false. Any non-zero number equates to true, !true is false

© 2013 SAP AG. All rights reserved.

22
Unary Operators 3/4
There are two unary logical NOT operators.
“!” performs a Boolean NOT operation and “~” performs a bitwise NOT operation.
var value1 = false;
var value2 = 2;
var value3 = 0x0F; // A hexadecimal value is prefixed by 0x. 0F is the binary value 00001111
// "!" coerces its operand to type Boolean (if necessary), then negates it
!value1;
//  true.
!value2;
//  false. Any non-zero number equates to true, !true is false

// "~" performs a bitwise logical NOT. Each bit in the binary value is flipped
~value3;
//  0xF0 (binary value 00001111 becomes 11110000)

© 2013 SAP AG. All rights reserved.

23
Unary Operators 4/4 (And just for fun…)
What would happen if you applied the bitwise NOT operator to a Boolean value?
// Please explain the following behaviour:
// Hint: You need to understand how the "2's compliment" binary representation works
~true;
// Bitwise NOT of Boolean true  -2
~false;
// Bitwise NOT of Boolean false  -1

© 2013 SAP AG. All rights reserved.

24
Unary Operators 4/4 (And just for fun…)
What would happen if you applied the bitwise NOT operator to a Boolean value?
// Please explain the following behaviour:
// Hint: You need to understand how the "2's compliment" binary representation works
~true;
// Bitwise NOT of Boolean true  -2
~false;
// Bitwise NOT of Boolean false  -1
// Think about the binary values used to represent TRUE and FALSE (hint  1 and 0)
// So 'true' is interpreted as numeric 1 (which as a single byte is 00000001) and 'false' is
// interpreted as numeric 0 (which as a single byte is 00000000).

© 2013 SAP AG. All rights reserved.

25
Unary Operators 4/4 (And just for fun…)
What would happen if you applied the bitwise NOT operator to a Boolean value?
// Please explain the following behaviour:
// Hint: You need to understand how the "2's compliment" binary representation works
~true;
// Bitwise NOT of Boolean true  -2
~false;
// Bitwise NOT of Boolean false  -1
// Think about the binary values used to represent TRUE and FALSE (hint  1 and 0)
// So 'true' is interpreted as numeric 1 (which as a single byte is 00000001) and 'false' is
// interpreted as numeric 0 (which as a single byte is 00000000).

// Now perform the bitwise NOT operation: so all the bits in 00000001 are flipped to give
// 11111110, and all the bits in 00000000 are flipped to give 11111111

© 2013 SAP AG. All rights reserved.

26
Unary Operators 4/4 (And just for fun…)
What would happen if you applied the bitwise NOT operator to a Boolean value?
// Please explain the following behaviour:
// Hint: You need to understand how the "2's compliment" binary representation works
~true;
// Bitwise NOT of Boolean true  -2
~false;
// Bitwise NOT of Boolean false  -1
// Think about the binary values used to represent TRUE and FALSE (hint  1 and 0)
// So 'true' is interpreted as numeric 1 (which as a single byte is 00000001) and 'false' is
// interpreted as numeric 0 (which as a single byte is 00000000).

// Now perform the bitwise NOT operation: so all the bits in 00000001 are flipped to give
// 11111110, and all the bits in 00000000 are flipped to give 11111111
// Now look at these values using the 2's complement format (where the senior bit has a
// value of -128, not +128). Therefore, 11111110 = -2 and 11111111 = -1

© 2013 SAP AG. All rights reserved.

27
Binary Operators 1/3
A binary operator is one that requires two operands; one on the left and one on the right.
Binary operators that separate their operands are also known as “infix” operators.
// The familiar arithmetic operations such as add, subtract, divide and multiply are binary
// operators
var x = 12;
var y = 3;
// No surprises
x + y;
// 
x - y;
// 
x * y;
// 
x / y;
// 

here I hope...
15
9
36
4

// Another less familiar binary operator is modulus division
x % y;
//  0. Divide x by y, return the remainder (12 / 3 = 4 remainder 0)

© 2013 SAP AG. All rights reserved.

28
Binary Operators 2/3
Binary operators to perform logical operations at the bit-level and bitwise shifting.
Bit shifting effectively multiplies or divides a value by some power of 2.
var x = 0x0F;
var y = 0xAA;
var z = 3;
// These
x & y;
x | y;
x ^ y;

// Decimal 15 or 00001111
// Decimal 170 or 10101010

operators manipulate
//  0x0A 00001010
//  0xAF 10101111
//  0xA5 10100101

y << z; //  1360
y >> z; //  0x15
y >>> z; //  0x15

© 2013 SAP AG. All rights reserved.

the individual bits of their operands
Bitwise AND
Bitwise OR
Bitwise Exclusive OR (XOR)

Shift y left by z places, zero padding on right (y * 2^z)
Shift y right by z places, preserving the sign bit
Shift y right by z places, zero padding on left

29
Binary Operators 3/3
Binary operators to perform Boolean logical operations
// These operators treat their operands as Boolean values
x && y;
// Boolean AND If x is false, the condition fails immediately without testing y
x || y;
// Boolean OR
If x is true, the condition passes immediately without testing y

As with all modern languages, the JavaScript Boolean operators AND and OR use a performance
enhancement called "early bail out".
This means that if the first operand of the AND operator evaluates to false, then the whole condition has
failed and there is no point testing the second operand, so the test bails out early.
Similarly, if the first operand of the OR operator evaluates to true, then the whole condition has passed
and there is no point testing the second operand, so the test bails out early.
© 2013 SAP AG. All rights reserved.

30
Ternary Operator: Test A Condition Without Using if
JavaScript has a single ternary operator to provide a compact way of representing a simple left/right
selection. A ternary operator requires three operands.

© 2013 SAP AG. All rights reserved.

31
Ternary Operator: Test A Condition Without Using if
JavaScript has a single ternary operator to provide a compact way of representing a simple left/right
selection. A ternary operator requires three operands.
// Doing it the long way
function catSays(animal) {
var result;
if (animal == "cat" ||
animal == "kitten" ) {
result = "Meow!";
}
else {
result "Not a cat!";
}
return result;
}

This is perfectly correct, but it is
unnecessarily verbose...
© 2013 SAP AG. All rights reserved.

32
Ternary Operator: Test A Condition Without Using if
JavaScript has a single ternary operator to provide a compact way of representing a simple left/right
selection. A ternary operator requires three operands.
// Doing it the long way
function catSays(animal) {
var result;
if (animal == "cat" ||
animal == "kitten" ) {
result = "Meow!";
}
else {
result "Not a cat!";
}

// The ternary operator allows you to write an if
// statement without needing to use the "if" keyword
function catSays(animal) {
return (animal == "cat" ||
animal == "kitten") ? "Meow!" : "Not a cat!";
}

return result;
}

This is perfectly correct, but it is
unnecessarily verbose...
© 2013 SAP AG. All rights reserved.

33
Ternary Operator: Test A Condition Without Using if
JavaScript has a single ternary operator to provide a compact way of representing a simple left/right
selection. A ternary operator requires three operands.
// Doing it the long way
function catSays(animal) {
var result;
if (animal == "cat" ||
animal == "kitten" ) {
result = "Meow!";
}
else {
result "Not a cat!";
}

// The ternary operator allows you to write an if
// statement without needing to use the "if" keyword
function catSays(animal) {
return (animal == "cat" ||
animal == "kitten") ? "Meow!" : "Not a cat!";
}

If this condition is true...

return result;
}

This is perfectly correct, but it is
unnecessarily verbose...
© 2013 SAP AG. All rights reserved.

34
Ternary Operator: Test A Condition Without Using if
JavaScript has a single ternary operator to provide a compact way of representing a simple left/right
selection. A ternary operator requires three operands.
// Doing it the long way
function catSays(animal) {
var result;
if (animal == "cat" ||
animal == "kitten" ) {
result = "Meow!";
}
else {
result "Not a cat!";
}
return result;

// The ternary operator allows you to write an if
// statement without needing to use the "if" keyword
function catSays(animal) {
return (animal == "cat" ||
animal == "kitten") ? "Meow!" : "Not a cat!";
}

Then the result is whatever
value follows the "?" character

}

This is perfectly correct, but it is
unnecessarily verbose...
© 2013 SAP AG. All rights reserved.

35
Ternary Operator: Test A Condition Without Using if
JavaScript has a single ternary operator to provide a compact way of representing a simple left/right
selection. A ternary operator requires three operands.
// Doing it the long way
function catSays(animal) {
var result;
if (animal == "cat" ||
animal == "kitten" ) {
result = "Meow!";
}
else {
result "Not a cat!";
}
return result;

// The ternary operator allows you to write an if
// statement without needing to use the "if" keyword
function catSays(animal) {
return (animal == "cat" ||
animal == "kitten") ? "Meow!" : "Not a cat!";
}

Else the result is whatever
value follows the ":" character

}

This is perfectly correct, but it is
unnecessarily verbose...
© 2013 SAP AG. All rights reserved.

36
Ternary Operator: Test A Condition Without Using if
JavaScript has a single ternary operator to provide a compact way of representing a simple left/right
selection. A ternary operator requires three operands.
// Doing it the long way
function catSays(animal) {
var result;
if (animal == "cat" ||
animal == "kitten" ) {
result = "Meow!";
}
else {
result "Not a cat!";
}
return result;
}

// The ternary operator allows you to write an if
// statement without needing to use the "if" keyword
function catSays(animal) {
return (animal == "cat" ||
animal == "kitten") ? "Meow!" : "Not a cat!";
}

The value returned
by the function
…is the outcome of
the ternary operator

This is perfectly correct, but it is
unnecessarily verbose...
© 2013 SAP AG. All rights reserved.

37
Type Coercion
Type Coercion to String: Using the Unary + Operator
“Type coercion”* is the process by which a value of one data type is transformed into a value of another data type.
This will occur automatically whenever an operator is supplied with a value that is not immediately suitable.
var value1 = "-1";
var value2 = "cat";

+value1; //  -1.
+value2; //  NaN.

Unary "+" returns the numeric representation of a string
Numeric representation of a non-numeric string is 'Not a number'

* To "coerce" someone into doing something means that you have forced them to do something they would not otherwise willingly do.
© 2013 SAP AG. All rights reserved.

39
Type Coercion to String: Using the Unary + Operator
“Type coercion” is the process by which a value of one data type is transformed into a value of another data type.
This will occur automatically whenever an operator is supplied with a value that is not immediately suitable.
var
var
var
var

value1
value2
value3
value4

=
=
=
=

"-1";
"cat";
false;
true;

+value1; //  -1.
+value2; //  NaN.

Unary "+" returns the numeric representation of a string
Numeric representation of a non-numeric string is 'Not a number'

+value3; //  numeric 0.
+value4; //  numeric 1.

Boolean false is coerced to numeric 0
Boolean true is coerced to numeric 1

The unary + operator can be used (if possible) to coerce character strings or Boolean values into
numbers.

© 2013 SAP AG. All rights reserved.

40
Type Coercion to String: Overloading the Binary + Operator
The binary plus operator can also be used for string concatenation. This is called “overloading” an
operator. Be careful though! The behaviour changes depending on the data types of the operands!
// The plus operator performs a normal arithmetic operation because both operands are numeric
1 + 2;
//  3 (No surprises here, I hope)

© 2013 SAP AG. All rights reserved.

41
Type Coercion to String: Overloading the Binary + Operator
The binary plus operator can also be used for string concatenation. This is called “overloading” an
operator. Be careful though! The behaviour changes depending on the data types of the operands!
// The plus operator performs a normal arithmetic operation because both operands are numeric
1 + 2;
//  3 (No surprises here, I hope)
// If any one of the operands passed to the binary plus operator is of type string, then the
// operator has been "overloaded" and string concatenation will take place instead of
// arithmetic addition.
1 + "2"; //  "12"
"3" + 4; //  "34"

© 2013 SAP AG. All rights reserved.

42
Type Coercion to String: Overloading the Binary + Operator
The binary plus operator can also be used for string concatenation. This is called “overloading” an
operator. Be careful though! The behaviour changes depending on the data types of the operands!
// The plus operator performs a normal arithmetic operation because both operands are numeric
1 + 2;
//  3 (No surprises here, I hope)
// If any one of the operands passed to the binary plus operator is of type string, then the
// operator has been "overloaded" and string concatenation will take place instead of
// arithmetic addition.
1 + "2"; //  "12"
"3" + 4; //  "34"
// Caution – type coercion takes place based on the data types of the operands!
1 + 2 + "3" + 4; //  "334" '1+2' is a numeric operation, so add. The rest is concatenation

© 2013 SAP AG. All rights reserved.

43
Type Coercion to Boolean: Using the Boolean NOT Operator
The Boolean NOT operator can be used to coerce a value to be treated either as true or false.
var value1 = false;
var value2 = 2;
// "!" coerces its operand to Boolean (if necessary), then negates it
!value1;
//  true.
!value2;
//  false. Any non-zero number equates to true, !true is false

© 2013 SAP AG. All rights reserved.

44
Type Coercion to Boolean: Using the Boolean NOT Operator
The Boolean NOT operator can be used to coerce a value to be treated either as true or false.
var value1 = false;
var value2 = 2;
// "!" coerces its operand to Boolean (if necessary), then negates it
!value1;
//  true.
!value2;
//  false. Any non-zero number equates to true, !true is false
// Here's a useful trick when minimising JavaScript code. The keywords "true" and "false" use
// 4 and 5 characters each. Rewriting these as !0 and !1 reduces the count to 2
!0;
//  true.
0 is coerced to Boolean false, !false is true
!1;
//  false. 1 is coerced to Boolean true, !true is false

© 2013 SAP AG. All rights reserved.

45
Type Coercion to Boolean: Truthy and Falsy 1/2
Since all JavaScript data types can be coerced to a Boolean value, this leads to the concept that all
JavaScript values are either “truthy” or “falsy”.
// Values that evaluate to Boolean true are said to be 'truthy', and those that evaluate to
// Boolean false are said to be 'falsy'.
// For example, create an object whose properties hold a value of each data type
var datatypes = {
zero:0, one:1, "null":null, "undefined":undefined, "NaN":NaN,
"function":function() {}, "true":true, "false":false,
emptyString:"", emptyObject:{}, emptyArray:[]
}

© 2013 SAP AG. All rights reserved.

46
Type Coercion to Boolean: Truthy and Falsy 1/2
Since all JavaScript data types can be coerced to a Boolean value, this leads to the concept that all
JavaScript values are either “truthy” or “falsy”.
// Values that evaluate to Boolean true are said to be 'truthy', and those that evaluate to
// Boolean false are said to be 'falsy'.
// For example, create an object whose properties hold a value of each data type
var datatypes = {
zero:0, one:1, "null":null, "undefined":undefined, "NaN":NaN,
"function":function() {}, "true":true, "false":false,
emptyString:"", emptyObject:{}, emptyArray:[]
}
// Loop around each property in the object writing the coerced Boolean value to the console
for (var i in datatypes) {
// See whether the above properties are truthy or falsy
// The "double not" (!!) is a trick that coerces any data type to its Boolean equivalent
console.log(i + " evaluates to " + !!datatypes[i]);
}

© 2013 SAP AG. All rights reserved.

47
Type Coercion to Boolean: Truthy and Falsy 2/2
The general idea is this: any value that can be thought of as “empty” will evaluate to false such as
zero or null etc. However, BE CAREFUL! Not all evaluations work the way you might expect!

As expected, an empty
string evaluates to false

© 2013 SAP AG. All rights reserved.

48
Type Coercion to Boolean: Truthy and Falsy 2/2
The general idea is this: any value that can be thought of as “empty” will evaluate to false such as
zero or null etc. However, BE CAREFUL! Not all evaluations work the way you might expect!

But empty arrays and empty
objects evaluate to true…

© 2013 SAP AG. All rights reserved.

49
Type Coercion to Boolean: Overloading the OR Operator
As a consequence of type coercion to Boolean, we can overload the logical OR operator (||) to check
whether a parameter has been passed to a function, and if not, substitute a default value.
// An overloaded OR operator is used to provide a default value if a function is not passed
// a required parameter
var person = function(fName,lName,DoB) {
this.firstName = fName || "Not specified";
this.lastName = lName || "Not specified";
this.dateOfBirth = DoB;
}

© 2013 SAP AG. All rights reserved.

50
Type Coercion to Boolean: Overloading the OR Operator
As a consequence of type coercion to Boolean, we can overload the logical OR operator (||) to check
whether a parameter has been passed to a function, and if not, substitute a default value.
// An overloaded OR operator is used to provide a default value if a function is not passed
// a required parameter
var person = function(fName,lName,DoB) {
this.firstName = fName || "Not specified";
this.lastName = lName || "Not specified";
this.dateOfBirth = DoB;
}

Here we rely on three aspects of JavaScript's behaviour:
1. Early bail out means that the second operand of the OR operator will only be evaluated if the first operand
equals (or is coerced to) false
2. If a function parameter is not supplied, the parameter value will be null
3. Type coercion causes null to evaluate to false.

© 2013 SAP AG. All rights reserved.

51
Type Coercion to Boolean: Overloading the OR Operator
As a consequence of type coercion to Boolean, we can overload the logical OR operator (||) to check
whether a parameter has been passed to a function, and if not, substitute a default value.
// An overloaded OR operator is used to provide a default value if a function is not passed
// a required parameter
var person = function(fName,lName,DoB) {
this.firstName = fName || "Not specified";
this.lastName = lName || "Not specified";
this.dateOfBirth = DoB;
}

Here we rely on three aspects of JavaScript's behaviour:
1. Early bail out means that the second operand of the OR operator will only be evaluated if the first operand
equals (or is coerced to) false
2. If a function parameter is not supplied, the parameter value will be null
3. Type coercion causes null to evaluate to false.
If either parameter fName or lName is supplied, then their non-null value will coerce to true causing OR to bail out early
and return the parameter value. However, if either of these parameters are not supplied, then their values will be null,
forcing the OR operator to return the value of its second operand – which is the default value.
© 2013 SAP AG. All rights reserved.

52
Type Coercion to Boolean: Counting Down to Zero in Loops
Here’s another example of where type coercion can be use to simplify the coding.
// Use number  Boolean type coercion to
// control a loop
var n = 5;
while (n--) {
console.log("Stop when n = 0. n is now "+n);
}

Here, we are relying on the fact that all non-zero numeric values are truthy and zero is falsy.

© 2013 SAP AG. All rights reserved.

53
Type Coercion to Boolean: Counting Down to Zero in Loops
Here’s another example of where type coercion can be use to simplify the coding.
// Use number  Boolean type coercion to
// control a loop
var n = 5;
while (n--) {
console.log("Stop when n = 0. n is now "+n);
}

Here, we are relying on the fact that all non-zero numeric values are truthy and zero is falsy.
The decrement operator -- is specifically used in the postfix position. This means that the value of n is
tested before being decremented.

© 2013 SAP AG. All rights reserved.

54
Type Coercion to Boolean: Counting Down to Zero in Loops
Here’s another example of where type coercion can be use to simplify the coding.
// Use number  Boolean type coercion to
// control a loop
var n = 5;
while (n--) {
console.log("Stop when n = 0. n is now "+n);
}

Here, we are relying on the fact that all non-zero numeric values are truthy and zero is falsy.
The decrement operator -- is specifically used in the postfix position. This means that the value of n is
tested before being decremented.
We now enter the body of the while loop with the decremented value of n – hence when the value of n is
first written to the console it is 4, not 5. All non-zero values of n are truthy, so the loop continues.

© 2013 SAP AG. All rights reserved.

55
Type Coercion to Boolean: Counting Down to Zero in Loops
Here’s another example of where type coercion can be use to simplify the coding.
// Use number  Boolean type coercion to
// control a loop
var n = 5;
while (n--) {
console.log("Stop when n = 0. n is now "+n);
}

Here, we are relying on the fact that all non-zero numeric values are truthy and zero is falsy.
The decrement operator -- is specifically used in the postfix position. This means that the value of n is
tested before being decremented.
We now enter the body of the while loop with the decremented value of n – hence when the value of n is
first written to the console it is 4, not 5. All non-zero values of n are truthy, so the loop continues.
The last time around the loop, n now equals 0. 0 is falsy, so the condition fails and the loop terminates.
© 2013 SAP AG. All rights reserved.

56
Type Coercion: Now Things Start To Get A Little Strange…
Type coercion can cause certain data types to be treated in a way that is not immediately obvious
// Type coercion
1 + [];
// 
1 + {};
// 
[] + {};
// 

to string by overloading the plus operator
"1"
Empty array is coerced to empty string, concatenate strings
"1{object Object}" Coerce empty object to string "{object Object}", concatenate
"{object Object}" [] coerced to "", {} coerced to "{object Object}", concatenate

// Type coercion of Boolean to numeric
1 + true; //  2
Boolean true is coerced to numeric 1, 1+1=2
1 + false; //  1
Boolean false is coerced to numeric 0, 1+0=1

© 2013 SAP AG. All rights reserved.

57
Type Coercion: OK, That's Just Weird…
And as if that were not strange enough, here are some even stranger edge cases - and as is written at
the edges of all good Medieval maps: Here be dragons
// Type coercion
{} + [];
//
{} + 1;
//
({}) + 1;
//
!+[];
!+[]+!![];

can produce some bizarre results!
 0
 1
 "{object Object}1"

//  true
//  2

!+[]+[];
//  "true"
!+[]+!![]+[]; //  "2"
[][[]];
[][[]]+[];

//  undefined
//  "undefined"

This strange behaviour is the basis of the Github obfuscation project called Hieroglyphy
© 2013 SAP AG. All rights reserved.

58
The typeof Operator
Type Determination (Another Unary Operator)
The typeof operator allows you to discover the data type of a variable’s value – well mostly…
// Declare some variables of various data types
var aNumber
= 123;
var aString
= "Nothing to see here, move along";
var anObject
= { aProperty : 0 };
var aFunction = function() { };
var notANumber = NaN;
var anArray
= [1,2,3,4,5];
var nullValue = null;
// What data types do we have here?
typeof aNumber;
//  'number'
typeof aString;
//  'string'
typeof anObject;
//  'object'
typeof aFunction;
//  'function'

© 2013 SAP AG. All rights reserved.

60
Type Determination (Another Unary Operator)
The typeof operator allows you to discover the data type of a variable’s value – well mostly…
// Declare some variables of various data types
var aNumber
= 123;
var aString
= "Nothing to see here, move along";
var anObject
= { aProperty : 0 };
var aFunction = function() { };
var notANumber = NaN;
var anArray
= [1,2,3,4,5];
var nullValue = null;
// What data types do we have here?
typeof aNumber;
//  'number'
typeof aString;
//  'string'
typeof anObject;
//  'object'
typeof aFunction;
//  'function'
typeof notANumber;
//  'number' This isn't as weird as you might think (See ECMAScript spec)

© 2013 SAP AG. All rights reserved.

61
Type Determination (Another Unary Operator)
The typeof operator allows you to discover the data type of a variable’s value – well mostly…
// Declare some variables of various data types
var aNumber
= 123;
var aString
= "Nothing to see here, move along";
var anObject
= { aProperty : 0 };
var aFunction = function() { };
var notANumber = NaN;
var anArray
= [1,2,3,4,5];
var nullValue = null;
// What data types do we have here?
typeof aNumber;
//  'number'
typeof aString;
//  'string'
typeof anObject;
//  'object'
typeof aFunction;
//  'function'
typeof notANumber;
//  'number' This isn't as weird as you might think (See ECMAScript spec)

// So far, so good – the typeof operator is being well-behaved...
typeof anArray;
//  'object'
Hmmm, this answer isn't wrong, but then neither is it helpful

© 2013 SAP AG. All rights reserved.

62
Type Determination (Another Unary Operator)
The typeof operator allows you to discover the data type of a variable’s value – well mostly…
// Declare some variables of various data types
var aNumber
= 123;
var aString
= "Nothing to see here, move along";
var anObject
= { aProperty : 0 };
var aFunction = function() { };
var notANumber = NaN;
var anArray
= [1,2,3,4,5];
var nullValue = null;
// What data types do we have here?
typeof aNumber;
//  'number'
typeof aString;
//  'string'
typeof anObject;
//  'object'
typeof aFunction;
//  'function'
typeof notANumber;
//  'number' This isn't as weird as you might think (See ECMAScript spec)

// So far, so good – the typeof operator is being well-behaved...
typeof anArray;
//  'object'
Hmmm, this answer isn't wrong, but then neither is it helpful
typeof nullValue;
//  'object'
Sorry, but this is just wrong!
© 2013 SAP AG. All rights reserved.

63
Fixing the typeof operator 1/3
typeof is not entirely wrong for returning 'object' when passed an array, because an array is
simply an object with array-like properties. However, whilst accurate, this answer is not helpful.
// Create our own isArray() function
// Use the toString() method belonging to JavaScript's standard Object prototype and check to see
// whether the object in question has a string representation of '[object Array]'.
// If it does, then we can be sure that the object really is an array.
var isArray = function(obj) {
return Object.prototype.toString.apply(obj) === '[object Array]';
};

© 2013 SAP AG. All rights reserved.

64
Fixing the typeof operator 2/3
What is much more annoying is that the typeof operator cannot tell the difference between an object
and a null value. So some improvement is needed here.
// This improvement works by exploiting the fact that all objects are truthy, but null is falsy.
// The first expression in the condition coerces myObj to Boolean; which, if it is null, will be
// false. Because this is an AND condition, the whole condition fails if the first operand is false
if (myObj && typeof myObj === 'object') {
// Yup, this is an object and not null value
};

© 2013 SAP AG. All rights reserved.

65
Fixing the typeof operator 3/3
Rather than having to implement these fixes yourself, many of the widely used JavaScript frameworks
provide their own replacement function for the typeof operator. For instance, in jQuery:
var anArray
= [1,2,3,4,5];
var nullValue = null;
// jQuery provides a robust fix for JavaScript's only-sometimes-helpful typeof operator
jQuery.type(anArray);
//  'array'
jQuery.type(nullValue);
//  'null'
// Or simply
jQuery.isArray(anArray);

© 2013 SAP AG. All rights reserved.

//  true

66
Using Operators
Operators: Basic Assignment
Any value can be assigned to any variable using the assignment operator "="
var char1 = "a";
var char2 = "b";

// The value "a" is assigned to the local variable char1
// The value "b" is assigned to the local variable char2

// An object containing the single property "propertyName" is assigned to the variable myObj
var myObj = {
propertyName: "Some value"
};
// A regular expression is assigned to the variable parseURL
var parseURL =
/^(?:([A-Za-z]+):)?(/{0,3})([0-9.-A-Za-z]+)(?::(d+))?(?:/([^?#]*))?(?:?([^#]*))?(?:#(.*))?$/;

© 2013 SAP AG. All rights reserved.

68
Operators: Shortcut Assignments
JavaScript has various shortcut operators designed to make operations more compact.
x
x
x
x

+=
-=
*=
/=

y;
y;
y;
y;

//
//
//
//

Add y to
Subtract
Multiply
Divide x

x and store the result in x:
y from x and store the result in x:
x by y and store the result in x:
by y and store the result in x:

x
x
x
x

=
=
=
=

x %= y;

// Remainder of x divided by y is stored in x:

x <<= y;
x >>= y;
x >>>= y;

+
*
/

y
y
y
y

// Bitwise left shift:
x = x << y
// Bitwise right shift (preserve sign): x = x >> y
// Bitwise right shift (ignore sign):
x = x >>> y

x &= y;
x |= y;
x ^= y;

x
x
x
x

// Bitwise AND: x = x & y
// Bitwise OR: x = x | y
// Bitwise XOR: x = x ^ y

© 2013 SAP AG. All rights reserved.

x = x % y

69
Operators: Basic Comparison
Any two values can be compared:
//
//
//
//
//

>
>=
<
<=
!=

Greater than
Greater than or equal to
Less than
Less than or equal to
Not equal to

3.14 <= 2.717;
"b" > "a";

//  False
//  True

© 2013 SAP AG. All rights reserved.

Because "b" has a larger ASCII value than "a"

70
Operators: Don't Confuse Assignment and Comparison
Do not confuse the assignment operator with the comparison operator!
var char1 = "a";
var char2 = "b";

// Declare a variable called 'char1' and assign to it the value "a"
// Declare a variable called 'char2' and assign to it the value "b"

// Beginner error...
if (char1 = char2) {
// OOPS!
// The above condition actually evaluates to true because:
// 1) The value of char2 is assigned to char1, so char1 now equals "b"
// 2) Since "b" is a non-empty string, it is truthy, so the value of char1 is coerced to true
// 3) Therefore the condition always passes
}

© 2013 SAP AG. All rights reserved.

71
Operators: Comparison With Type Coercion: ==
Any test for (in)equality must first check whether the data types of the operands are the same.
If they are not, then type coercion is performed:
// "=="
// "!="

If data types are not equal, first perform type coercion, then test for equality
If data types are not equal, first perform type coercion, then test for inequality

"1" == 1;
"2" != 1 + 2;

//  True
//  True

Numeric 1 is converted to string "1". Strings are equal
Perform addition  1 + 2 = 3, convert result to string "3". Strings are not equal

2 == "1" + "1"; // False - Convert numeric 2 to string "2", concatenate "1" + "1"  "11". Strings are not equal
// Comparison operators
// ">" Greater than
">=" Greater than or equal to
// "<" Less than
"<=" less than or equal to
"a" > "b";
"4" < 5;

//  False
//  True

© 2013 SAP AG. All rights reserved.

"a" comes before "b" in the ASCII collation sequence
Convert numeric 5 to string "5", "4" comes before "5" in the ASCII collation sequence

72
Operators: Comparison Without Type Coercion: ===
If your comparison is required to check the equality not only of the values, but also the data types, then
you must use a different comparison operator:
// "==="
// "!=="

Test for exact equality. First test data types for equality, then test values for equality
Test for inequality.
First test data types for equality, then test values for inequality

"1" === 1;

//  False

1 + 1 === "2";
//  False
1 + 1 === parseInt("2"); //  True

Fails immediately because string and number are different data types
1+1 = numeric 2. Number and string do not match
1+1 = numeric 2. parseInt("2")  numeric 2. Both data type & value are equal

// Be careful with the equality operators and type coercion!
1 + 1 !== "2";
//  True
Because number and string are different data types
1 + 1 != "2";
//  False Because number is coerced to string. Strings are equal

© 2013 SAP AG. All rights reserved.

73
Operators: Invocation
Everything in JavaScript is an object – even functions! This means that functions can be treated either
as executable units of code, or as data objects just like a string or a date.
// Define an anonymous function object and store it in a variable called 'person'
var person = function() {
var firstName = "Harry";
var lastName = "Hawk";
var dateOfBirth = "03 Aug 1976";
return firstName + " " + lastName + " was born on " + dateOfBirth;
}

© 2013 SAP AG. All rights reserved.

74
Operators: Invocation
Everything in JavaScript is an object – even functions! This means that functions can be treated either
as executable units of code, or as data objects just like a string or a date.
// Define an anonymous function object and store it in a variable called 'person'
var person = function() {
var firstName = "Harry";
var lastName = "Hawk";
var dateOfBirth = "03 Aug 1976";
return firstName + " " + lastName + " was born on " + dateOfBirth;
}

We can distinguish between a “function as an executable unit of code ” and a “function as a data object” by the
use of the invocation operator (). This operator can take zero or more parameters inside the parentheses.

© 2013 SAP AG. All rights reserved.

75
Operators: Invocation
Everything in JavaScript is an object – even functions! This means that functions can be treated either
as executable units of code, or as data objects just like a string or a date.
// Define an anonymous function object and store it in a variable called 'person'
var person = function() {
var firstName = "Harry";
var lastName = "Hawk";
var dateOfBirth = "03 Aug 1976";
return firstName + " " + lastName + " was born on " + dateOfBirth;
}
person;

//  function()

This is just a reference to the object called person that happens to be a function

We can distinguish between a “function as an executable unit of code ” and a “function as a data object” by the
use of the invocation operator (). This operator can take zero or more parameters inside the parentheses.
Without the invocation operator, a function reference is simply that – a reference to an object that happens to
have an executable part.

© 2013 SAP AG. All rights reserved.

76
Operators: Invocation
Everything in JavaScript is an object – even functions! This means that functions can be treated either
as executable units of code, or as data objects just like a string or a date.
// Define an anonymous function object and store it in a variable called 'person'
var person = function() {
var firstName = "Harry";
var lastName = "Hawk";
var dateOfBirth = "03 Aug 1976";
return firstName + " " + lastName + " was born on " + dateOfBirth;
}
person;
person();

//  function() This is just a reference to the object called person that happens to be a function
//  "Harry Hawk was born on 03 Aug 1976"
Now the function is invoked

We can distinguish between a “function as an executable unit of code ” and a “function as a data object” by the
use of the invocation operator (). This operator can take zero or more parameters inside the parentheses.
Without the invocation operator, a function reference is simply that – a reference to an object that happens to
have an executable part.
Conversely, if the invocation operator is used, the function is treated as an executable unit of code and invoked.
© 2013 SAP AG. All rights reserved.

77
Declarations & JavaScript Objects
Declarations: Variables and Properties
JavaScript distinguishes between values stored as a variables and values stored as properties.
Both properties and variables are named values, but the scope of their storage differs:

© 2013 SAP AG. All rights reserved.

79
Declarations: Variables and Properties
JavaScript distinguishes between values stored as a variables and values stored as properties.
Both properties and variables are named values, but the scope of their storage differs:



A property is a named value that is always stored as the member of an object
foobar = "Phluff 'n' stuff";
A property is created simply by assigning a value to name. If you do not specify to which object the
property belongs (as in the above example), then that property will always belong to the Global
Object.

© 2013 SAP AG. All rights reserved.

80
Declarations: Variables and Properties
JavaScript distinguishes between values stored as a variables and values stored as properties.
Both properties and variables are named values, but the scope of their storage differs:



A property is a named value that is always stored as the member of an object
foobar = "Phluff 'n' stuff";
A property is created simply by assigning a value to name. If you do not specify to which object the
property belongs (as in the above example), then that property will always belong to the Global
Object.



A variable is a named value stored within an execution context
var barfoo = "Chicken soup";
A variable is created by use of the var keyword in front of the assignment.
More details will be given later about exactly what an “execution context” is.

© 2013 SAP AG. All rights reserved.

81
Declarations: Objects
In JavaScript, everything is either an object (even functions) or the property of an object.
An ‘object’ is simply an unordered collection of zero or more name:value pairs.

© 2013 SAP AG. All rights reserved.

82
Declarations: Objects
In JavaScript, everything is either an object (even functions) or the property of an object.
An ‘object’ is simply an unordered collection of zero or more name:value pairs.
The simplest way to create an object is
first to define an empty object, then
assign it some arbitrary property values:
// Create an empty object
var person1 = {};
person1.firstName = "Harry";
person1.lastName = "Hawk";
person1.hobbies
= ["swimming","cycling"];
person1.listHobbies = function() {
return this.hobbies.join(" ");
}

© 2013 SAP AG. All rights reserved.

83
Declarations: Objects
In JavaScript, everything is either an object (even functions) or the property of an object.
An ‘object’ is simply an unordered collection of zero or more name:value pairs.
The simplest way to create an object is
first to define an empty object, then
assign it some arbitrary property values:
Alternatively, you could use the array syntax:
// Create an empty object
var person1 = {};

// Create an empty object
var person2 = {};

person1.firstName = "Harry";
person1.lastName = "Hawk";
person1.hobbies
= ["swimming","cycling"];

person2["firstName"] = "Harry";
person2["Last-Name"] = "Hawk";
person2["hobbies"]
= ["swimming","cycling"];

person1.listHobbies = function() {
return this.hobbies.join(" ");
}

person2["listHobbies"] = function() {
return this.hobbies.join(" ");
}

© 2013 SAP AG. All rights reserved.

84
Declarations: Objects
In JavaScript, everything is either an object (even functions) or the property of an object.
An ‘object’ is simply an unordered collection of zero or more name:value pairs.
The simplest way to create an object is
first to define an empty object, then
assign it some arbitrary property values:
Alternatively, you could use the array syntax:
// Create an empty object
var person1 = {};

// Create an empty object
var person2 = {};

person1.firstName = "Harry";
person1.lastName = "Hawk";
person1.hobbies
= ["swimming","cycling"];

person2["firstName"] = "Harry";
person2["Last-Name"] = "Hawk";
person2["hobbies"]
= ["swimming","cycling"];

person1.listHobbies = function() {
return this.hobbies.join(" ");
}

person2["listHobbies"] = function() {
return this.hobbies.join(" ");
}

The array syntax must be used either if you want to create an object property containing a character
not permitted in a variable name, or if the property name is a reserved word.
© 2013 SAP AG. All rights reserved.

85
Two Ways To Access Object Properties
The properties of a JavaScript object are accessed by specifying the object name and then using
either the refinement operator “.” or the array element syntax. All object properties are public!
// The refinement operator: place a dot "." between the object name and the property name
person1.firstName;
//  "Harry"
person1.hobbies[1];
//  "cycling"

© 2013 SAP AG. All rights reserved.

86
Two Ways To Access Object Properties
The properties of a JavaScript object are accessed by specifying the object name and then using
either the refinement operator “.” or the array element syntax. All object properties are public!
// The refinement operator: place a dot "." between the object name and the property name
person1.firstName;
//  "Harry"
person1.hobbies[1];
//  "cycling"
// The refinement operator is useful if the property name is both known at design time and
// does not contain any illegal characters such as "-" or ";". However, if either of these
// conditions are not met, then object properties can be accessed as array elements.
person2["Last-Name"];
//  "Hawk"
person2["hobbies"][0];
//  "swimming"

© 2013 SAP AG. All rights reserved.

87
Two Ways To Access Object Properties
The properties of a JavaScript object are accessed by specifying the object name and then using
either the refinement operator “.” or the array element syntax. All object properties are public!
// The refinement operator: place a dot "." between the object name and the property name
person1.firstName;
//  "Harry"
person1.hobbies[1];
//  "cycling"
// The refinement operator is useful if the property name is both known at design time and
// does not contain any illegal characters such as "-" or ";". However, if either of these
// conditions are not met, then object properties can be accessed as array elements.
person2["Last-Name"];
//  "Hawk"
person2["hobbies"][0];
//  "swimming"

// Both forms of property access can be chained together
person1.propertyObject.someProperty;
person2["propertyObject"]["someProperty"];

© 2013 SAP AG. All rights reserved.

88
Two Ways To Access Object Properties
The properties of a JavaScript object are accessed by specifying the object name and then using
either the refinement operator “.” or the array element syntax. All object properties are public!
// The refinement operator: place a dot "." between the object name and the property name
person1.firstName;
//  "Harry"
person1.hobbies[1];
//  "cycling"
// The refinement operator is useful if the property name is both known at design time and
// does not contain any illegal characters such as "-" or ";". However, if either of these
// conditions are not met, then object properties can be accessed as array elements.
person2["Last-Name"];
//  "Hawk"
person2["hobbies"][0];
//  "swimming"

// Both forms of property access can be chained together
person1.propertyObject.someProperty;
person2["propertyObject"]["someProperty"];
// Any object property that is of type 'function' is known as a method and can be invoked
person1.listHobbies();
//  "swimming cycling"

© 2013 SAP AG. All rights reserved.

89
Deleting Object Properties
The properties of a JavaScript object can be deleted using the delete keyword.
// Property deletion
var aGlobalVariable = "I'm a global variable"; // Global variable, but not a property of the global object
aGlobalProperty
= "I'm a global property"; // A property belonging to the global object
delete aGlobalVariable;
delete aGlobalProperty;

//  false. Delete can only operate on properties, not variables
//  true. The property is deleted because it belongs to the global object

aGlobalVariable;
aGlobalProperty;

//  "I'm a global variable"
//  undefined

© 2013 SAP AG. All rights reserved.

90
JavaScript Object Notation (JSON)
The syntax for creating a JavaScript object directly in your program is the same syntax that is used for
serialising a JavaScript object as a text string:
// Create an inline JavaScript object
var person = {
firstName : "Harry",
lastName : "Hawk",
dateOfBirth : "1976 Aug 03"
}

© 2013 SAP AG. All rights reserved.

91
JavaScript Object Notation (JSON)
The syntax for creating a JavaScript object directly in your program is the same syntax that is used for
serialising a JavaScript object as a text string:
// Create an inline JavaScript object
var person = {
firstName : "Harry",
lastName : "Hawk",
dateOfBirth : "1976 Aug 03"
}

© 2013 SAP AG. All rights reserved.

// The same object serialised in JSON
{ firstName : "Harry",
lastName : "Hawk",
dateOfBirth : "1976 Aug 03" }

92
JavaScript Object Notation (JSON)
The syntax for creating a JavaScript object directly in your program is the same syntax that is used for
serialising a JavaScript object as a text string:
// Create an inline JavaScript object
var person = {
firstName : "Harry",
lastName : "Hawk",
dateOfBirth : "1976 Aug 03"
}

// The same object serialised in JSON
{ firstName : "Harry",
lastName : "Hawk",
dateOfBirth : "1976 Aug 03" }

The convenience of this symmetry makes JSON the ideal output format for data from a web server.
Once assigned to a JavaScript variable, a JSON string is parsed automatically making the internal
structure of the object accessible to the rest of the program.
// Replacing the inline object definition with a function call that obtains a JSON response from a web
// server does not alter the above functionality unchanged
var person = getJSONFromBackend(someKeyValue);

© 2013 SAP AG. All rights reserved.

93
Default Object Methods and Properties
When a simple JavaScript object is created, the inline definition lists 3 properties of our own design:
firstName, lastName and dateOfBirth.
// Create an inline JavaScript object
var person = {
firstName : "Harry",
lastName : "Hawk",
dateOfBirth : "1976 Aug 03"
}

© 2013 SAP AG. All rights reserved.

94
Default Object Methods and Properties
When a simple JavaScript object is created, the inline definition lists 3 properties of our own design:
firstName, lastName and dateOfBirth.
// Create an inline JavaScript object
var person = {
firstName : "Harry",
lastName : "Hawk",
dateOfBirth : "1976 Aug 03"
}

person
Properties
 firstName
 lastName
 dateOfBirth
 __proto__

However, the person object also has a default property called __proto__ that cannot be deleted.
The __proto__ property is not actually part of the ECMAScript specification, so in that sense, it is a
non-standard property. However, all modern browsers (except Internet Explorer) implement this
property.
More details will be given about this property later.
© 2013 SAP AG. All rights reserved.

95
Default Object Methods and Properties 1/2
Using the NodeJS command prompt, a simple inline JavaScript object is created containing 3
properties: firstName, lastName and dateOfBirth.
> var person = {
...
firstName : "Harry",
...
lastName : "Hawk",
...
dateOfBirth : "1976 Aug 03"
... }
undefined
>

© 2013 SAP AG. All rights reserved.

96
Default Object Methods and Properties 2/2
If we type the object name followed by a dot character and then press tab, we are shown a list of all
the properties available in this object. Notice that there are several default methods available.
> var person = {
...
firstName : "Harry",
...
lastName : "Hawk",
...
dateOfBirth : "1976 Aug 03"
... }
undefined
> person.
person.__defineGetter__
person.__defineSetter__
person.hasOwnProperty
person.isPrototypeOf
person.valueOf
person.dateOfBirth

© 2013 SAP AG. All rights reserved.

person.firstName

person.__lookupGetter__
person.propertyIsEnumerable

person.__lookupSetter__
person.toLocaleString

person.constructor
person.toString

person.lastName

97
Default Object Methods and Properties 2/2
If we type the object name followed by a dot character and then press tab, we are shown a list of all
the properties available in this object. Notice that there are several default methods available.
> var person = {
...
firstName : "Harry",
...
lastName : "Hawk",
...
dateOfBirth : "1976 Aug 03"
... }
undefined
> person.
person.__defineGetter__
person.__defineSetter__
person.hasOwnProperty
person.isPrototypeOf
person.valueOf
person.dateOfBirth

person.firstName

person.__lookupGetter__
person.propertyIsEnumerable

person.__lookupSetter__
person.toLocaleString

person.constructor
person.toString

person.lastName

Methods inherited from the
JavaScript object called Object

© 2013 SAP AG. All rights reserved.

98
Default Object Methods and Properties 2/2
If we type the object name followed by a dot character and then press tab, we are shown a list of all
the properties available in this object. Notice that there are several default methods available.
> var person = {
...
firstName : "Harry",
...
lastName : "Hawk",
...
dateOfBirth : "1976 Aug 03"
... }
undefined
> person.__proto__.
person.__proto__.__defineGetter__
person.__proto__.__lookupSetter__
person.__proto__.isPrototypeOf
person.__proto__.toString

person.__proto__.__defineSetter__
person.__proto__.constructor
person.__proto__.propertyIsEnumerable
person.__proto__.valueOf

person.__proto__.__lookupGetter__
person.__proto__.hasOwnProperty
person.__proto__.toLocaleString

Even though the __proto__ property is not explicitly listed, if you enter its name followed by a dot and
then press tab, you will see the methods and properties inherited from the object acting as person's
prototype.
More about prototypes later…
© 2013 SAP AG. All rights reserved.

99
JavaScript Arrays
Arrays 1/4
Remember! Everything in JavaScript is an object; therefore, a JavaScript array is simply a regular
object that has extra array-like functionality built in.
// Create an array variable.
var listOfThings = ["ball","cup","pen","car"];
// Access the elements in the
listOfThings[1];
// 
listOfThings.length;
// 
listOfThings[4];
// 

© 2013 SAP AG. All rights reserved.

array
"cup"
4
undefined

All array indices are zero based, not one based

101
Arrays 1/4
Remember! Everything in JavaScript is an object; therefore, a JavaScript array is simply a regular
object that has extra array-like functionality built in.
// Create an array variable.
var listOfThings = ["ball","cup","pen","car"];
// Access the elements in the
listOfThings[1];
// 
listOfThings.length;
// 
listOfThings[4];
// 

array
"cup"
4
undefined

All array indices are zero based, not one based

// JavaScript arrays are not typesafe, their elements can be of a mixture of datatypes
var differentThings = ["Chicken Soup", 12.34, null, ["a","b","c","d"],
undefined, NaN, {prop: 123}, true, false];

© 2013 SAP AG. All rights reserved.

102
Arrays 1/4
Remember! Everything in JavaScript is an object; therefore, a JavaScript array is simply a regular
object that has extra array-like functionality built in.
// Create an array variable.
var listOfThings = ["ball","cup","pen","car"];
// Access the elements in the
listOfThings[1];
// 
listOfThings.length;
// 
listOfThings[4];
// 

array
"cup"
4
undefined

All array indices are zero based, not one based

// JavaScript arrays are not typesafe, their elements can be of a mixture of datatypes
var differentThings = ["Chicken Soup", 12.34, null, ["a","b","c","d"],
undefined, NaN, {prop: 123}, true, false];

IMPORTANT
When you declare an Array, you are creating a regular JavaScript object that contains an extra set
methods such as .push() and .pop(), and a .length property.
These methods give this JavaScript object array-like behaviour.
© 2013 SAP AG. All rights reserved.

103
Arrays 2/4
Using the NodeJS command prompt, a new array is created called myArray. As before, type the
object name followed by a dot and press the tab key to display the possible methods and properties…
> var listOfThings = ["ball","cup","pen","car"];
undefined
> listOfThings.
listOfThings.__defineGetter__
listOfThings.__defineSetter__
listOfThings.constructor
listOfThings.hasOwnProperty
listOfThings.toLocaleString
listOfThings.toString

listOfThings.__lookupGetter__
listOfThings.isPrototypeOf
listOfThings.valueOf

listOfThings.__lookupSetter__
listOfThings.propertyIsEnumerable

listOfThings.concat
listOfThings.indexOf
listOfThings.map
listOfThings.reduceRight
listOfThings.some

listOfThings.filter
listOfThings.lastIndexOf
listOfThings.push
listOfThings.shift
listOfThings.splice

listOfThings.forEach
listOfThings.length
listOfThings.reduce
listOfThings.slice
listOfThings.unshift

listOfThings.0

© 2013 SAP AG. All rights reserved.

listOfThings.every
listOfThings.join
listOfThings.pop
listOfThings.reverse
listOfThings.sort

listOfThings.1
listOfThings.2
Methods inherited from the standard
JavaScript object called Object

listOfThings.3

104
Arrays 2/4
Using the NodeJS command prompt, a new array is created called myArray. As before, type the
object name followed by a dot and press the tab key to display the possible methods and properties…
> var listOfThings = ["ball","cup","pen","car"];
undefined
> listOfThings.
listOfThings.__defineGetter__
listOfThings.__defineSetter__
listOfThings.constructor
listOfThings.hasOwnProperty
listOfThings.toLocaleString
listOfThings.toString

listOfThings.__lookupGetter__
listOfThings.isPrototypeOf
listOfThings.valueOf

listOfThings.__lookupSetter__
listOfThings.propertyIsEnumerable

listOfThings.concat
listOfThings.indexOf
listOfThings.map
listOfThings.reduceRight
listOfThings.some

listOfThings.every
listOfThings.join
listOfThings.pop
listOfThings.reverse
listOfThings.sort

listOfThings.filter
listOfThings.lastIndexOf
listOfThings.push
listOfThings.shift
listOfThings.splice

listOfThings.forEach
listOfThings.length
listOfThings.reduce
listOfThings.slice
listOfThings.unshift

listOfThings.0

listOfThings.1

listOfThings.2

listOfThings.3

Extra built-in methods that give
this object array-like capabilities

© 2013 SAP AG. All rights reserved.

105
Arrays 2/4
Using the NodeJS command prompt, a new array is created called myArray. As before, type the
object name followed by a dot and press the tab key to display the possible methods and properties…
> var listOfThings = ["ball","cup","pen","car"];
undefined
> listOfThings.
listOfThings.__defineGetter__
listOfThings.__defineSetter__
listOfThings.constructor
listOfThings.hasOwnProperty
listOfThings.toLocaleString
listOfThings.toString

listOfThings.__lookupGetter__
listOfThings.isPrototypeOf
listOfThings.valueOf

listOfThings.__lookupSetter__
listOfThings.propertyIsEnumerable

listOfThings.concat
listOfThings.indexOf
listOfThings.map
listOfThings.reduceRight
listOfThings.some

listOfThings.every
listOfThings.join
listOfThings.pop
listOfThings.reverse
listOfThings.sort

listOfThings.filter
listOfThings.lastIndexOf
listOfThings.push
listOfThings.shift
listOfThings.splice

listOfThings.forEach
listOfThings.length
listOfThings.reduce
listOfThings.slice
listOfThings.unshift

listOfThings.0

listOfThings.1

listOfThings.2

listOfThings.3

Automatically created object properties.
Each array element is created as a property whose name
is the text string of the corresponding index number

© 2013 SAP AG. All rights reserved.

106
Arrays 3/4
All array elements are treated as a special type of object property. JavaScript uses the string
representation of the numeric index as the property name.
// Create an array variable.
var listOfThings = ["ball","cup","pen","car"];
// Array elements can be accessed either by their numeric index, or by the string
// representation of the numeric index.
listOfThings[1];
//  "cup"

© 2013 SAP AG. All rights reserved.

107
Arrays 3/4
All array elements are treated as a special type of object property. JavaScript uses the string
representation of the numeric index as the property name.
// Create an array variable.
var listOfThings = ["ball","cup","pen","car"];
// Array elements can be accessed either by their numeric index, or by the string
// representation of the numeric index.
listOfThings[1];
//  "cup"
listOfThings["1"];
//  "cup"

© 2013 SAP AG. All rights reserved.

108
Arrays 3/4
All array elements are treated as a special type of object property. JavaScript uses the string
representation of the numeric index as the property name.
// Create an array variable.
var listOfThings = ["ball","cup","pen","car"];
// Array elements can be accessed either by their numeric index, or by the string
// representation of the numeric index.
listOfThings[1];
//  "cup"
listOfThings["1"];
//  "cup"
// Create a new element using a numeric string as the index
listOfThings["4"] = "tree";

© 2013 SAP AG. All rights reserved.

109
Arrays 3/4
All array elements are treated as a special type of object property. JavaScript uses the string
representation of the numeric index as the property name.
// Create an array variable.
var listOfThings = ["ball","cup","pen","car"];
// Array elements can be accessed either by their numeric index, or by the string
// representation of the numeric index.
listOfThings[1];
//  "cup"
listOfThings["1"];
//  "cup"
// Create a new element using a numeric string as the index
listOfThings["4"] = "tree";
listOfThings[4];
//  "tree"
listOfThings;
//  ["ball","cup","pen","car","tree"]

© 2013 SAP AG. All rights reserved.

110
Arrays 3/4
All array elements are treated as a special type of object property. JavaScript uses the string
representation of the numeric index as the property name.
// Create an array variable.
var listOfThings = ["ball","cup","pen","car"];
// Array elements can be accessed either by their numeric index, or by the string
// representation of the numeric index.
listOfThings[1];
//  "cup"
listOfThings["1"];
//  "cup"
// Create a new element using a numeric string as the index
listOfThings["4"] = "tree";
listOfThings[4];
//  "tree"
listOfThings;
//  ["ball","cup","pen","car","tree"]
// Alternatively, a new element can be appended to the array using the push() method
listOfThings.push("dog");
listOfThings;
//  ["ball","cup","pen","car","tree","dog"]

© 2013 SAP AG. All rights reserved.

111
Arrays 4/4
Since JavaScript arrays are just objects with array-like behaviour, you can add new properties to the
array object using any names you like.
// Create an array variable.
var listOfThings = ["ball","cup","pen","car"];
listOfThings.length;
//  4
// Create an array element using a non-numeric property name
listOfThings["first"] = "Some value";
listOfThings["first"]; //  "Some value"

© 2013 SAP AG. All rights reserved.

112
Arrays 4/4
Since JavaScript arrays are just objects with array-like behaviour, you can add new properties to the
array object using any names you like.
// Create an array variable.
var listOfThings = ["ball","cup","pen","car"];
listOfThings.length;
//  4
// Create an array element using a non-numeric property name
listOfThings["first"] = "Some value";
listOfThings["first"]; //  "Some value"

listOfThings.length;
listOfThings;

© 2013 SAP AG. All rights reserved.

//  4 Uh?! Didn't we just add a new element to the array?
//  ["ball","cup","pen","car"] No, we added an object property,
//
not an array element...

113
Arrays 4/4
Since JavaScript arrays are just objects with array-like behaviour, you can add new properties to the
array object using any names you like.
// Create an array variable.
var listOfThings = ["ball","cup","pen","car"];
listOfThings.length;
//  4
// Create an array element using a non-numeric property name
listOfThings["first"] = "Some value";
listOfThings["first"]; //  "Some value"

listOfThings.length;
listOfThings;

//  4 Uh?! Didn't we just add a new element to the array?
//  ["ball","cup","pen","car"] No, we added an object property,
//
not an array element...

Be careful!
If the property name cannot be interpreted as an integer, then that new property will not be treated as
an “element” of the array! It will simply be an object property with no special relevance to the set of
elements making up the “array”.
© 2013 SAP AG. All rights reserved.

114
Array .length Property (and What it Doesn’t Mean!)
The value of an array's .length property doesn't always return the value you might expect.
It does not necessarily represent the number of elements that actually exist in the array!
// Create an empty array
var someArray = [];
someArray.length; //  0. Everything is behaving as expected...
// Add a new element
someArray[4] = "Surprise!";

© 2013 SAP AG. All rights reserved.

115
Array .length Property (and What it Doesn’t Mean!)
The value of an array's .length property doesn't always return the value you might expect.
It does not necessarily represent the number of elements that actually exist in the array!
// Create an empty array
var someArray = [];
someArray.length; //  0. Everything is behaving as expected...
// Add a new element
someArray[4] = "Surprise!";
someArray.length; //  5 Uh!?

© 2013 SAP AG. All rights reserved.

116
Array .length Property (and What it Doesn’t Mean!)
The value of an array's .length property doesn't always return the value you might expect.
It does not necessarily represent the number of elements that actually exist in the array!
// Create an empty array
var someArray = [];
someArray.length; //  0. Everything is behaving as expected...
// Add a new element
someArray[4] = "Surprise!";
someArray.length; //  5 Uh!?

someArray;

© 2013 SAP AG. All rights reserved.

// 

[undefined, undefined, undefined, undefined, "Surprise!"]

117
Array .length Property (and What it Doesn’t Mean!)
The value of an array's .length property doesn't always return the value you might expect.
It does not necessarily represent the number of elements that actually exist in the array!
// Create an empty array
var someArray = [];
someArray.length; //  0. Everything is behaving as expected...
// Add a new element
someArray[4] = "Surprise!";
someArray.length; //  5 Uh!?

someArray;

// 

[undefined, undefined, undefined, undefined, "Surprise!"]

The .length property will always return a value 1 higher than the value of the current highest index –
irrespective of whether any of the intervening elements exist or not!

© 2013 SAP AG. All rights reserved.

118
Regular Expressions
A Regular Expression is a tool for defining a pattern of text and then locating instances of that pattern
within a larger string.
// Create a regular expression for identifying RGB colour triples in the form of either
// "#RRGGBB" or "#RGB"
var regEx = /#([a-f0-9]{6}|[a-f0-9]{3})/i;
var colour1 = "The background colour is #3300ff";
var colour2 = "The foreground colour is sky blue pink";

var results1 = regEx.exec(colour1); //  ["#3300ff", "3300ff"]

© 2013 SAP AG. All rights reserved.

119
Regular Expressions
A Regular Expression is a tool for defining a pattern of text and then locating instances of that pattern
within a larger string.
// Create a regular expression for identifying RGB colour triples in the form of either
// "#RRGGBB" or "#RGB"
var regEx = /#([a-f0-9]{6}|[a-f0-9]{3})/i;
var colour1 = "The background colour is #3300ff";
var colour2 = "The foreground colour is sky blue pink";

var results1 = regEx.exec(colour1); //  ["#3300ff", "3300ff"]
var results2 = regEx.exec(colour2); //  null The string does not contain an RGB triple

© 2013 SAP AG. All rights reserved.

120
Regular Expressions
A Regular Expression is a tool for defining a pattern of text and then locating instances of that pattern
within a larger string.
// Create a regular expression for identifying RGB colour triples in the form of either
// "#RRGGBB" or "#RGB"
var regEx = /#([a-f0-9]{6}|[a-f0-9]{3})/i;
var colour1 = "The background colour is #3300ff";
var colour2 = "The foreground colour is sky blue pink";

var results1 = regEx.exec(colour1); //  ["#3300ff", "3300ff"]
var results2 = regEx.exec(colour2); //  null The string does not contain an RGB triple
results1.index;

//  25

© 2013 SAP AG. All rights reserved.

The index at which the first text pattern match was found

121
Regular Expressions
A Regular Expression is a tool for defining a pattern of text and then locating instances of that pattern
within a larger string.
// Create a regular expression for identifying RGB colour triples in the form of either
// "#RRGGBB" or "#RGB"
var regEx = /#([a-f0-9]{6}|[a-f0-9]{3})/i;
var colour1 = "The background colour is #3300ff";
var colour2 = "The foreground colour is sky blue pink";

var results1 = regEx.exec(colour1); //  ["#3300ff", "3300ff"]
var results2 = regEx.exec(colour2); //  null The string does not contain an RGB triple
results1.index;

//  25

The index at which the first text pattern match was found

See https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions for more details
on the syntax and use of regular expressions.

© 2013 SAP AG. All rights reserved.

122

More Related Content

What's hot

Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...Edureka!
 
Java 9 New Features
Java 9 New FeaturesJava 9 New Features
Java 9 New FeaturesAli BAKAN
 
Java 10 New Features
Java 10 New FeaturesJava 10 New Features
Java 10 New FeaturesAli BAKAN
 
Advanced Reflection in Java
Advanced Reflection in JavaAdvanced Reflection in Java
Advanced Reflection in Javakim.mens
 
Deep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UKDeep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UKJosé Paumard
 
Java presentation
Java presentationJava presentation
Java presentationsurajdmk
 
Memory Management in the Java Virtual Machine(Garbage collection)
Memory Management in the Java Virtual Machine(Garbage collection)Memory Management in the Java Virtual Machine(Garbage collection)
Memory Management in the Java Virtual Machine(Garbage collection)Prashanth Kumar
 
Core Java Slides
Core Java SlidesCore Java Slides
Core Java SlidesVinit Vyas
 
GraalVM: Run Programs Faster Everywhere
GraalVM: Run Programs Faster EverywhereGraalVM: Run Programs Faster Everywhere
GraalVM: Run Programs Faster EverywhereJ On The Beach
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java WorkshopSimon Ritter
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Edureka!
 

What's hot (20)

Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
 
Java 9 New Features
Java 9 New FeaturesJava 9 New Features
Java 9 New Features
 
TypeScript VS JavaScript.pptx
TypeScript VS JavaScript.pptxTypeScript VS JavaScript.pptx
TypeScript VS JavaScript.pptx
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Java 10 New Features
Java 10 New FeaturesJava 10 New Features
Java 10 New Features
 
Java PPT
Java PPTJava PPT
Java PPT
 
JavaScript Variables
JavaScript VariablesJavaScript Variables
JavaScript Variables
 
Advanced Reflection in Java
Advanced Reflection in JavaAdvanced Reflection in Java
Advanced Reflection in Java
 
Deep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UKDeep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UK
 
Java presentation
Java presentationJava presentation
Java presentation
 
Memory Management in the Java Virtual Machine(Garbage collection)
Memory Management in the Java Virtual Machine(Garbage collection)Memory Management in the Java Virtual Machine(Garbage collection)
Memory Management in the Java Virtual Machine(Garbage collection)
 
Angular 2 observables
Angular 2 observablesAngular 2 observables
Angular 2 observables
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Rust
RustRust
Rust
 
Core Java Slides
Core Java SlidesCore Java Slides
Core Java Slides
 
GraalVM: Run Programs Faster Everywhere
GraalVM: Run Programs Faster EverywhereGraalVM: Run Programs Faster Everywhere
GraalVM: Run Programs Faster Everywhere
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java Workshop
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Java
JavaJava
Java
 

Similar to JavaScript for ABAP Programmers - 3/7 Syntax

Cordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to JavascriptCordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to JavascriptBinu Paul
 
JavaScript Coding Guidelines
JavaScript Coding GuidelinesJavaScript Coding Guidelines
JavaScript Coding GuidelinesOleksii Prohonnyi
 
Introduction of basics loop and array
Introduction of basics loop and arrayIntroduction of basics loop and array
Introduction of basics loop and arrayprojectsinfo
 
prt123.pptx
prt123.pptxprt123.pptx
prt123.pptxASADKS
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsEng Teong Cheah
 
JavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdfJavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdfranjanadeore1
 
Angular JS in 2017
Angular JS in 2017Angular JS in 2017
Angular JS in 2017Ayush Sharma
 
Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorialadelaticleanu
 
[FullStack NYC 2019] Effective Unit Tests for JavaScript
[FullStack NYC 2019] Effective Unit Tests for JavaScript[FullStack NYC 2019] Effective Unit Tests for JavaScript
[FullStack NYC 2019] Effective Unit Tests for JavaScriptHazem Saleh
 
imperative programming language, java, android
imperative programming language, java, androidimperative programming language, java, android
imperative programming language, java, androidi i
 
JAVA 8 Parallel Stream
JAVA 8 Parallel StreamJAVA 8 Parallel Stream
JAVA 8 Parallel StreamTengwen Wang
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdfvenud11
 
SoftTest Ireland: Model Based Testing - January 27th 2011
SoftTest Ireland: Model Based Testing - January 27th 2011SoftTest Ireland: Model Based Testing - January 27th 2011
SoftTest Ireland: Model Based Testing - January 27th 2011David O'Dowd
 
While loop and for loop 06 (js)
While loop and for loop 06 (js)While loop and for loop 06 (js)
While loop and for loop 06 (js)AbhishekMondal42
 

Similar to JavaScript for ABAP Programmers - 3/7 Syntax (20)

Cordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to JavascriptCordova training : Day 3 - Introduction to Javascript
Cordova training : Day 3 - Introduction to Javascript
 
JavaScript Coding Guidelines
JavaScript Coding GuidelinesJavaScript Coding Guidelines
JavaScript Coding Guidelines
 
Final requirement
Final requirementFinal requirement
Final requirement
 
Introduction of basics loop and array
Introduction of basics loop and arrayIntroduction of basics loop and array
Introduction of basics loop and array
 
prt123.pptx
prt123.pptxprt123.pptx
prt123.pptx
 
Coding standards
Coding standardsCoding standards
Coding standards
 
Janakiram web
Janakiram webJanakiram web
Janakiram web
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & Loops
 
JavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdfJavaScript Cheatsheets with easy way .pdf
JavaScript Cheatsheets with easy way .pdf
 
Angular JS in 2017
Angular JS in 2017Angular JS in 2017
Angular JS in 2017
 
Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorial
 
[FullStack NYC 2019] Effective Unit Tests for JavaScript
[FullStack NYC 2019] Effective Unit Tests for JavaScript[FullStack NYC 2019] Effective Unit Tests for JavaScript
[FullStack NYC 2019] Effective Unit Tests for JavaScript
 
imperative programming language, java, android
imperative programming language, java, androidimperative programming language, java, android
imperative programming language, java, android
 
JAVA 8 Parallel Stream
JAVA 8 Parallel StreamJAVA 8 Parallel Stream
JAVA 8 Parallel Stream
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdf
 
SoftTest Ireland: Model Based Testing - January 27th 2011
SoftTest Ireland: Model Based Testing - January 27th 2011SoftTest Ireland: Model Based Testing - January 27th 2011
SoftTest Ireland: Model Based Testing - January 27th 2011
 
While loop and for loop 06 (js)
While loop and for loop 06 (js)While loop and for loop 06 (js)
While loop and for loop 06 (js)
 
Java script best practices v4
Java script best practices v4Java script best practices v4
Java script best practices v4
 
Loops
LoopsLoops
Loops
 

Recently uploaded

Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 

Recently uploaded (20)

Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 

JavaScript for ABAP Programmers - 3/7 Syntax

  • 1. JavaScript for ABAP Programmers Syntax Chris Whealy / The RIG
  • 2. ABAP Strongly typed Syntax similar to COBOL Block Scope No equivalent concept OO using class based inheritance Imperative programming JavaScript Weakly typed Syntax derived from Java Lexical Scope Functions are 1st class citizens OO using referential inheritance Imperative or Functional programming
  • 4. Syntax: Keywords and Reserved words As with any other language, JavaScript has a list of words that may not be used as variable names because they are keywords of the language. These are: break, case, catch, continue, debugger, default, delete, do, else, false, finally, for, function, if, in, instanceof, new, null, return, switch, this, throw, true, try, typeof, var, void, while, with However, the ECMAScript specification also excludes the following words from implementations because they have been reserved for future use. These are: class, enum, export, extends, import, super, implements, interface, let, package, private, protected, public, static, yield © 2013 SAP AG. All rights reserved. 4
  • 5. Syntax: Code Blocks A code block is formed by enclosing a set of logically related JavaScript statements in curly braces. Code blocks are used to define functions, or to delimit a set of instructions used for flow control. // A stand-alone code block { // Everything inside the curlies belongs // to this code block } © 2013 SAP AG. All rights reserved. A standalone code block is not very useful in JavaScript because it can neither be referenced nor reused 5
  • 6. Syntax: Code Blocks A code block is formed by enclosing a set of logically related JavaScript statements in curly braces. Code blocks are used to define functions, or to delimit a set of instructions used for flow control. // A stand-alone code block { // Everything inside the curlies belongs // to this code block } // Here's a more useful code block function doThis(someParameter) { // This code block becomes the executable // part of a function object. } A standalone code block is not very useful in JavaScript because it can neither be referenced nor reused Preceding a code block with the keyword function() (and an optional name) creates a function object A function is executed by using the invocation operator () after the function name with zero or more parameters doThis("a value"); © 2013 SAP AG. All rights reserved. 6
  • 7. Syntax: Flow Control: Selection A selection statement determines which code block should be performed based on the outcome of a condition. Selections are either simple left/right branches or multi-way branches. // Left/Right branch: // Is this condition true? if (someCondition == true) { // Yup, so do this code block } else { // Nope, do this code block instead } © 2013 SAP AG. All rights reserved. A simple left/right branch is performed using an if/else construct. 7
  • 8. Syntax: Flow Control: Selection A selection statement determines which code block should be performed based on the outcome of a condition. Selections are either simple left/right branches or multi-way branches. // Left/Right branch: // Is this condition true? if (someCondition == true) { // Yup, so do this code block } else { // Nope, do this code block instead } // Multi-way branch: switch (someValue) { case "a": alert("Bang!"); break; case "b": alert("Fizz!"); break; default: alert("None of the above!"); } © 2013 SAP AG. All rights reserved. A simple left/right branch is performed using an if/else construct. Multi-way branch is performed using a switch/case construct 8
  • 9. Syntax: Flow Control: Iteration "Iteration" is the name given to the repeated execution of a code block whilst a condition remains true. // Iterate using 'while' while (someCondition == true) { // Do this code block } © 2013 SAP AG. All rights reserved. The condition is tested first. If it evaluates to true, then the code block is executed and the condition tested again. As long as the condition remains true, the code block will be executed 9
  • 10. Syntax: Flow Control: Iteration "Iteration" is the name given to the repeated execution of a code block whilst a condition remains true. // Iterate using 'while' while (someCondition == true) { // Do this code block } // Iterate using 'for' for (var i=0; i<someLimit; i++) { // Do this code block } © 2013 SAP AG. All rights reserved. The condition is tested first. If it evaluates to true, then the code block is executed and the condition tested again. As long as the condition remains true, the code block will be executed A for loop executes a code block a specific number of times and is controlled by providing: • A start value for the loop control variable • A continuation condition • An instruction to modify the loop control variable 10
  • 11. Syntax: Flow Control: Iteration "Iteration" is the name given to the repeated execution of a code block whilst a condition remains true. // Iterate using 'while' while (someCondition == true) { // Do this code block } // Iterate using 'for' for (var i=0; i<someLimit; i++) { // Do this code block } // Iterate using 'for ... in' for (var prop in someObject) { // Perform this code block on each // property belonging to someObject } © 2013 SAP AG. All rights reserved. The condition is tested first. If it evaluates to true, then the code block is executed and the condition tested again. As long as the condition remains true, the code block will be executed A for loop executes a code block a specific number of times and is controlled by providing: • A start value for the loop control variable • A continuation condition • An instruction to modify the loop control variable The for in construct allows you to iterate through all the properties belonging to an object 11
  • 12. Syntax: Statement Terminators In JavaScript the statement terminator is a semi-colon. However, be careful; its use is optional! // Be careful with the optional statement terminator in JavaScript! var someVariable = "Some value" // The semi-colon is missing, but that's OK because there's nothing ambiguous here... © 2013 SAP AG. All rights reserved. 12
  • 13. Syntax: Statement Terminators In JavaScript the statement terminator is a semi-colon. However, be careful; its use is optional! // Be careful with the optional statement terminator in JavaScript! var someVariable = "Some value" // The semi-colon is missing, but that's OK because there's nothing ambiguous here... // This is also OK. The invisble carriage return after the 'return n * n' statement automatically terminates the expression. function good_sqr(n) { return n * n } © 2013 SAP AG. All rights reserved. 13
  • 14. Syntax: Statement Terminators In JavaScript the statement terminator is a semi-colon. However, be careful; its use is optional! // Be careful with the optional statement terminator in JavaScript! var someVariable = "Some value" // The semi-colon is missing, but that's OK because there's nothing ambiguous here... // This is also OK. The invisble carriage return after the 'return n * n' statement automatically terminates the expression. function good_sqr(n) { return n * n } // NASTY SURPRISE!! This function always returns the special value 'undefined'! function bad_sqr(n) { // The 'return' statement used with no parameters means 'return undefined'. If 'return' is immediately followed by a // carriage return, then JavaScript assumes that you meant to write 'return undefined'. // The expression 'n * n;' on its own is valid, but will never be executed because the function has already terminated return n * n; } © 2013 SAP AG. All rights reserved. 14
  • 15. Syntax: Statement Terminators In JavaScript the statement terminator is a semi-colon. However, be careful; its use is optional! // Be careful with the optional statement terminator in JavaScript! var someVariable = "Some value" // The semi-colon is missing, but that's OK because there's nothing ambiguous here... // This is also OK. The invisble carriage return after the 'return n * n' statement automatically terminates the expression. function good_sqr(n) { return n * n } // NASTY SURPRISE!! This function always returns the special value 'undefined'! function bad_sqr(n) { // The 'return' statement used with no parameters means 'return undefined'. If 'return' is immediately followed by a // carriage return, then JavaScript assumes that you meant to write 'return undefined'. // The expression 'n * n;' on its own is valid, but will never be executed because the function has already terminated return n * n; } IMPORTANT! A missing statement terminator sometimes results in a carriage return being misinterpreted as the end of the statement. Therefore: • JavaScript statements should always be terminated explicitly • Only split JavaScript statements across multiple lines at points where statement termination is not syntactically possible © 2013 SAP AG. All rights reserved. 15
  • 16. Syntax: Comments Comments can be single line Or multi-line // this is a single line comment /* this is a multi-line comment */ The comment syntax in JavaScript is exactly the same as that used in Java, C and C++ Unlike the full line comment delimiter "*" in ABAP, the single line JavaScript comment delimiter // does not need to start in column 1 of the source code; it can appear anywhere on the line. © 2013 SAP AG. All rights reserved. 16
  • 18. Unary Operators 1/4 A unary operator is an operator that requires only one operand. Some unary operators can be specified either before (prefix) or after (postfix) their operand. var value1 = 1; var value2 = 0; © 2013 SAP AG. All rights reserved. 18
  • 19. Unary Operators 1/4 A unary operator is an operator that requires only one operand. Some unary operators can be specified either before (prefix) or after (postfix) their operand. var value1 = 1; var value2 = 0; // Unary increment ++ // Unary decrement -// The (in/de)crement value2 = value1++; value1; value2; © 2013 SAP AG. All rights reserved. operator can be used as either a prefix or a postfix! // First, assign value1 to value2 then increment value1 // 2 // 1 19
  • 20. Unary Operators 1/4 A unary operator is an operator that requires only one operand. Some unary operators can be specified either before (prefix) or after (postfix) their operand. var value1 = 1; var value2 = 0; // Unary increment ++ // Unary decrement -// The (in/de)crement value2 = value1++; value1; value2; operator can be used as either a prefix or a postfix! // First, assign value1 to value2 then increment value1 // 2 // 1 value2 = ++value1; value1; value2; // First, increment value1 then assign the result to value2 // 3 // 3 © 2013 SAP AG. All rights reserved. 20
  • 21. Unary Operators 2/4 The arithmetic operators for addition and subtraction can be used as prefix unary operators. var value1 = -1; var value2 = "cat"; -value1; //  1. +value1; //  -1. // Return the negative numeric value Return the numeric value, not the positive numeric value! Notice, the minus sign is not flipped! -value2; //  NaN. A string has no numeric representation, so the result is 'Not a number' +value2; //  NaN. A string has no numeric representation, so the result is 'Not a number' © 2013 SAP AG. All rights reserved. 21
  • 22. Unary Operators 3/4 There are two unary logical NOT operators. “!” performs a Boolean NOT operation and “~” performs a bitwise NOT operation. var value1 = false; var value2 = 2; // "!" coerces its operand to type Boolean (if necessary), then negates it !value1; //  true. !value2; //  false. Any non-zero number equates to true, !true is false © 2013 SAP AG. All rights reserved. 22
  • 23. Unary Operators 3/4 There are two unary logical NOT operators. “!” performs a Boolean NOT operation and “~” performs a bitwise NOT operation. var value1 = false; var value2 = 2; var value3 = 0x0F; // A hexadecimal value is prefixed by 0x. 0F is the binary value 00001111 // "!" coerces its operand to type Boolean (if necessary), then negates it !value1; //  true. !value2; //  false. Any non-zero number equates to true, !true is false // "~" performs a bitwise logical NOT. Each bit in the binary value is flipped ~value3; //  0xF0 (binary value 00001111 becomes 11110000) © 2013 SAP AG. All rights reserved. 23
  • 24. Unary Operators 4/4 (And just for fun…) What would happen if you applied the bitwise NOT operator to a Boolean value? // Please explain the following behaviour: // Hint: You need to understand how the "2's compliment" binary representation works ~true; // Bitwise NOT of Boolean true  -2 ~false; // Bitwise NOT of Boolean false  -1 © 2013 SAP AG. All rights reserved. 24
  • 25. Unary Operators 4/4 (And just for fun…) What would happen if you applied the bitwise NOT operator to a Boolean value? // Please explain the following behaviour: // Hint: You need to understand how the "2's compliment" binary representation works ~true; // Bitwise NOT of Boolean true  -2 ~false; // Bitwise NOT of Boolean false  -1 // Think about the binary values used to represent TRUE and FALSE (hint  1 and 0) // So 'true' is interpreted as numeric 1 (which as a single byte is 00000001) and 'false' is // interpreted as numeric 0 (which as a single byte is 00000000). © 2013 SAP AG. All rights reserved. 25
  • 26. Unary Operators 4/4 (And just for fun…) What would happen if you applied the bitwise NOT operator to a Boolean value? // Please explain the following behaviour: // Hint: You need to understand how the "2's compliment" binary representation works ~true; // Bitwise NOT of Boolean true  -2 ~false; // Bitwise NOT of Boolean false  -1 // Think about the binary values used to represent TRUE and FALSE (hint  1 and 0) // So 'true' is interpreted as numeric 1 (which as a single byte is 00000001) and 'false' is // interpreted as numeric 0 (which as a single byte is 00000000). // Now perform the bitwise NOT operation: so all the bits in 00000001 are flipped to give // 11111110, and all the bits in 00000000 are flipped to give 11111111 © 2013 SAP AG. All rights reserved. 26
  • 27. Unary Operators 4/4 (And just for fun…) What would happen if you applied the bitwise NOT operator to a Boolean value? // Please explain the following behaviour: // Hint: You need to understand how the "2's compliment" binary representation works ~true; // Bitwise NOT of Boolean true  -2 ~false; // Bitwise NOT of Boolean false  -1 // Think about the binary values used to represent TRUE and FALSE (hint  1 and 0) // So 'true' is interpreted as numeric 1 (which as a single byte is 00000001) and 'false' is // interpreted as numeric 0 (which as a single byte is 00000000). // Now perform the bitwise NOT operation: so all the bits in 00000001 are flipped to give // 11111110, and all the bits in 00000000 are flipped to give 11111111 // Now look at these values using the 2's complement format (where the senior bit has a // value of -128, not +128). Therefore, 11111110 = -2 and 11111111 = -1 © 2013 SAP AG. All rights reserved. 27
  • 28. Binary Operators 1/3 A binary operator is one that requires two operands; one on the left and one on the right. Binary operators that separate their operands are also known as “infix” operators. // The familiar arithmetic operations such as add, subtract, divide and multiply are binary // operators var x = 12; var y = 3; // No surprises x + y; //  x - y; //  x * y; //  x / y; //  here I hope... 15 9 36 4 // Another less familiar binary operator is modulus division x % y; //  0. Divide x by y, return the remainder (12 / 3 = 4 remainder 0) © 2013 SAP AG. All rights reserved. 28
  • 29. Binary Operators 2/3 Binary operators to perform logical operations at the bit-level and bitwise shifting. Bit shifting effectively multiplies or divides a value by some power of 2. var x = 0x0F; var y = 0xAA; var z = 3; // These x & y; x | y; x ^ y; // Decimal 15 or 00001111 // Decimal 170 or 10101010 operators manipulate //  0x0A 00001010 //  0xAF 10101111 //  0xA5 10100101 y << z; //  1360 y >> z; //  0x15 y >>> z; //  0x15 © 2013 SAP AG. All rights reserved. the individual bits of their operands Bitwise AND Bitwise OR Bitwise Exclusive OR (XOR) Shift y left by z places, zero padding on right (y * 2^z) Shift y right by z places, preserving the sign bit Shift y right by z places, zero padding on left 29
  • 30. Binary Operators 3/3 Binary operators to perform Boolean logical operations // These operators treat their operands as Boolean values x && y; // Boolean AND If x is false, the condition fails immediately without testing y x || y; // Boolean OR If x is true, the condition passes immediately without testing y As with all modern languages, the JavaScript Boolean operators AND and OR use a performance enhancement called "early bail out". This means that if the first operand of the AND operator evaluates to false, then the whole condition has failed and there is no point testing the second operand, so the test bails out early. Similarly, if the first operand of the OR operator evaluates to true, then the whole condition has passed and there is no point testing the second operand, so the test bails out early. © 2013 SAP AG. All rights reserved. 30
  • 31. Ternary Operator: Test A Condition Without Using if JavaScript has a single ternary operator to provide a compact way of representing a simple left/right selection. A ternary operator requires three operands. © 2013 SAP AG. All rights reserved. 31
  • 32. Ternary Operator: Test A Condition Without Using if JavaScript has a single ternary operator to provide a compact way of representing a simple left/right selection. A ternary operator requires three operands. // Doing it the long way function catSays(animal) { var result; if (animal == "cat" || animal == "kitten" ) { result = "Meow!"; } else { result "Not a cat!"; } return result; } This is perfectly correct, but it is unnecessarily verbose... © 2013 SAP AG. All rights reserved. 32
  • 33. Ternary Operator: Test A Condition Without Using if JavaScript has a single ternary operator to provide a compact way of representing a simple left/right selection. A ternary operator requires three operands. // Doing it the long way function catSays(animal) { var result; if (animal == "cat" || animal == "kitten" ) { result = "Meow!"; } else { result "Not a cat!"; } // The ternary operator allows you to write an if // statement without needing to use the "if" keyword function catSays(animal) { return (animal == "cat" || animal == "kitten") ? "Meow!" : "Not a cat!"; } return result; } This is perfectly correct, but it is unnecessarily verbose... © 2013 SAP AG. All rights reserved. 33
  • 34. Ternary Operator: Test A Condition Without Using if JavaScript has a single ternary operator to provide a compact way of representing a simple left/right selection. A ternary operator requires three operands. // Doing it the long way function catSays(animal) { var result; if (animal == "cat" || animal == "kitten" ) { result = "Meow!"; } else { result "Not a cat!"; } // The ternary operator allows you to write an if // statement without needing to use the "if" keyword function catSays(animal) { return (animal == "cat" || animal == "kitten") ? "Meow!" : "Not a cat!"; } If this condition is true... return result; } This is perfectly correct, but it is unnecessarily verbose... © 2013 SAP AG. All rights reserved. 34
  • 35. Ternary Operator: Test A Condition Without Using if JavaScript has a single ternary operator to provide a compact way of representing a simple left/right selection. A ternary operator requires three operands. // Doing it the long way function catSays(animal) { var result; if (animal == "cat" || animal == "kitten" ) { result = "Meow!"; } else { result "Not a cat!"; } return result; // The ternary operator allows you to write an if // statement without needing to use the "if" keyword function catSays(animal) { return (animal == "cat" || animal == "kitten") ? "Meow!" : "Not a cat!"; } Then the result is whatever value follows the "?" character } This is perfectly correct, but it is unnecessarily verbose... © 2013 SAP AG. All rights reserved. 35
  • 36. Ternary Operator: Test A Condition Without Using if JavaScript has a single ternary operator to provide a compact way of representing a simple left/right selection. A ternary operator requires three operands. // Doing it the long way function catSays(animal) { var result; if (animal == "cat" || animal == "kitten" ) { result = "Meow!"; } else { result "Not a cat!"; } return result; // The ternary operator allows you to write an if // statement without needing to use the "if" keyword function catSays(animal) { return (animal == "cat" || animal == "kitten") ? "Meow!" : "Not a cat!"; } Else the result is whatever value follows the ":" character } This is perfectly correct, but it is unnecessarily verbose... © 2013 SAP AG. All rights reserved. 36
  • 37. Ternary Operator: Test A Condition Without Using if JavaScript has a single ternary operator to provide a compact way of representing a simple left/right selection. A ternary operator requires three operands. // Doing it the long way function catSays(animal) { var result; if (animal == "cat" || animal == "kitten" ) { result = "Meow!"; } else { result "Not a cat!"; } return result; } // The ternary operator allows you to write an if // statement without needing to use the "if" keyword function catSays(animal) { return (animal == "cat" || animal == "kitten") ? "Meow!" : "Not a cat!"; } The value returned by the function …is the outcome of the ternary operator This is perfectly correct, but it is unnecessarily verbose... © 2013 SAP AG. All rights reserved. 37
  • 39. Type Coercion to String: Using the Unary + Operator “Type coercion”* is the process by which a value of one data type is transformed into a value of another data type. This will occur automatically whenever an operator is supplied with a value that is not immediately suitable. var value1 = "-1"; var value2 = "cat"; +value1; //  -1. +value2; //  NaN. Unary "+" returns the numeric representation of a string Numeric representation of a non-numeric string is 'Not a number' * To "coerce" someone into doing something means that you have forced them to do something they would not otherwise willingly do. © 2013 SAP AG. All rights reserved. 39
  • 40. Type Coercion to String: Using the Unary + Operator “Type coercion” is the process by which a value of one data type is transformed into a value of another data type. This will occur automatically whenever an operator is supplied with a value that is not immediately suitable. var var var var value1 value2 value3 value4 = = = = "-1"; "cat"; false; true; +value1; //  -1. +value2; //  NaN. Unary "+" returns the numeric representation of a string Numeric representation of a non-numeric string is 'Not a number' +value3; //  numeric 0. +value4; //  numeric 1. Boolean false is coerced to numeric 0 Boolean true is coerced to numeric 1 The unary + operator can be used (if possible) to coerce character strings or Boolean values into numbers. © 2013 SAP AG. All rights reserved. 40
  • 41. Type Coercion to String: Overloading the Binary + Operator The binary plus operator can also be used for string concatenation. This is called “overloading” an operator. Be careful though! The behaviour changes depending on the data types of the operands! // The plus operator performs a normal arithmetic operation because both operands are numeric 1 + 2; //  3 (No surprises here, I hope) © 2013 SAP AG. All rights reserved. 41
  • 42. Type Coercion to String: Overloading the Binary + Operator The binary plus operator can also be used for string concatenation. This is called “overloading” an operator. Be careful though! The behaviour changes depending on the data types of the operands! // The plus operator performs a normal arithmetic operation because both operands are numeric 1 + 2; //  3 (No surprises here, I hope) // If any one of the operands passed to the binary plus operator is of type string, then the // operator has been "overloaded" and string concatenation will take place instead of // arithmetic addition. 1 + "2"; //  "12" "3" + 4; //  "34" © 2013 SAP AG. All rights reserved. 42
  • 43. Type Coercion to String: Overloading the Binary + Operator The binary plus operator can also be used for string concatenation. This is called “overloading” an operator. Be careful though! The behaviour changes depending on the data types of the operands! // The plus operator performs a normal arithmetic operation because both operands are numeric 1 + 2; //  3 (No surprises here, I hope) // If any one of the operands passed to the binary plus operator is of type string, then the // operator has been "overloaded" and string concatenation will take place instead of // arithmetic addition. 1 + "2"; //  "12" "3" + 4; //  "34" // Caution – type coercion takes place based on the data types of the operands! 1 + 2 + "3" + 4; //  "334" '1+2' is a numeric operation, so add. The rest is concatenation © 2013 SAP AG. All rights reserved. 43
  • 44. Type Coercion to Boolean: Using the Boolean NOT Operator The Boolean NOT operator can be used to coerce a value to be treated either as true or false. var value1 = false; var value2 = 2; // "!" coerces its operand to Boolean (if necessary), then negates it !value1; //  true. !value2; //  false. Any non-zero number equates to true, !true is false © 2013 SAP AG. All rights reserved. 44
  • 45. Type Coercion to Boolean: Using the Boolean NOT Operator The Boolean NOT operator can be used to coerce a value to be treated either as true or false. var value1 = false; var value2 = 2; // "!" coerces its operand to Boolean (if necessary), then negates it !value1; //  true. !value2; //  false. Any non-zero number equates to true, !true is false // Here's a useful trick when minimising JavaScript code. The keywords "true" and "false" use // 4 and 5 characters each. Rewriting these as !0 and !1 reduces the count to 2 !0; //  true. 0 is coerced to Boolean false, !false is true !1; //  false. 1 is coerced to Boolean true, !true is false © 2013 SAP AG. All rights reserved. 45
  • 46. Type Coercion to Boolean: Truthy and Falsy 1/2 Since all JavaScript data types can be coerced to a Boolean value, this leads to the concept that all JavaScript values are either “truthy” or “falsy”. // Values that evaluate to Boolean true are said to be 'truthy', and those that evaluate to // Boolean false are said to be 'falsy'. // For example, create an object whose properties hold a value of each data type var datatypes = { zero:0, one:1, "null":null, "undefined":undefined, "NaN":NaN, "function":function() {}, "true":true, "false":false, emptyString:"", emptyObject:{}, emptyArray:[] } © 2013 SAP AG. All rights reserved. 46
  • 47. Type Coercion to Boolean: Truthy and Falsy 1/2 Since all JavaScript data types can be coerced to a Boolean value, this leads to the concept that all JavaScript values are either “truthy” or “falsy”. // Values that evaluate to Boolean true are said to be 'truthy', and those that evaluate to // Boolean false are said to be 'falsy'. // For example, create an object whose properties hold a value of each data type var datatypes = { zero:0, one:1, "null":null, "undefined":undefined, "NaN":NaN, "function":function() {}, "true":true, "false":false, emptyString:"", emptyObject:{}, emptyArray:[] } // Loop around each property in the object writing the coerced Boolean value to the console for (var i in datatypes) { // See whether the above properties are truthy or falsy // The "double not" (!!) is a trick that coerces any data type to its Boolean equivalent console.log(i + " evaluates to " + !!datatypes[i]); } © 2013 SAP AG. All rights reserved. 47
  • 48. Type Coercion to Boolean: Truthy and Falsy 2/2 The general idea is this: any value that can be thought of as “empty” will evaluate to false such as zero or null etc. However, BE CAREFUL! Not all evaluations work the way you might expect! As expected, an empty string evaluates to false © 2013 SAP AG. All rights reserved. 48
  • 49. Type Coercion to Boolean: Truthy and Falsy 2/2 The general idea is this: any value that can be thought of as “empty” will evaluate to false such as zero or null etc. However, BE CAREFUL! Not all evaluations work the way you might expect! But empty arrays and empty objects evaluate to true… © 2013 SAP AG. All rights reserved. 49
  • 50. Type Coercion to Boolean: Overloading the OR Operator As a consequence of type coercion to Boolean, we can overload the logical OR operator (||) to check whether a parameter has been passed to a function, and if not, substitute a default value. // An overloaded OR operator is used to provide a default value if a function is not passed // a required parameter var person = function(fName,lName,DoB) { this.firstName = fName || "Not specified"; this.lastName = lName || "Not specified"; this.dateOfBirth = DoB; } © 2013 SAP AG. All rights reserved. 50
  • 51. Type Coercion to Boolean: Overloading the OR Operator As a consequence of type coercion to Boolean, we can overload the logical OR operator (||) to check whether a parameter has been passed to a function, and if not, substitute a default value. // An overloaded OR operator is used to provide a default value if a function is not passed // a required parameter var person = function(fName,lName,DoB) { this.firstName = fName || "Not specified"; this.lastName = lName || "Not specified"; this.dateOfBirth = DoB; } Here we rely on three aspects of JavaScript's behaviour: 1. Early bail out means that the second operand of the OR operator will only be evaluated if the first operand equals (or is coerced to) false 2. If a function parameter is not supplied, the parameter value will be null 3. Type coercion causes null to evaluate to false. © 2013 SAP AG. All rights reserved. 51
  • 52. Type Coercion to Boolean: Overloading the OR Operator As a consequence of type coercion to Boolean, we can overload the logical OR operator (||) to check whether a parameter has been passed to a function, and if not, substitute a default value. // An overloaded OR operator is used to provide a default value if a function is not passed // a required parameter var person = function(fName,lName,DoB) { this.firstName = fName || "Not specified"; this.lastName = lName || "Not specified"; this.dateOfBirth = DoB; } Here we rely on three aspects of JavaScript's behaviour: 1. Early bail out means that the second operand of the OR operator will only be evaluated if the first operand equals (or is coerced to) false 2. If a function parameter is not supplied, the parameter value will be null 3. Type coercion causes null to evaluate to false. If either parameter fName or lName is supplied, then their non-null value will coerce to true causing OR to bail out early and return the parameter value. However, if either of these parameters are not supplied, then their values will be null, forcing the OR operator to return the value of its second operand – which is the default value. © 2013 SAP AG. All rights reserved. 52
  • 53. Type Coercion to Boolean: Counting Down to Zero in Loops Here’s another example of where type coercion can be use to simplify the coding. // Use number  Boolean type coercion to // control a loop var n = 5; while (n--) { console.log("Stop when n = 0. n is now "+n); } Here, we are relying on the fact that all non-zero numeric values are truthy and zero is falsy. © 2013 SAP AG. All rights reserved. 53
  • 54. Type Coercion to Boolean: Counting Down to Zero in Loops Here’s another example of where type coercion can be use to simplify the coding. // Use number  Boolean type coercion to // control a loop var n = 5; while (n--) { console.log("Stop when n = 0. n is now "+n); } Here, we are relying on the fact that all non-zero numeric values are truthy and zero is falsy. The decrement operator -- is specifically used in the postfix position. This means that the value of n is tested before being decremented. © 2013 SAP AG. All rights reserved. 54
  • 55. Type Coercion to Boolean: Counting Down to Zero in Loops Here’s another example of where type coercion can be use to simplify the coding. // Use number  Boolean type coercion to // control a loop var n = 5; while (n--) { console.log("Stop when n = 0. n is now "+n); } Here, we are relying on the fact that all non-zero numeric values are truthy and zero is falsy. The decrement operator -- is specifically used in the postfix position. This means that the value of n is tested before being decremented. We now enter the body of the while loop with the decremented value of n – hence when the value of n is first written to the console it is 4, not 5. All non-zero values of n are truthy, so the loop continues. © 2013 SAP AG. All rights reserved. 55
  • 56. Type Coercion to Boolean: Counting Down to Zero in Loops Here’s another example of where type coercion can be use to simplify the coding. // Use number  Boolean type coercion to // control a loop var n = 5; while (n--) { console.log("Stop when n = 0. n is now "+n); } Here, we are relying on the fact that all non-zero numeric values are truthy and zero is falsy. The decrement operator -- is specifically used in the postfix position. This means that the value of n is tested before being decremented. We now enter the body of the while loop with the decremented value of n – hence when the value of n is first written to the console it is 4, not 5. All non-zero values of n are truthy, so the loop continues. The last time around the loop, n now equals 0. 0 is falsy, so the condition fails and the loop terminates. © 2013 SAP AG. All rights reserved. 56
  • 57. Type Coercion: Now Things Start To Get A Little Strange… Type coercion can cause certain data types to be treated in a way that is not immediately obvious // Type coercion 1 + []; //  1 + {}; //  [] + {}; //  to string by overloading the plus operator "1" Empty array is coerced to empty string, concatenate strings "1{object Object}" Coerce empty object to string "{object Object}", concatenate "{object Object}" [] coerced to "", {} coerced to "{object Object}", concatenate // Type coercion of Boolean to numeric 1 + true; //  2 Boolean true is coerced to numeric 1, 1+1=2 1 + false; //  1 Boolean false is coerced to numeric 0, 1+0=1 © 2013 SAP AG. All rights reserved. 57
  • 58. Type Coercion: OK, That's Just Weird… And as if that were not strange enough, here are some even stranger edge cases - and as is written at the edges of all good Medieval maps: Here be dragons // Type coercion {} + []; // {} + 1; // ({}) + 1; // !+[]; !+[]+!![]; can produce some bizarre results!  0  1  "{object Object}1" //  true //  2 !+[]+[]; //  "true" !+[]+!![]+[]; //  "2" [][[]]; [][[]]+[]; //  undefined //  "undefined" This strange behaviour is the basis of the Github obfuscation project called Hieroglyphy © 2013 SAP AG. All rights reserved. 58
  • 60. Type Determination (Another Unary Operator) The typeof operator allows you to discover the data type of a variable’s value – well mostly… // Declare some variables of various data types var aNumber = 123; var aString = "Nothing to see here, move along"; var anObject = { aProperty : 0 }; var aFunction = function() { }; var notANumber = NaN; var anArray = [1,2,3,4,5]; var nullValue = null; // What data types do we have here? typeof aNumber; //  'number' typeof aString; //  'string' typeof anObject; //  'object' typeof aFunction; //  'function' © 2013 SAP AG. All rights reserved. 60
  • 61. Type Determination (Another Unary Operator) The typeof operator allows you to discover the data type of a variable’s value – well mostly… // Declare some variables of various data types var aNumber = 123; var aString = "Nothing to see here, move along"; var anObject = { aProperty : 0 }; var aFunction = function() { }; var notANumber = NaN; var anArray = [1,2,3,4,5]; var nullValue = null; // What data types do we have here? typeof aNumber; //  'number' typeof aString; //  'string' typeof anObject; //  'object' typeof aFunction; //  'function' typeof notANumber; //  'number' This isn't as weird as you might think (See ECMAScript spec) © 2013 SAP AG. All rights reserved. 61
  • 62. Type Determination (Another Unary Operator) The typeof operator allows you to discover the data type of a variable’s value – well mostly… // Declare some variables of various data types var aNumber = 123; var aString = "Nothing to see here, move along"; var anObject = { aProperty : 0 }; var aFunction = function() { }; var notANumber = NaN; var anArray = [1,2,3,4,5]; var nullValue = null; // What data types do we have here? typeof aNumber; //  'number' typeof aString; //  'string' typeof anObject; //  'object' typeof aFunction; //  'function' typeof notANumber; //  'number' This isn't as weird as you might think (See ECMAScript spec) // So far, so good – the typeof operator is being well-behaved... typeof anArray; //  'object' Hmmm, this answer isn't wrong, but then neither is it helpful © 2013 SAP AG. All rights reserved. 62
  • 63. Type Determination (Another Unary Operator) The typeof operator allows you to discover the data type of a variable’s value – well mostly… // Declare some variables of various data types var aNumber = 123; var aString = "Nothing to see here, move along"; var anObject = { aProperty : 0 }; var aFunction = function() { }; var notANumber = NaN; var anArray = [1,2,3,4,5]; var nullValue = null; // What data types do we have here? typeof aNumber; //  'number' typeof aString; //  'string' typeof anObject; //  'object' typeof aFunction; //  'function' typeof notANumber; //  'number' This isn't as weird as you might think (See ECMAScript spec) // So far, so good – the typeof operator is being well-behaved... typeof anArray; //  'object' Hmmm, this answer isn't wrong, but then neither is it helpful typeof nullValue; //  'object' Sorry, but this is just wrong! © 2013 SAP AG. All rights reserved. 63
  • 64. Fixing the typeof operator 1/3 typeof is not entirely wrong for returning 'object' when passed an array, because an array is simply an object with array-like properties. However, whilst accurate, this answer is not helpful. // Create our own isArray() function // Use the toString() method belonging to JavaScript's standard Object prototype and check to see // whether the object in question has a string representation of '[object Array]'. // If it does, then we can be sure that the object really is an array. var isArray = function(obj) { return Object.prototype.toString.apply(obj) === '[object Array]'; }; © 2013 SAP AG. All rights reserved. 64
  • 65. Fixing the typeof operator 2/3 What is much more annoying is that the typeof operator cannot tell the difference between an object and a null value. So some improvement is needed here. // This improvement works by exploiting the fact that all objects are truthy, but null is falsy. // The first expression in the condition coerces myObj to Boolean; which, if it is null, will be // false. Because this is an AND condition, the whole condition fails if the first operand is false if (myObj && typeof myObj === 'object') { // Yup, this is an object and not null value }; © 2013 SAP AG. All rights reserved. 65
  • 66. Fixing the typeof operator 3/3 Rather than having to implement these fixes yourself, many of the widely used JavaScript frameworks provide their own replacement function for the typeof operator. For instance, in jQuery: var anArray = [1,2,3,4,5]; var nullValue = null; // jQuery provides a robust fix for JavaScript's only-sometimes-helpful typeof operator jQuery.type(anArray); //  'array' jQuery.type(nullValue); //  'null' // Or simply jQuery.isArray(anArray); © 2013 SAP AG. All rights reserved. //  true 66
  • 68. Operators: Basic Assignment Any value can be assigned to any variable using the assignment operator "=" var char1 = "a"; var char2 = "b"; // The value "a" is assigned to the local variable char1 // The value "b" is assigned to the local variable char2 // An object containing the single property "propertyName" is assigned to the variable myObj var myObj = { propertyName: "Some value" }; // A regular expression is assigned to the variable parseURL var parseURL = /^(?:([A-Za-z]+):)?(/{0,3})([0-9.-A-Za-z]+)(?::(d+))?(?:/([^?#]*))?(?:?([^#]*))?(?:#(.*))?$/; © 2013 SAP AG. All rights reserved. 68
  • 69. Operators: Shortcut Assignments JavaScript has various shortcut operators designed to make operations more compact. x x x x += -= *= /= y; y; y; y; // // // // Add y to Subtract Multiply Divide x x and store the result in x: y from x and store the result in x: x by y and store the result in x: by y and store the result in x: x x x x = = = = x %= y; // Remainder of x divided by y is stored in x: x <<= y; x >>= y; x >>>= y; + * / y y y y // Bitwise left shift: x = x << y // Bitwise right shift (preserve sign): x = x >> y // Bitwise right shift (ignore sign): x = x >>> y x &= y; x |= y; x ^= y; x x x x // Bitwise AND: x = x & y // Bitwise OR: x = x | y // Bitwise XOR: x = x ^ y © 2013 SAP AG. All rights reserved. x = x % y 69
  • 70. Operators: Basic Comparison Any two values can be compared: // // // // // > >= < <= != Greater than Greater than or equal to Less than Less than or equal to Not equal to 3.14 <= 2.717; "b" > "a"; //  False //  True © 2013 SAP AG. All rights reserved. Because "b" has a larger ASCII value than "a" 70
  • 71. Operators: Don't Confuse Assignment and Comparison Do not confuse the assignment operator with the comparison operator! var char1 = "a"; var char2 = "b"; // Declare a variable called 'char1' and assign to it the value "a" // Declare a variable called 'char2' and assign to it the value "b" // Beginner error... if (char1 = char2) { // OOPS! // The above condition actually evaluates to true because: // 1) The value of char2 is assigned to char1, so char1 now equals "b" // 2) Since "b" is a non-empty string, it is truthy, so the value of char1 is coerced to true // 3) Therefore the condition always passes } © 2013 SAP AG. All rights reserved. 71
  • 72. Operators: Comparison With Type Coercion: == Any test for (in)equality must first check whether the data types of the operands are the same. If they are not, then type coercion is performed: // "==" // "!=" If data types are not equal, first perform type coercion, then test for equality If data types are not equal, first perform type coercion, then test for inequality "1" == 1; "2" != 1 + 2; //  True //  True Numeric 1 is converted to string "1". Strings are equal Perform addition  1 + 2 = 3, convert result to string "3". Strings are not equal 2 == "1" + "1"; // False - Convert numeric 2 to string "2", concatenate "1" + "1"  "11". Strings are not equal // Comparison operators // ">" Greater than ">=" Greater than or equal to // "<" Less than "<=" less than or equal to "a" > "b"; "4" < 5; //  False //  True © 2013 SAP AG. All rights reserved. "a" comes before "b" in the ASCII collation sequence Convert numeric 5 to string "5", "4" comes before "5" in the ASCII collation sequence 72
  • 73. Operators: Comparison Without Type Coercion: === If your comparison is required to check the equality not only of the values, but also the data types, then you must use a different comparison operator: // "===" // "!==" Test for exact equality. First test data types for equality, then test values for equality Test for inequality. First test data types for equality, then test values for inequality "1" === 1; //  False 1 + 1 === "2"; //  False 1 + 1 === parseInt("2"); //  True Fails immediately because string and number are different data types 1+1 = numeric 2. Number and string do not match 1+1 = numeric 2. parseInt("2")  numeric 2. Both data type & value are equal // Be careful with the equality operators and type coercion! 1 + 1 !== "2"; //  True Because number and string are different data types 1 + 1 != "2"; //  False Because number is coerced to string. Strings are equal © 2013 SAP AG. All rights reserved. 73
  • 74. Operators: Invocation Everything in JavaScript is an object – even functions! This means that functions can be treated either as executable units of code, or as data objects just like a string or a date. // Define an anonymous function object and store it in a variable called 'person' var person = function() { var firstName = "Harry"; var lastName = "Hawk"; var dateOfBirth = "03 Aug 1976"; return firstName + " " + lastName + " was born on " + dateOfBirth; } © 2013 SAP AG. All rights reserved. 74
  • 75. Operators: Invocation Everything in JavaScript is an object – even functions! This means that functions can be treated either as executable units of code, or as data objects just like a string or a date. // Define an anonymous function object and store it in a variable called 'person' var person = function() { var firstName = "Harry"; var lastName = "Hawk"; var dateOfBirth = "03 Aug 1976"; return firstName + " " + lastName + " was born on " + dateOfBirth; } We can distinguish between a “function as an executable unit of code ” and a “function as a data object” by the use of the invocation operator (). This operator can take zero or more parameters inside the parentheses. © 2013 SAP AG. All rights reserved. 75
  • 76. Operators: Invocation Everything in JavaScript is an object – even functions! This means that functions can be treated either as executable units of code, or as data objects just like a string or a date. // Define an anonymous function object and store it in a variable called 'person' var person = function() { var firstName = "Harry"; var lastName = "Hawk"; var dateOfBirth = "03 Aug 1976"; return firstName + " " + lastName + " was born on " + dateOfBirth; } person; //  function() This is just a reference to the object called person that happens to be a function We can distinguish between a “function as an executable unit of code ” and a “function as a data object” by the use of the invocation operator (). This operator can take zero or more parameters inside the parentheses. Without the invocation operator, a function reference is simply that – a reference to an object that happens to have an executable part. © 2013 SAP AG. All rights reserved. 76
  • 77. Operators: Invocation Everything in JavaScript is an object – even functions! This means that functions can be treated either as executable units of code, or as data objects just like a string or a date. // Define an anonymous function object and store it in a variable called 'person' var person = function() { var firstName = "Harry"; var lastName = "Hawk"; var dateOfBirth = "03 Aug 1976"; return firstName + " " + lastName + " was born on " + dateOfBirth; } person; person(); //  function() This is just a reference to the object called person that happens to be a function //  "Harry Hawk was born on 03 Aug 1976" Now the function is invoked We can distinguish between a “function as an executable unit of code ” and a “function as a data object” by the use of the invocation operator (). This operator can take zero or more parameters inside the parentheses. Without the invocation operator, a function reference is simply that – a reference to an object that happens to have an executable part. Conversely, if the invocation operator is used, the function is treated as an executable unit of code and invoked. © 2013 SAP AG. All rights reserved. 77
  • 79. Declarations: Variables and Properties JavaScript distinguishes between values stored as a variables and values stored as properties. Both properties and variables are named values, but the scope of their storage differs: © 2013 SAP AG. All rights reserved. 79
  • 80. Declarations: Variables and Properties JavaScript distinguishes between values stored as a variables and values stored as properties. Both properties and variables are named values, but the scope of their storage differs:  A property is a named value that is always stored as the member of an object foobar = "Phluff 'n' stuff"; A property is created simply by assigning a value to name. If you do not specify to which object the property belongs (as in the above example), then that property will always belong to the Global Object. © 2013 SAP AG. All rights reserved. 80
  • 81. Declarations: Variables and Properties JavaScript distinguishes between values stored as a variables and values stored as properties. Both properties and variables are named values, but the scope of their storage differs:  A property is a named value that is always stored as the member of an object foobar = "Phluff 'n' stuff"; A property is created simply by assigning a value to name. If you do not specify to which object the property belongs (as in the above example), then that property will always belong to the Global Object.  A variable is a named value stored within an execution context var barfoo = "Chicken soup"; A variable is created by use of the var keyword in front of the assignment. More details will be given later about exactly what an “execution context” is. © 2013 SAP AG. All rights reserved. 81
  • 82. Declarations: Objects In JavaScript, everything is either an object (even functions) or the property of an object. An ‘object’ is simply an unordered collection of zero or more name:value pairs. © 2013 SAP AG. All rights reserved. 82
  • 83. Declarations: Objects In JavaScript, everything is either an object (even functions) or the property of an object. An ‘object’ is simply an unordered collection of zero or more name:value pairs. The simplest way to create an object is first to define an empty object, then assign it some arbitrary property values: // Create an empty object var person1 = {}; person1.firstName = "Harry"; person1.lastName = "Hawk"; person1.hobbies = ["swimming","cycling"]; person1.listHobbies = function() { return this.hobbies.join(" "); } © 2013 SAP AG. All rights reserved. 83
  • 84. Declarations: Objects In JavaScript, everything is either an object (even functions) or the property of an object. An ‘object’ is simply an unordered collection of zero or more name:value pairs. The simplest way to create an object is first to define an empty object, then assign it some arbitrary property values: Alternatively, you could use the array syntax: // Create an empty object var person1 = {}; // Create an empty object var person2 = {}; person1.firstName = "Harry"; person1.lastName = "Hawk"; person1.hobbies = ["swimming","cycling"]; person2["firstName"] = "Harry"; person2["Last-Name"] = "Hawk"; person2["hobbies"] = ["swimming","cycling"]; person1.listHobbies = function() { return this.hobbies.join(" "); } person2["listHobbies"] = function() { return this.hobbies.join(" "); } © 2013 SAP AG. All rights reserved. 84
  • 85. Declarations: Objects In JavaScript, everything is either an object (even functions) or the property of an object. An ‘object’ is simply an unordered collection of zero or more name:value pairs. The simplest way to create an object is first to define an empty object, then assign it some arbitrary property values: Alternatively, you could use the array syntax: // Create an empty object var person1 = {}; // Create an empty object var person2 = {}; person1.firstName = "Harry"; person1.lastName = "Hawk"; person1.hobbies = ["swimming","cycling"]; person2["firstName"] = "Harry"; person2["Last-Name"] = "Hawk"; person2["hobbies"] = ["swimming","cycling"]; person1.listHobbies = function() { return this.hobbies.join(" "); } person2["listHobbies"] = function() { return this.hobbies.join(" "); } The array syntax must be used either if you want to create an object property containing a character not permitted in a variable name, or if the property name is a reserved word. © 2013 SAP AG. All rights reserved. 85
  • 86. Two Ways To Access Object Properties The properties of a JavaScript object are accessed by specifying the object name and then using either the refinement operator “.” or the array element syntax. All object properties are public! // The refinement operator: place a dot "." between the object name and the property name person1.firstName; //  "Harry" person1.hobbies[1]; //  "cycling" © 2013 SAP AG. All rights reserved. 86
  • 87. Two Ways To Access Object Properties The properties of a JavaScript object are accessed by specifying the object name and then using either the refinement operator “.” or the array element syntax. All object properties are public! // The refinement operator: place a dot "." between the object name and the property name person1.firstName; //  "Harry" person1.hobbies[1]; //  "cycling" // The refinement operator is useful if the property name is both known at design time and // does not contain any illegal characters such as "-" or ";". However, if either of these // conditions are not met, then object properties can be accessed as array elements. person2["Last-Name"]; //  "Hawk" person2["hobbies"][0]; //  "swimming" © 2013 SAP AG. All rights reserved. 87
  • 88. Two Ways To Access Object Properties The properties of a JavaScript object are accessed by specifying the object name and then using either the refinement operator “.” or the array element syntax. All object properties are public! // The refinement operator: place a dot "." between the object name and the property name person1.firstName; //  "Harry" person1.hobbies[1]; //  "cycling" // The refinement operator is useful if the property name is both known at design time and // does not contain any illegal characters such as "-" or ";". However, if either of these // conditions are not met, then object properties can be accessed as array elements. person2["Last-Name"]; //  "Hawk" person2["hobbies"][0]; //  "swimming" // Both forms of property access can be chained together person1.propertyObject.someProperty; person2["propertyObject"]["someProperty"]; © 2013 SAP AG. All rights reserved. 88
  • 89. Two Ways To Access Object Properties The properties of a JavaScript object are accessed by specifying the object name and then using either the refinement operator “.” or the array element syntax. All object properties are public! // The refinement operator: place a dot "." between the object name and the property name person1.firstName; //  "Harry" person1.hobbies[1]; //  "cycling" // The refinement operator is useful if the property name is both known at design time and // does not contain any illegal characters such as "-" or ";". However, if either of these // conditions are not met, then object properties can be accessed as array elements. person2["Last-Name"]; //  "Hawk" person2["hobbies"][0]; //  "swimming" // Both forms of property access can be chained together person1.propertyObject.someProperty; person2["propertyObject"]["someProperty"]; // Any object property that is of type 'function' is known as a method and can be invoked person1.listHobbies(); //  "swimming cycling" © 2013 SAP AG. All rights reserved. 89
  • 90. Deleting Object Properties The properties of a JavaScript object can be deleted using the delete keyword. // Property deletion var aGlobalVariable = "I'm a global variable"; // Global variable, but not a property of the global object aGlobalProperty = "I'm a global property"; // A property belonging to the global object delete aGlobalVariable; delete aGlobalProperty; //  false. Delete can only operate on properties, not variables //  true. The property is deleted because it belongs to the global object aGlobalVariable; aGlobalProperty; //  "I'm a global variable" //  undefined © 2013 SAP AG. All rights reserved. 90
  • 91. JavaScript Object Notation (JSON) The syntax for creating a JavaScript object directly in your program is the same syntax that is used for serialising a JavaScript object as a text string: // Create an inline JavaScript object var person = { firstName : "Harry", lastName : "Hawk", dateOfBirth : "1976 Aug 03" } © 2013 SAP AG. All rights reserved. 91
  • 92. JavaScript Object Notation (JSON) The syntax for creating a JavaScript object directly in your program is the same syntax that is used for serialising a JavaScript object as a text string: // Create an inline JavaScript object var person = { firstName : "Harry", lastName : "Hawk", dateOfBirth : "1976 Aug 03" } © 2013 SAP AG. All rights reserved. // The same object serialised in JSON { firstName : "Harry", lastName : "Hawk", dateOfBirth : "1976 Aug 03" } 92
  • 93. JavaScript Object Notation (JSON) The syntax for creating a JavaScript object directly in your program is the same syntax that is used for serialising a JavaScript object as a text string: // Create an inline JavaScript object var person = { firstName : "Harry", lastName : "Hawk", dateOfBirth : "1976 Aug 03" } // The same object serialised in JSON { firstName : "Harry", lastName : "Hawk", dateOfBirth : "1976 Aug 03" } The convenience of this symmetry makes JSON the ideal output format for data from a web server. Once assigned to a JavaScript variable, a JSON string is parsed automatically making the internal structure of the object accessible to the rest of the program. // Replacing the inline object definition with a function call that obtains a JSON response from a web // server does not alter the above functionality unchanged var person = getJSONFromBackend(someKeyValue); © 2013 SAP AG. All rights reserved. 93
  • 94. Default Object Methods and Properties When a simple JavaScript object is created, the inline definition lists 3 properties of our own design: firstName, lastName and dateOfBirth. // Create an inline JavaScript object var person = { firstName : "Harry", lastName : "Hawk", dateOfBirth : "1976 Aug 03" } © 2013 SAP AG. All rights reserved. 94
  • 95. Default Object Methods and Properties When a simple JavaScript object is created, the inline definition lists 3 properties of our own design: firstName, lastName and dateOfBirth. // Create an inline JavaScript object var person = { firstName : "Harry", lastName : "Hawk", dateOfBirth : "1976 Aug 03" } person Properties  firstName  lastName  dateOfBirth  __proto__ However, the person object also has a default property called __proto__ that cannot be deleted. The __proto__ property is not actually part of the ECMAScript specification, so in that sense, it is a non-standard property. However, all modern browsers (except Internet Explorer) implement this property. More details will be given about this property later. © 2013 SAP AG. All rights reserved. 95
  • 96. Default Object Methods and Properties 1/2 Using the NodeJS command prompt, a simple inline JavaScript object is created containing 3 properties: firstName, lastName and dateOfBirth. > var person = { ... firstName : "Harry", ... lastName : "Hawk", ... dateOfBirth : "1976 Aug 03" ... } undefined > © 2013 SAP AG. All rights reserved. 96
  • 97. Default Object Methods and Properties 2/2 If we type the object name followed by a dot character and then press tab, we are shown a list of all the properties available in this object. Notice that there are several default methods available. > var person = { ... firstName : "Harry", ... lastName : "Hawk", ... dateOfBirth : "1976 Aug 03" ... } undefined > person. person.__defineGetter__ person.__defineSetter__ person.hasOwnProperty person.isPrototypeOf person.valueOf person.dateOfBirth © 2013 SAP AG. All rights reserved. person.firstName person.__lookupGetter__ person.propertyIsEnumerable person.__lookupSetter__ person.toLocaleString person.constructor person.toString person.lastName 97
  • 98. Default Object Methods and Properties 2/2 If we type the object name followed by a dot character and then press tab, we are shown a list of all the properties available in this object. Notice that there are several default methods available. > var person = { ... firstName : "Harry", ... lastName : "Hawk", ... dateOfBirth : "1976 Aug 03" ... } undefined > person. person.__defineGetter__ person.__defineSetter__ person.hasOwnProperty person.isPrototypeOf person.valueOf person.dateOfBirth person.firstName person.__lookupGetter__ person.propertyIsEnumerable person.__lookupSetter__ person.toLocaleString person.constructor person.toString person.lastName Methods inherited from the JavaScript object called Object © 2013 SAP AG. All rights reserved. 98
  • 99. Default Object Methods and Properties 2/2 If we type the object name followed by a dot character and then press tab, we are shown a list of all the properties available in this object. Notice that there are several default methods available. > var person = { ... firstName : "Harry", ... lastName : "Hawk", ... dateOfBirth : "1976 Aug 03" ... } undefined > person.__proto__. person.__proto__.__defineGetter__ person.__proto__.__lookupSetter__ person.__proto__.isPrototypeOf person.__proto__.toString person.__proto__.__defineSetter__ person.__proto__.constructor person.__proto__.propertyIsEnumerable person.__proto__.valueOf person.__proto__.__lookupGetter__ person.__proto__.hasOwnProperty person.__proto__.toLocaleString Even though the __proto__ property is not explicitly listed, if you enter its name followed by a dot and then press tab, you will see the methods and properties inherited from the object acting as person's prototype. More about prototypes later… © 2013 SAP AG. All rights reserved. 99
  • 101. Arrays 1/4 Remember! Everything in JavaScript is an object; therefore, a JavaScript array is simply a regular object that has extra array-like functionality built in. // Create an array variable. var listOfThings = ["ball","cup","pen","car"]; // Access the elements in the listOfThings[1]; //  listOfThings.length; //  listOfThings[4]; //  © 2013 SAP AG. All rights reserved. array "cup" 4 undefined All array indices are zero based, not one based 101
  • 102. Arrays 1/4 Remember! Everything in JavaScript is an object; therefore, a JavaScript array is simply a regular object that has extra array-like functionality built in. // Create an array variable. var listOfThings = ["ball","cup","pen","car"]; // Access the elements in the listOfThings[1]; //  listOfThings.length; //  listOfThings[4]; //  array "cup" 4 undefined All array indices are zero based, not one based // JavaScript arrays are not typesafe, their elements can be of a mixture of datatypes var differentThings = ["Chicken Soup", 12.34, null, ["a","b","c","d"], undefined, NaN, {prop: 123}, true, false]; © 2013 SAP AG. All rights reserved. 102
  • 103. Arrays 1/4 Remember! Everything in JavaScript is an object; therefore, a JavaScript array is simply a regular object that has extra array-like functionality built in. // Create an array variable. var listOfThings = ["ball","cup","pen","car"]; // Access the elements in the listOfThings[1]; //  listOfThings.length; //  listOfThings[4]; //  array "cup" 4 undefined All array indices are zero based, not one based // JavaScript arrays are not typesafe, their elements can be of a mixture of datatypes var differentThings = ["Chicken Soup", 12.34, null, ["a","b","c","d"], undefined, NaN, {prop: 123}, true, false]; IMPORTANT When you declare an Array, you are creating a regular JavaScript object that contains an extra set methods such as .push() and .pop(), and a .length property. These methods give this JavaScript object array-like behaviour. © 2013 SAP AG. All rights reserved. 103
  • 104. Arrays 2/4 Using the NodeJS command prompt, a new array is created called myArray. As before, type the object name followed by a dot and press the tab key to display the possible methods and properties… > var listOfThings = ["ball","cup","pen","car"]; undefined > listOfThings. listOfThings.__defineGetter__ listOfThings.__defineSetter__ listOfThings.constructor listOfThings.hasOwnProperty listOfThings.toLocaleString listOfThings.toString listOfThings.__lookupGetter__ listOfThings.isPrototypeOf listOfThings.valueOf listOfThings.__lookupSetter__ listOfThings.propertyIsEnumerable listOfThings.concat listOfThings.indexOf listOfThings.map listOfThings.reduceRight listOfThings.some listOfThings.filter listOfThings.lastIndexOf listOfThings.push listOfThings.shift listOfThings.splice listOfThings.forEach listOfThings.length listOfThings.reduce listOfThings.slice listOfThings.unshift listOfThings.0 © 2013 SAP AG. All rights reserved. listOfThings.every listOfThings.join listOfThings.pop listOfThings.reverse listOfThings.sort listOfThings.1 listOfThings.2 Methods inherited from the standard JavaScript object called Object listOfThings.3 104
  • 105. Arrays 2/4 Using the NodeJS command prompt, a new array is created called myArray. As before, type the object name followed by a dot and press the tab key to display the possible methods and properties… > var listOfThings = ["ball","cup","pen","car"]; undefined > listOfThings. listOfThings.__defineGetter__ listOfThings.__defineSetter__ listOfThings.constructor listOfThings.hasOwnProperty listOfThings.toLocaleString listOfThings.toString listOfThings.__lookupGetter__ listOfThings.isPrototypeOf listOfThings.valueOf listOfThings.__lookupSetter__ listOfThings.propertyIsEnumerable listOfThings.concat listOfThings.indexOf listOfThings.map listOfThings.reduceRight listOfThings.some listOfThings.every listOfThings.join listOfThings.pop listOfThings.reverse listOfThings.sort listOfThings.filter listOfThings.lastIndexOf listOfThings.push listOfThings.shift listOfThings.splice listOfThings.forEach listOfThings.length listOfThings.reduce listOfThings.slice listOfThings.unshift listOfThings.0 listOfThings.1 listOfThings.2 listOfThings.3 Extra built-in methods that give this object array-like capabilities © 2013 SAP AG. All rights reserved. 105
  • 106. Arrays 2/4 Using the NodeJS command prompt, a new array is created called myArray. As before, type the object name followed by a dot and press the tab key to display the possible methods and properties… > var listOfThings = ["ball","cup","pen","car"]; undefined > listOfThings. listOfThings.__defineGetter__ listOfThings.__defineSetter__ listOfThings.constructor listOfThings.hasOwnProperty listOfThings.toLocaleString listOfThings.toString listOfThings.__lookupGetter__ listOfThings.isPrototypeOf listOfThings.valueOf listOfThings.__lookupSetter__ listOfThings.propertyIsEnumerable listOfThings.concat listOfThings.indexOf listOfThings.map listOfThings.reduceRight listOfThings.some listOfThings.every listOfThings.join listOfThings.pop listOfThings.reverse listOfThings.sort listOfThings.filter listOfThings.lastIndexOf listOfThings.push listOfThings.shift listOfThings.splice listOfThings.forEach listOfThings.length listOfThings.reduce listOfThings.slice listOfThings.unshift listOfThings.0 listOfThings.1 listOfThings.2 listOfThings.3 Automatically created object properties. Each array element is created as a property whose name is the text string of the corresponding index number © 2013 SAP AG. All rights reserved. 106
  • 107. Arrays 3/4 All array elements are treated as a special type of object property. JavaScript uses the string representation of the numeric index as the property name. // Create an array variable. var listOfThings = ["ball","cup","pen","car"]; // Array elements can be accessed either by their numeric index, or by the string // representation of the numeric index. listOfThings[1]; //  "cup" © 2013 SAP AG. All rights reserved. 107
  • 108. Arrays 3/4 All array elements are treated as a special type of object property. JavaScript uses the string representation of the numeric index as the property name. // Create an array variable. var listOfThings = ["ball","cup","pen","car"]; // Array elements can be accessed either by their numeric index, or by the string // representation of the numeric index. listOfThings[1]; //  "cup" listOfThings["1"]; //  "cup" © 2013 SAP AG. All rights reserved. 108
  • 109. Arrays 3/4 All array elements are treated as a special type of object property. JavaScript uses the string representation of the numeric index as the property name. // Create an array variable. var listOfThings = ["ball","cup","pen","car"]; // Array elements can be accessed either by their numeric index, or by the string // representation of the numeric index. listOfThings[1]; //  "cup" listOfThings["1"]; //  "cup" // Create a new element using a numeric string as the index listOfThings["4"] = "tree"; © 2013 SAP AG. All rights reserved. 109
  • 110. Arrays 3/4 All array elements are treated as a special type of object property. JavaScript uses the string representation of the numeric index as the property name. // Create an array variable. var listOfThings = ["ball","cup","pen","car"]; // Array elements can be accessed either by their numeric index, or by the string // representation of the numeric index. listOfThings[1]; //  "cup" listOfThings["1"]; //  "cup" // Create a new element using a numeric string as the index listOfThings["4"] = "tree"; listOfThings[4]; //  "tree" listOfThings; //  ["ball","cup","pen","car","tree"] © 2013 SAP AG. All rights reserved. 110
  • 111. Arrays 3/4 All array elements are treated as a special type of object property. JavaScript uses the string representation of the numeric index as the property name. // Create an array variable. var listOfThings = ["ball","cup","pen","car"]; // Array elements can be accessed either by their numeric index, or by the string // representation of the numeric index. listOfThings[1]; //  "cup" listOfThings["1"]; //  "cup" // Create a new element using a numeric string as the index listOfThings["4"] = "tree"; listOfThings[4]; //  "tree" listOfThings; //  ["ball","cup","pen","car","tree"] // Alternatively, a new element can be appended to the array using the push() method listOfThings.push("dog"); listOfThings; //  ["ball","cup","pen","car","tree","dog"] © 2013 SAP AG. All rights reserved. 111
  • 112. Arrays 4/4 Since JavaScript arrays are just objects with array-like behaviour, you can add new properties to the array object using any names you like. // Create an array variable. var listOfThings = ["ball","cup","pen","car"]; listOfThings.length; //  4 // Create an array element using a non-numeric property name listOfThings["first"] = "Some value"; listOfThings["first"]; //  "Some value" © 2013 SAP AG. All rights reserved. 112
  • 113. Arrays 4/4 Since JavaScript arrays are just objects with array-like behaviour, you can add new properties to the array object using any names you like. // Create an array variable. var listOfThings = ["ball","cup","pen","car"]; listOfThings.length; //  4 // Create an array element using a non-numeric property name listOfThings["first"] = "Some value"; listOfThings["first"]; //  "Some value" listOfThings.length; listOfThings; © 2013 SAP AG. All rights reserved. //  4 Uh?! Didn't we just add a new element to the array? //  ["ball","cup","pen","car"] No, we added an object property, // not an array element... 113
  • 114. Arrays 4/4 Since JavaScript arrays are just objects with array-like behaviour, you can add new properties to the array object using any names you like. // Create an array variable. var listOfThings = ["ball","cup","pen","car"]; listOfThings.length; //  4 // Create an array element using a non-numeric property name listOfThings["first"] = "Some value"; listOfThings["first"]; //  "Some value" listOfThings.length; listOfThings; //  4 Uh?! Didn't we just add a new element to the array? //  ["ball","cup","pen","car"] No, we added an object property, // not an array element... Be careful! If the property name cannot be interpreted as an integer, then that new property will not be treated as an “element” of the array! It will simply be an object property with no special relevance to the set of elements making up the “array”. © 2013 SAP AG. All rights reserved. 114
  • 115. Array .length Property (and What it Doesn’t Mean!) The value of an array's .length property doesn't always return the value you might expect. It does not necessarily represent the number of elements that actually exist in the array! // Create an empty array var someArray = []; someArray.length; //  0. Everything is behaving as expected... // Add a new element someArray[4] = "Surprise!"; © 2013 SAP AG. All rights reserved. 115
  • 116. Array .length Property (and What it Doesn’t Mean!) The value of an array's .length property doesn't always return the value you might expect. It does not necessarily represent the number of elements that actually exist in the array! // Create an empty array var someArray = []; someArray.length; //  0. Everything is behaving as expected... // Add a new element someArray[4] = "Surprise!"; someArray.length; //  5 Uh!? © 2013 SAP AG. All rights reserved. 116
  • 117. Array .length Property (and What it Doesn’t Mean!) The value of an array's .length property doesn't always return the value you might expect. It does not necessarily represent the number of elements that actually exist in the array! // Create an empty array var someArray = []; someArray.length; //  0. Everything is behaving as expected... // Add a new element someArray[4] = "Surprise!"; someArray.length; //  5 Uh!? someArray; © 2013 SAP AG. All rights reserved. //  [undefined, undefined, undefined, undefined, "Surprise!"] 117
  • 118. Array .length Property (and What it Doesn’t Mean!) The value of an array's .length property doesn't always return the value you might expect. It does not necessarily represent the number of elements that actually exist in the array! // Create an empty array var someArray = []; someArray.length; //  0. Everything is behaving as expected... // Add a new element someArray[4] = "Surprise!"; someArray.length; //  5 Uh!? someArray; //  [undefined, undefined, undefined, undefined, "Surprise!"] The .length property will always return a value 1 higher than the value of the current highest index – irrespective of whether any of the intervening elements exist or not! © 2013 SAP AG. All rights reserved. 118
  • 119. Regular Expressions A Regular Expression is a tool for defining a pattern of text and then locating instances of that pattern within a larger string. // Create a regular expression for identifying RGB colour triples in the form of either // "#RRGGBB" or "#RGB" var regEx = /#([a-f0-9]{6}|[a-f0-9]{3})/i; var colour1 = "The background colour is #3300ff"; var colour2 = "The foreground colour is sky blue pink"; var results1 = regEx.exec(colour1); //  ["#3300ff", "3300ff"] © 2013 SAP AG. All rights reserved. 119
  • 120. Regular Expressions A Regular Expression is a tool for defining a pattern of text and then locating instances of that pattern within a larger string. // Create a regular expression for identifying RGB colour triples in the form of either // "#RRGGBB" or "#RGB" var regEx = /#([a-f0-9]{6}|[a-f0-9]{3})/i; var colour1 = "The background colour is #3300ff"; var colour2 = "The foreground colour is sky blue pink"; var results1 = regEx.exec(colour1); //  ["#3300ff", "3300ff"] var results2 = regEx.exec(colour2); //  null The string does not contain an RGB triple © 2013 SAP AG. All rights reserved. 120
  • 121. Regular Expressions A Regular Expression is a tool for defining a pattern of text and then locating instances of that pattern within a larger string. // Create a regular expression for identifying RGB colour triples in the form of either // "#RRGGBB" or "#RGB" var regEx = /#([a-f0-9]{6}|[a-f0-9]{3})/i; var colour1 = "The background colour is #3300ff"; var colour2 = "The foreground colour is sky blue pink"; var results1 = regEx.exec(colour1); //  ["#3300ff", "3300ff"] var results2 = regEx.exec(colour2); //  null The string does not contain an RGB triple results1.index; //  25 © 2013 SAP AG. All rights reserved. The index at which the first text pattern match was found 121
  • 122. Regular Expressions A Regular Expression is a tool for defining a pattern of text and then locating instances of that pattern within a larger string. // Create a regular expression for identifying RGB colour triples in the form of either // "#RRGGBB" or "#RGB" var regEx = /#([a-f0-9]{6}|[a-f0-9]{3})/i; var colour1 = "The background colour is #3300ff"; var colour2 = "The foreground colour is sky blue pink"; var results1 = regEx.exec(colour1); //  ["#3300ff", "3300ff"] var results2 = regEx.exec(colour2); //  null The string does not contain an RGB triple results1.index; //  25 The index at which the first text pattern match was found See https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions for more details on the syntax and use of regular expressions. © 2013 SAP AG. All rights reserved. 122