32
Copyright © 2010 Kony Solu4ons, Inc. CONFIDENTIAL 1 Copyright © 2013 Kony, Inc. CONFIDENTIAL JavaScript Tutorial

JavaScript Tutorial

Embed Size (px)

Citation preview

Page 1: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   1 Copyright © 2013 Kony, Inc. CONFIDENTIAL

JavaScript Tutorial

Page 2: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   2 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  JavaScript is most commonly associated with the web

§  We are going to go through a basic tutorial on JavaScript covering the basics you’ll need to get through in order to be successful with the Kony Developer training course.

§  This is by no means a comprehensive JavaScript tutorial – you’ll need to work on your JavaScript skills on your own.

§  A great place to start is www.w3schools.com/js or any of the many other site like this:

JavaScript

Page 3: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   3 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  In order to learn JavaScript, you’ll need to be able to write and TEST your JavaScript code

§  There are LOTS of ways to test JavaScript code but it's harder to find a way to test JavaScript outside of the web context

§  We will use Firebug – a plugin to Firefox – to test pure JavaScript so we can learn the language without worrying about HTML

§  Here's an example of what you get:

Testing our code

results from running code shown here

enter in our JavaScript code

to run the code…

Page 4: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   4 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  In the upper corner of Firefox you'll see the Firebug add-in (note: earlier versions may have it elsewhere on the screen):

§  Clicking on the icon opens the Firebug window at the bottom of the screen:

Testing our code – using Firebug

Firebug window

check this to open the editor

Page 5: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   5 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  This is the view we'll use for writing and running our code:

Testing our code – using Firebug (cont.)

click to run your code

for this module, when asked to write code, we will do it here

here you'll see your code echoed back to you along with any results

shows the history of all code that you ran – good for re-running old stuff

clears the results window

Page 6: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   6 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  JavaScript has some basic rules that we’ll just cover here

§  Before we start, from here on we’ll frequently use “JS” to mean JavaScript

§  We’ll also use this font when we are talking code or giving code samples or snippets

§  Here are the rules:

§  JS is case sensitive: hello and Hello and HELLO are all different variables as far as JS is concerned and if a method is called alert, calling Alert won’t work

§  typical JS convention is to lower case the first letter of a variable and camel case the rest or just all lower case

§  To comment out a whole line or part of a line of code, use //

§  for example: //this is a comment line

§  To comment multiple lines, start the comment on the first line with /* and end the comment on the last line with */ - everything inbetween is considered a comment

§  for example: /* here starts my comment and here ends my comment */

§  Every line of code must end with a ";"

Syntax

Page 7: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   7 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  You'll be writing a lot of functions

§  Functions are defined using the function keyword.

§  You must have the input parameters specified in parenthesis - if no inputs, you still need the parenthesis

§  The function code is entered within curly braces {}

§  Here is an example of a function definition with no input parameters:

function myFunction() {

// your logic goes here

}

§  Here is an example of a function with 2 input parameters:

function myFunction(inputA, inputB) {

// your logic goes here

}

§  You can call a function by just entering it's name and any parameters, if required:

myFunction("fred","flinstone");

Functions

Page 8: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   8 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  JavaScript variables are not typed as string, number, boolean, etc

§  There are 2 levels of variable – global and “local” (within a function)

§  The variable for each is defined using the same syntax

§  In JavaScript you can define a variable using var OR just start using it

§  What differentiates between the two is WHERE you define them

§  Here's an example:

var a; //creates a new global variable a with no initial value

function myFunction() {

var b="fred"; //b is a local variable to this function

}

§  Here's another example:

a="betty"; //creates a new global variable a and set it to "betty"

function myFunction() {

b="fred"; //b is a GLOBAL variable

}

Variables

without the var inside a function, it's declaring a global – using var makes it local

Page 9: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   9 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  You can assign values to variables with = and = is ONLY used for assignments of values (we will contrast that to how to check for equality in an IF statement later).

§  Operators are:

§  Note: for strings, "+" is your concatenation operator (ex. "hello" + " world" -> "hello world")

Variable assignments and math

courtesy of w3schools.com

Page 10: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   10 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  Strings can be represented by either single quotes or double quotes – they both work

§  Example: "hello" and 'hello' both work

§  Example: "this will 'work'" => this will 'work'

§  You can concatenate variables with strings, variables with variables, etc..

§  Example: if a = 10 and b = "frog" then

b + "s live to be " + a + " years old" => frogs live to be 10 years old

§  Strings are an array of characters – you can access characters by index (0 based)

§  Example: if a="hello world" then a[4] is "o"

§  There are many string functions available, here are some examples for a="hello world":

§  a.length => 11

§  a.indexOf("wor") => 6 remember, it's 0 based

Strings, numbers and Boolean values

Page 11: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   11 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  Numbers are not typed as real, long, integer etc…

§  All numbers in JavaScript are stored internally as 64 bit floating point numbers

§  For example all of the following declarations result in IDENTICAL values:

§  b = 100;

§  b = 10e1;

§  b = 100.0000000

§  Note: b=10 and b="10" are totally different things

§  To convert a numeric string to a number use the Number() function

§  For example: if b="101.967" then Number(b) will be 101.967 – the number

§  For Boolean values, use true and false. For example:

var isActive=false;

Strings, numbers and Boolean values (cont.)

Page 12: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   12 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  Functions can do things AND functions can return things

§  Using the return keyword to have the function return a value back to the calling routine

§  Consider this example:

function doAdd(x, y) {

return x+y;

}

function showResult() {

return ("if x=5 and y=10, then the sum is " + doAdd(5,10));

}

§  Calling showResult(); would return: "if x=5 and y=10, then the sum is 15"

Functions – returning data

Page 13: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   13 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  For testing out code, we'll need to print out our results

§  For Firebug, using the console.log() function will output results.

§  The syntax is:

console.log(<something>) where <something> can be a string, number, object, etc…

§  It will try to print the text equivalent. We'll see how useful that is with arrays and JSON objects…

§  Here's an example:

§  Note: in other tools print() might work instead of console.log()

Printing out results

Note: since the output echoes the code, for simple examples we'll just show the output to see code and results

Page 14: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   14 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  We'll start with a simple exercise to get used to JavaScript

§  Create a global variable and set it to the string "this is a good test string"

§  Create a function that will:

§  accept 2 input parameters – a string and a number

§  print out how many characters in the passed in string

§  add the number of characters to the passed in number and return that as a result

§  Call that function passing in the global variable and a hardcoded number

§  Print out the function result

§  Solution shown on next slide if you need help…

Exercise – JS functions and strings

example output when the passed in number is 55

Page 15: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   15 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  Here is a simple solution to the exercise.

§  Let's walk through it to make sure we understand everything going on:

§  Don't forget the ";" at the end of each line

§  Function code must be enclosed in {}

Exercise – functions and strings solved

create our global variable

our function that takes 2 input parameters…

…prints the string length…

…and returns the math result

here we call our function from within our print statement

Page 16: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   16 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  If statement format: if (condition)

{

code to be executed if true

}

§  if…else if…else statement format: if (condition)

{ code to be executed if true

} else if (condition)

{ code to be executed if true

} else

{ code to be executed if neither are true

}

Comparisons

condition must always be in parenthesis

Note that the if statement itself doesn't have ";" after it anywhere

Page 17: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   17 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  JavaScript utilized the following comparison operators (the return value based on x=5):

§  Note: if (x=5)… will NOT work. Why? because the assignment will happen (i.e. setting x to the value of 5) and the result of that is success which will always be true

Comparison operators

courtesy of w3schools.com

Page 18: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   18 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  Here are some examples. For each assume x=10 and y="ten"…

Comparison examples

if (x=="10") { console.log("x is a string") }

if (y=="ten") { console.log ("y is 10")

} else { console.log ("y is not 10")

}

if (x<=0) { console.log ("x is too small")

} else if (x > 20) { console.log ("x is too big")

} else { console.log ("x is just right")

}

Example: if

Example: if…else

Example: if…else if…else

Page 19: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   19 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  You can also use these conditional operators:

§  Here is a shortcut notation for conditionally setting a value (if statement shortcut):

condition?<return value if true>:<return value if false>

§  For example, if ears=3, then the statement:

earstatus = (ears==2)?"you have 2 ears":"you have extra ears!"

§  will result in earstatus being set to "you have extra ears!"

§  if checking for the existence of a value use null.

§  For example if (a==null) {console.log("value undefinied")}

Conditional operators and shortcut

courtesy of w3schools.com

Page 20: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   20 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  Arrays are zero based indexed collections of values – the values in an array can be of different types – and the values are comma separated in [ ]

§  For example: randomData= ["apple",true,10.346] then

§  randomData[0] would be the string "apple"

§  randomData[1] would be the Boolean value true

§  randomData[2] would be the number 10.346

§  To add a value, pick an index and set the value

§  if the index already exists, it'll overwrite that value

§  if the index doesn't exist, it'll create that value

§  if the new index leaves a gap, the gap index values will be undefined

§  for our example above

§  randomData[2]="fred" overwrites 10.346 with "fred"

§  randomData[5]=6.5 means randomData[3] and randomData[4] are null

Arrays

Page 21: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   21 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  We will be using a lot of JSON Objects (JavaScript Object Notation)

§  These are like arrays, but instead of being index based, they are based using key/value pairs

§  The syntax is comma separated key/value pairs inside {}. The key/value pairs are denoted with key:value

§  Note: the key is interpreted as a string and it's ok to write it with or without quotes

§  For example:

bodyParts = {hands:2, mouth:1, fingers:10, toes:10, tails:0, hair:"brown"}

§  bodyParts["hands"] would return 2

§  bodyParts["hair"] would return "brown"

§  bodyParts[0] would return null

§  bodyParts["heart"]=1 would set a key of "heart" and it's value would be 1

§  Note: explicitly typing keys as strings is fine too: bodyParts ={"hands":2, "mouth":1}

JSON Objects

key value

Page 22: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   22 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  BOTH arrays and JSON Objects need to be defined as arrays/objects before use

§  you can't just start out with a[1]=0

§  Arrays/JSON objects are objects, not types, so they need to be declared as such

§  You can nest arrays and JSON objects. For example:

fredinfo = {firstname:"fred", lastname="flinstone"}

people= ["wilma", "barney", fredinfo]

§  the array element people[2] returns the object defined as fredinfo

§  the array element people[2]["lastname"] returns "flinstone"

§  For arrays, you can check to see if there are any values with the .length method.

§  For example:

§  If a=[1,4,2,5] then a.length would return 4

§  if a=[] then a.length would return 0 and in this case, a is NOT null

Arrays and JSON Objects

note the nesting of index/key values

Page 23: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   23 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  Loops for a specific number of iterations

§  Here is the basic syntax:

for (statement 1; condition; statement 2) {

code to be executed }

§  where:

§  statement 1 is executed before the loop (not each iteration)

§  condition is checked and if true will execute the next iteration of the loop

§  statement 2 is executed after each iteration of the loop

§  For example:

cars = ["ford", "hyundai", "audi", "BMW"] for (var i=0; i<cars.length; i++) {

console.log (cars[i]); }

For loops

i is initialized to 0 for the first pass the i++ runs AFTER the code block executes.

Page 24: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   24 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  Loops indefinitely until a condition is met

§  Here is the basic while loop syntax:

while (condition) {

code to be executed }

§  where: condition is checked and if true will execute the next iteration of the loop

§  Here is another variation, the do…while loop:

do {

code to be executed } while (condition);

§  where: condition is checked and if true will execute the next iteration of the loop

§  Note, unlike the while loop, the do…while will execute once before checking the criteria

While loops

Page 25: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   25 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  JavaScript supports the try…catch block to catch any unexpected errors without crashing your app

§  The syntax is:

try { //your code } catch(err) { //your error handling code here }

§  The err object will contain the error information.

§  in our Chrome tool we'll only get a text string with the error information (error name and error message)

§  in a Kony app, you'll actually get an error object including the following properties:

§  sourceURL – the module name that contains the code that caused the error

§  name – the type of error

§  message – the actual error message

Try…Catch error handling

Page 26: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   26 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  For example:

function testErr() { try { a[xxx]=87; //bad line of code – didn't initialize a } catch(err) { console.log("error: " + err); } } testErr();

§  the single line of code in our function will throw an error:

Try…Catch error handling

Note: this "undefined" entry means that the function you called (i.e. testErr) didn't return a value so it's result is undefined – that is not an error

Page 27: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   27 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  If we run that same code in a Kony app, here is what the logs would say (iPhone example):

§  in our error handling code, for example, we could isolate just the error message by accessing err.message or just the name with err.name

§  You can also throw errors in your code forcing it down the catch path.

§  The syntax is simply: throw <something> where <something> can be a string, number, Boolean or an object

§  Your error handling code will have to know what to expect if you'll throw a custom error that is different than what might be thrown by the system

§  Let's look at an example of this…

Try…Catch error handling

Page 28: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   28 Copyright © 2013 Kony, Inc. CONFIDENTIAL

function testPrint(input) { try { if (input<5) { throw "too small!" } else { a[xxx]=87; } } catch(err) { if (err.message != null) { console.log("this error occurred: " + err.message); } else { console.log(err); } }

}

Try…Catch error handling example

if the input is less than 5, we throw a custom error that is only text

we know this line will throw a system error

we can check to see if the error object has a message attribute

if so, print the error's message info

if not, assume it's our text error message

cont…

Page 29: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   29 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  There is a better way…

§  Rather than throwing an error message, throw an error object so now the handling code gets much easier:

function testPrint(input) { try { if (input<5) { throw {message: "too small!", value:input, otherdata:"etc…"}; } else { a[xxx]=87; } } catch(err) { console.log("this error occurred: " + err.message); //more code to process other error values } }

§  Note: this will work for Kony apps that throw the error object, our Chrome tool won't work for this…

Throwing an error object

Throw the error object with message attribute and any other data we might need to know

we will now always get an error object with a message attribute -

Page 30: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   30 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  Let's put a few of these coding concepts to use in this exercise

§  The idea is to write code that loops through some data and prints out the results in nice formatted sentences

§  Start off using this exact code as your "data":

a={name:"Pedro",age:25,sport:"golf",cars:["BWM","Audi"]}; b={name:"Aida",age:32,sport:"checkers",cars:null}; c={name:"Igor",age:29,sport:"football",cars:["VW"]}; people = [a,b,c];

§  Write a function that displays THIS as the output when passed in the people data as input:

§  Solution shown on next slide if you need help…

Exercise – looping through data

Page 31: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   31 Copyright © 2013 Kony, Inc. CONFIDENTIAL

function printpeople(list) { for (var i=0;i<list.length;i++) { var display; display = list[i]["name"] + " is " + list[i]["age"] + " years "; display = display + " and loves to play " + list[i]["sport"];

if (list[i]["cars"] != null) { var cardisplay =""; for (var j=0;j<list[i]["cars"].length;j++) {

if (j==0) {cardisplay = list[i]["cars"][j];} else {cardisplay = cardisplay + ", " + list[i]["cars"][j];}

} display = display + " and has these cars: " + cardisplay; } else { display = display + " and has no cars"; } console.log(display); }

}

§  to call our function, we'd have one line, after the function definition: printpeople(people);

Exercise – looping through data solved our data is an array of JSON objects so we can iterate through it by index

check to make sure there are cars in the collection

start building our sentence using keys to get data

cars is also an array to loop through

know when to use ","

add cars to display text

text if no cars found

output our results

Page 32: JavaScript Tutorial

Copyright  ©  2010  Kony  Solu4ons,  Inc.    CONFIDENTIAL   32 Copyright © 2013 Kony, Inc. CONFIDENTIAL

§  JavaScript really doesn't care about white space in your code.

§  We can rewrite this example: function checkx(x) { if (x<=0) { console.log("x is too small"); } else if (x > 20) { console.log("x is too big"); } else { console.log("x is just right"); } }

§  As this: function checkx(x) { if (x<=0) {print("x is too small");} else if (x > 20){print("x is too big");} else {print("x is just right");}}

§  It really doesn't matter – follow whatever standards you want, the code all runs the same J

A note on style