Tom Kleen



JavaScript Day #2The Boolean classThe 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-0null""falseundefinedNaNthe 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. undefinedThe 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. Type ConversionsJava 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:BooleansBoolean type conversions:Boolean valueAs a stringAs a numbertrue"true"1false"false"0Exampleconsole.log (true);console.log (false);console.log (Number( true)); console.log (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();StringsString type conversions:ValueAs a BooleanAs a number""false0String that looks like a number, e.g. "2.5"truethe equivalent number, e.g. 2.5Any other stringtrueNumbersNumber to Boolean:Zero converts to the Boolean false. Any other number converts to true (including Nan, Infinity, and -Infinity)Exampleconsole.log(Boolean(0));console.log(Boolean(2.5));Number to String:Any number converts to its corresponding string representation.Exampleconsole.log(2.5);EqualityBecause JavaScript automatically does type conversions, the following are legal:null==undefined"0" == 00 == false"0" == falseWhenever an expression has a string for at least one value and the "+" operator, everything in the expression is converted to a string.Explicit ConversionsYou can do explicit type conversions using the Number(), Boolean(), String(), or Object() constructor. ExampleTo explicitly convert a string to a number:Number("2.5")To control the number of decimal places when outputting numbers, use the toFixed() method.Examplen = 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!Exampleconsole.log(parseInt(" 3 stooges"));// returns 3console.log(parseInt("0xFF"));// returns 255console.log(parseFloat(".1"));// returns .1console.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.ExpressionsAn expression is code that the interpreter can evaluate to a value.The simplest expressions are literals and variables.Example1.2"Hello"truefalsenullxArray expressionsArrays can be initialized with array expressions.Examplevar 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 expressionsObjects can be initialized with an object expression.Examplevar point = {x:100, y:50};console.log(point.x);console.log(point.y);Function definition expressionsExamplevar square = function(x) { return x * x;};console.log(square(20));VariablesJavaScript 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.Examplevar 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.Examplevar x ;// Now x is undefinedconsole.log(x);x = 5;// Now x is a Numberconsole.log(x);x = "John";// Now x is a Stringconsole.log(x);Declaring Variable TypesWhen 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 ScopeVariables 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.This statement:name="George";will declare the variable name as a global variable , even if it is executed inside a function!StatementsJavaScript 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/OperatorsGiven that x=10 and y=5, the table below explains the assignment operators:OperatorExampleSame AsResult=x=y?x=5+=x+=yx=x+yx=15-=x-=yx=x-yx=5*=x*=yx=x*yx=50/=x/=yx=x/yx=2%=x%=yx=x%yx=0Conditionals: The if statementThe 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.Examplevar i = 10;if (i==10) console.log("i is 10");else console.log("i is not 10");Conditionals: The switch statementThe syntax for the switch:switch(<expression>){case <value1>: statements; break;case <value2>: statements; break;...default: statements; break;}When looking for a matching case value, strict equality (===) is used!ExampleIn 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");LoopsJavaScript has four kinds of loops:for- loops through a block of code a number of timesfor/in- loops through the properties of an objectwhile- loops through a block of code while a specified condition is truedo/while- also loops through a block of code while a specified condition is trueLoops: The for loopThe 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 10for (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 loopWe will look at this later.Loops: The while loopThe 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;Examplevar i=10;while (i>0){ console.log(i); i-- ;}console.log("Done with while loop.\n");Loops: The do while loopThe 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.Examplevar i = 0;do{ i++; console.log(i);}while (i<10);console.log("Done with do while loop.\n");JavaScript Data ClassesJavaScript has four basic data classes:NumberStringBooleanObjectThe 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 MethodsMethodDescriptiontoExponential(x)Converts a number into an exponential notationtoFixed(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 stringExamplen = 1.2345m = n.toFixed(2);console.log("n is: " + n + ". m is: " + m);The Object classIn 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.ExampleYou 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. ExampleThis 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);Some other helpful classesThe JavaScript Date classJavaScript 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.To get the current date/time: d1 = new Date(); // current date and timePass 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 sincePass in a date string: d3 = new Date("9/11/2001");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); //2 is March! console.log(d1); console.log(d2); console.log(d3); console.log(d4); console.log(d5);ExampleGetting the year:var d = new Date();console.log(d.getFullYear());ExampleGetting 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):FunctionDescriptionReturned Valuesgetdate() getUTCDate()Day of the month1-31getday() getUTCDay()Day of the week (integer)0-6getFullYear() getUTCFullYear()Year (full four digit)1900+getHours() getUTCHours()Hour of the day (integer)0-23getMinutes() getUTCMinutes()Minutes (since last hour)0-59getMonth() getUTCMonth()Month0-11getSeconds() getUTCSeconds()Seconds (since last minute)0-59getTime()Number of milliseconds since 1/1/1970?Remember that UTC is Coordinated Universal Time (it's not an English acronym) The English-speaking countries wanted CUT (Coordinated Universal Time), and French-speaking countries wanted TUC ("temps universel coordonné"). The end result was UTC! ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download