JavaScript Day #2 The Boolean class The Boolean object represents two values: true and false. The following code creates a Boolean object called myBoolean: var myBoolean=new Boolean(); If the Boolean object has no initial value (as above), or if the passed value is one of the following: 0 -0 null "" false undefined NaN the object is set to false. Any value can be converted into a Boolean. However, unless it is one of the 7 values listed above, it will be converted into true (even with the string "false"!). Note that the fifth bullet item above is the value false, not the string "false"! console.log("0 as Boolean: " + Boolean(0)); console.log("-0 as Boolean: " + Boolean(-0)); console.log('"" as Boolean: ' + Boolean("")); console.log("null as Boolean: " + Boolean(null)); console.log("false as Boolean: " + Boolean(false)); console.log("NaN as Boolean: " + Boolean(NaN)); console.log("undefined as Boolean: " + Boolean(undefined)); console.log('"false" as Boolean: ' + Boolean("false")); You can also print Boolean values. Can you figure out why the following don't print the same thing? console.log("4==5: " + 4==5); console.log("4==5: " + (4==5)); null vs. undefined The values null and undefined are similar. A variable's value is undefined if it has never been assigned a value. A variable's value is null if it has been assigned the value null. Document1 1 2/10/2016 Type Conversions Java is a weakly-typed language. You will not get type-conversion errors when you try to assign a value of one type to another type. Here are some type conversions: Booleans Boolean type conversions: Boolean value true false Example console.log console.log console.log console.log As a string "true" "false" As a number 1 0 (true); (false); (Number( true)); (Number(false)); If you want a blank line, print an empty string: console.log(""); If you try this, you do not get a blank line: console.log(); Strings String type conversions: Value "" String that looks like a number, e.g. "2.5" Any other string As a Boolean false true As a number 0 the equivalent number, e.g. 2.5 true Numbers Number to Boolean: Zero converts to the Boolean false. Any other number converts to true (including Nan, Infinity, and -Infinity) Example console.log(Boolean(0)); console.log(Boolean(2.5)); Number to String: Any number converts to its corresponding string representation. Example console.log(2.5); Equality Because JavaScript automatically does type conversions, the following are legal: Document1 2 2/10/2016 null==undefined "0" == 0 0 == false "0" == false Whenever an expression has a string for at least one value and the "+" operator, everything in the expression is converted to a string. Explicit Conversions You can do explicit type conversions using the Number(), Boolean(), String(), or Object() constructor. Example To explicitly convert a string to a number: Number("2.5") To control the number of decimal places when outputting numbers, use the toFixed() method. Example n = 123.45678; console.log(n.toFixed(0)); //"123" console.log(n.toFixed(2)); //"123.45" console.log(n.toFixed(5)); //"123.45678" The parseInt() and parseFloat() global methods (they do not belong to any class) can be used to explicitly convert strings to integers or floating-point numbers. Both functions skip leading white space and parse as many characters as they can! Example console.log(parseInt(" 3 stooges")); // returns 3 console.log(parseInt("0xFF")); // returns 255 console.log(parseFloat(".1")); // returns .1 console.log(parseInt("0.1")); // returns 0! console.log(parseInt("0.999")); // returns 0! console.log(parseInt(".1")); // returns Nan! The fourth example converts "0.1" int a floating-point number and then truncates to make it an integer. The last example returns Nan because .1 is not an integer. Document1 3 2/10/2016 Expressions An expression is code that the interpreter can evaluate to a value. The simplest expressions are literals and variables. Example 1.2 "Hello" true false null x Array expressions Arrays can be initialized with array expressions. Example var list = [1, 2, 3, 4, 5]; var table = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]; Technically, table is not a 2D array. Rather, it is a 1D array whose elements are 1D arrays. Try printing them out: console.log(list); console.log(table); You get their type, not their values. Object expressions Objects can be initialized with an object expression. Example var point = {x:100, y:50}; console.log(point.x); console.log(point.y); Function definition expressions Example var square = function(x) { return x * x;}; console.log(square(20)); Document1 4 2/10/2016 Variables JavaScript variables are case-sensitive. JavaScript is not strongly typed. Variables are declared using the keyword var. Declaring variables is not required, but is considered a good programming practice. Example var x = 1; var y = 3.14159; Variables that are not initialized in the declaration are considered undefined (having no value, which is not the same as having a value of 0, or having the value null). JavaScript variables are dynamically typed. Example var x ; // Now x is undefined console.log(x); x = 5; // Now x is a Number console.log(x); x = "John"; // Now x is a String console.log(x); Declaring Variable Types When you declare a new variable, you can declare its type like this. The keyword new is optional. var carname=new String(); var x= new Number(); var y= new Boolean(); var cars= new Array(); var person= new Object(); console.log("carname: " + carname); console.log("x: " + x); console.log("y: " + y); console.log("cars: " + cars); console.log("person: " + person); Variable Scope Variables declared inside a function are local and are created when the function begins execution, and are deleted when the function ends execution. Variables declared outside of a function are global and are available to all of the script code and are only deleted when the web page is closed. Unlike C# and Java, there is no such thing as block-level scope (making a variable visible only within a {} block). If you declare a variable in a function (even within a block of the function), its scope is the entire function!. If you declare a variable outside of a function, its scope is global and it is available throughout the web page. NOTE: If you assign a value to variable that has not yet been declared, the variable will automatically be a global variable. Document1 5 2/10/2016 This statement: name="George"; will declare the variable name as a global variable , even if it is executed inside a function! Statements JavaScript allows compound statements or statement blocks. A compound statement or statement block is any list of statements surrounded by curly brackets {}. The var statement is used to declare variables. The function statement is used to declare functions. Assignment Statement/Operators Given that x=10 and y=5, the table below explains the assignment operators: Operator Example Same As Result = x=y += x+=y x=x+y x=15 -= x-=y x=x-y x=5 *= x*=y x=x*y x=50 /= x/=y x=x/y x=2 %= x%=y x=x%y x=0 x=5 Conditionals: The if statement The syntax for the if: if (expression) statement; else statement2; Except for the fact that the expression can be of any type, the if statement is the same as in C# and Java. Example var i = 10; if (i==10) console.log("i is 10"); else console.log("i is not 10"); Conditionals: The switch statement The syntax for the switch: Document1 6 2/10/2016 switch(<expression>) { case <value1>: statements; break; case <value2>: statements; break; ... default: statements; break; } When looking for a matching case value, strict equality (===) is used! Example In the example below, note that I am re-declaring the variable i. This is ok in JavaScript! var i=10; switch(i) { case 5: console.log("it's 5!"); break; case 10: console.log("it's 10!"); break; default: console.log ("it's neither!"); } console.log("Done with switch.\n"); Loops JavaScript has four kinds of loops: for- loops through a block of code a number of times for/in- loops through the properties of an object while- loops through a block of code while a specified condition is true do/while- also loops through a block of code while a specified condition is true Loops: The for loop The for loop is identical to C# and Java except it doesn't allow you to declare the loop variable in the initialize section of the loop. It must be declared previously. Syntax: for (initialize; test; increment) statement; The for loop was made for arrays. Example // Print 1 to 10 Document1 7 2/10/2016 for (i=1; i<=10; i++) { console.log("number " + i.toString()); } The loop in this example shows how a "boolean" in JavaScript can be anything. Also note that i goes off the end of the array without an error! cars=["BMW","Volvo","Saab","Ford"]; var i=0; for (;cars[i];i++) console.log(cars[i]); console.log("After the loop, i is " + i + " Loops: The for…in loop We will look at this later. Loops: The while loop The while loop loops through a block of code as long as a specified condition is true. The syntax for the while loop: while (expression) statement; Example var i=10; while (i>0) { console.log(i); i-- ; } console.log("Done with while loop.\n"); Loops: The do while loop The do…while loop is similar to the while loop except that, since the test is at the bottom of the loop, the body will always get executed at least one time. The syntax for the do while loop: do { code block to be executed } while (boolean); NOTE: If there is more than one statement in the loop, the statements must be enclosed in curly brackets {}. If there is only one statement, the curly brackets are optional. Example var i = 0; do { i++; console.log(i); } while (i<10); Document1 8 2/10/2016 console.log("Done with do while loop.\n"); Document1 9 2/10/2016 JavaScript Data Classes JavaScript has four basic data classes: Number String Boolean Object The first three are primitives, but all primitive values have object equivalents which wrap around the primitive (these are called wrapper classes) and allow it to be treated as an object. Some Number Object Methods Method Description toExponential(x) Converts a number into an exponential notation toFixed(x) Formats a number with x numbers of digits after the decimal point. Does not change x. toString(x) Converts a Number object to a string Example n = 1.2345 m = n.toFixed(2); console.log("n is: " + n + ". m is: " + m); The Object class In JavaScript, an object is a collection of values (properties).An object is delimited by curly braces. Inside the braces the object's properties are defined as name and value pairs (name : value). The properties are separated by commas (w3): var person= { firstname:"John", lastname:"Doe", id:5566 }; The object (person) in the example above has 3 properties: firstname, lastname, and id. Spaces and line breaks are not important. Your declaration can span multiple lines. Example You can access an object's properties in one of two ways: either with the dot notation or using array-like notation with the property name as a string enclosed by square brackets. name=person.lastname; name=person["lastname"]; You can also create your own objects. Document1 10 2/10/2016 Example This example creates an object called "person", and adds four properties to it: person=new Object(); person.firstname="John"; person.lastname="Doe"; person.age=50; person.eyecolor="blue"; console.log(person.firstname); console.log(person.lastname); console.log(person.age); console.log(person.eyecolor); Document1 11 2/10/2016 Some other helpful classes The JavaScript Date class JavaScript has a built-in Date class. The Date object is used to work with dates and times. Date objects are created with the Date() constructor. There are four ways of initiating a date. 1. To get the current date/time: d1 = new Date(); // current date and time 2. Pass in the number of milliseconds that have passed since 1/1/1970 and JavaScript will give you the date/time: d2 = new Date(100000000); //milliseconds since 3. Pass in a date string: d3 = new Date("9/11/2001"); 4. Pass in a year, month, day, hour, minutes, seconds, milliseconds: d5 = new Date(2013, 2, 5, 10, 15, 15, 500); All arguments after the first three are optional: Example d4 = new Date(2013, 2, 5); console.log(d1); console.log(d2); console.log(d3); console.log(d4); console.log(d5); //2 is March! Example Getting the year: var d = new Date(); console.log(d.getFullYear()); Example Getting the time: var d = new Date(); document.write(d.getTime()); This gets the number of milliseconds since 1/1/1970. More Date methods (this is not a comprehensive list): Function Description Returned Values getdate() getUTCDate() Day of the month 1-31 getday() getUTCDay() Day of the week (integer) 0-6 Document1 12 2/10/2016 getFullYear() getUTCFullYear() Year (full four digit) 1900+ getHours() getUTCHours() Hour of the day (integer) 0-23 getMinutes() getUTCMinutes() Minutes (since last hour) 0-59 getMonth() getUTCMonth() Month 0-11 getSeconds() getUTCSeconds() Seconds (since last minute) 0-59 getTime() Number of milliseconds since 1/1/1970 Remember that UTC is Coordinated Universal Time (it's not an English acronym) The Englishspeaking countries wanted CUT (Coordinated Universal Time), and French-speaking countries wanted TUC ("temps universel coordonné". The end result was UTC! Document1 13 2/10/2016