Quiz guide

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Explain what happens when a keyword like "var" is use with a different case, such as "VAR".

All keywords in JavaScript are case sensitive. Using a keyword incorrectly will result in an Error being thrown.

Explain how various array methods are used, including: concat, join, pop, push, reverse, slice, sort, splice, and toString.

Certain methods change the array they are called from (pop, push, sort, splice, reverse) while others return a new array (concat, slice) or a string representation of the array (join, toString) without modifying the original array.

String to Number

n = s - 0; n = +s; n = Number(s); // Base 10 number, whitespace ok n = parseInt(s,base); //Parse integer using base n = parseFloat(s); //Parse from beginning of string InfoBubble.gif Note: Strings that cannot be converted to numbers will result in NaN

Does epic box primitives?

no. because unboxing is not consistent

Explain what could happen if JavaScript files are not loaded in the intended order

You may end up attempting to use a code construct, such as a class or function, before it is defined. This will likely result in an error being thrown.

Explain how various string methods are used, including indexOf, substring and split.

indexOf(subString,start) - Locate the position of the first occurrence of the substring at or after the starting postion (optional). substring(start,end) - Return a substring starting from start and ending at but not including end. If end is not specified, the entire remaining string is returned. A negative start or end is treated as zero if start>end, the values are swapped split(delimiter,limit) - Splits a string at the given delimiter to an array of strings, with a maximum number of elements equal to the limit (optional).

From Boolean

true String: "true" Number: 1 false String: "false" Number: 0

Describe the difference between a class property and an instance property in JavaScript

A class property is accessed through the constructor function of an object, while an instance property is accessed through objects created from the constructor function. Instance properties include properties defined in the prototype. For example: var MyClass=function(){}; MyClass.prototype = {instanceProperty:"This is an instance property"}; MyClass.classProperty = "This is a class property"; var myObject = new MyClass(); myObject.instanceProperty; //"This is an instance property" MyClass.classProperty; //"This is a class property" Instance properties can be added to the prototype after it is initialized. This allows one script file to extend a class defined in another: MyClass.prototype.newInstanceProperty = "This is also an instance property of current and new objects created from MyClass"; myObject.newInstanceProperty; //"This is also an instance property of current and new objects created from MyClass" var mySecondObject=new MyClass(); mySecondObject.newInstanceProperty; //"This is also an instance property of current and new objects created from MyClass" Instance properties that are specific to one object, not all objects of the class, can be added directly to that object: myObject.individualInstanceProperty = "Other objects of MyClass won't have this"; typeof mySecondObject.individualInstanceProperty; //"undefined" This same feature can be used to mask the default value of an instance property defined on the prototype with a value that is specific to a single instance. Note: Instance properties added to the prototype are not copied to instances of the class. Instead, the prototype is accessed only if the instance doesn't already have it's own specific copy of the property. For details, see: accessing an instance property.

Describe the difference between a closure and a non-closure function

A closure is created when one function returns another. The reason that this is significant is that the returned function must remember the variables that were available locally at the time the closure was created. This is known as the closure's context: function nonClosureFunction(a) { ///<summary>This is a non-closure function that returns a closure function</summary> return function(b) { return a+b; } } var closureFunction = nonClosureFunction(5); closureFunction(2); // returns 7 Notice that from the point it is created, closureFunction will always remember that the value of a is 5, since a is part of its context.

Describe the difference between the different date piecing methods: getDate, getDay, getMonth and getYear

A date represents the number of milliseconds since midnight (UTC) on 1/1/1970. To piece a date, use the following methods. In each case, if UTC is omitted, then the local time zone is used:aDate.get[UTC]FullYear()Returns the 4-digit year all 0 indexed except day of the month which is 1 to 31. 0 sunday to 6 saturday. 0 to 23 for hours. 0 to 999 for milliseconds

Describe the difference between the try, catch and finally keywords and explain how they are used.

All three keywords are used when dealing with errors. Errors are thrown using the following syntax: throw new Error("message");Use try around code that you suspect may throw an error, and catch to capture that error and respond to it:If there is code that must run regardless of if there was an error, include it with finally Note: There are other kinds of errors. Use the instanceof keyword to check for a particular kind of error. Examples include: EvalError RangeError ReferenceError SyntaxError TypeError URIError

Describe the difference between an array and an object

An array is, in fact, an object: typeof {}; //"object" typeof []; //"object" They both can contain arbitrary key-value pairs: function showProperties(obj) { var str = "{"; for(prop in obj) { str += prop + ":" + obj[prop] + ","; } return str.length === 1?"{}":str.substr(0,str.length-1) + "}"; } var myObject = {0:"a", 1:"b", 2:"c", prop:"val"}; var myArray = ["a", "b", "c"]; myArray.prop="val"; showProperties(myObject); // "{0:a,1:b,2:c,prop:val}" showProperties(myArray); // "{0:a,1:b,2:c,prop:val}" The differences of an array include the methods added by the Array class, as well as the special handling of the Array's length property.

Explain what happens when an undeclared and uninitialized variable is used in an expression.

An error is thrown. For example: var a = 1, b = a + c; // c is undeclared and not initialized, so an error is thrown var c, a = 1, b = a + c; // c is declared, so an error is not thrown, but b is NaN because c is still undefined

Describe what an object literal is and how it is used

An object literal is a shorthand notation used to describe objects in JavaScript. The basic syntax for an object literal is: {key1:val1, ..., keyN:valN} Where key can be any legal identifier that is unique within the object, and value can be any valid JavaScript value, including another object literal. If quotes are placed around the key, then the key can be any unique string: Object literals are the preferred way to define and initialize objects, because they are concise and easy to read. For example, this object: var myObject = new Object(); myObject["property One"] = 1; myObject.prop2 = 2; myObject.func1 = function() { alert("function 1"); }; myObject.array1 = new Array("a","b","c"); Can easily be converted into an object literal: var myObject = { "property One": 1, prop2: 2, func1: function() { alert("function 1"); }, array1: ["a", "b", "c"] }; Object literals are commonly used for the following tasks: Defining class prototypes Creating one-off, classless objects

To Boolean

Boolean(x) or !!x Number x is 0 or NaN: false otherwise: true String x is an empty string: false otherwise: true Object, Function or Array x is null or undefined: false otherwise: true Note: When null is converted to a number, the result is 0. When undefined is converted to a number, the result is NaN.

List the built in data types of javascript

Boolean,Number,String,Object,Function,Array, undefined

Describe the difference between Boxing and Unboxing primitives and explain when each occurs.

Boxing is the process of taking a primitive Number, Boolean or String value and wrapping it in an instance of that class, while unboxing is the process of extracting the primitive value from the wrapper object, usually by calling the valueOf method. Boxing never happens without explicitly creating a new instance of Number, String or Boolean. Unboxing will happen automatically in some cases, but not in others. For example:Automatic var boxedNum = new Number(5); var newNum = boxedNum + 5; //Results in 10 Not automatic var boxedBool = new Boolean(false); if(boxedBool) { alert("true"); } //Outputs true if(boxedBool.valueOf()) { alert("true"); } //Does not output true Note that the first alert in the Not Automatic example will always output true, regardless of the contained primitive value, because boxedBool is a non-null, non-undefined object.

Explain what happens when a property on an instance of a class is accessed

First, the object itself is checked to determine if the property exists directly on the object. If not and the object is an instance of a class, then the prototype of the class is checked for the property. For example: In the previous example, prop1 is part of the prototype of the class of myObject, so myObject.prop1 returned 1. However, if prop1 is set directly on myObject, then that value will be returned instead: Finally, if prop1 is deleted from myObject, then the prototype value is once again returned:

Explain what happens when an object is converted to a string

For most built-in classes, a reasonable string conversion will take place automatically: Array "String: " + ["a", "b", "c"]; "String: a,b,c" String "String: " + new String("abc"); "String: abc" Number "String: " + new Number("42"); "String: 42" Boolean "String: " + new Boolean(false); "String: false" However, for custom objects and instances of custom classes, the default toString method for an object will be called, unless it explicitly is overridden by the object or class: Default Object toString "String: " + {}; "String: [object Object]" Object overriding toString "String: " + {toString:function(){return "Hello world!"}}; "String: Hello world!" Class overriding toString var myClass = function() {}; myClass.prototype = { toString: function() { return "Hello world"; }}; "String: " + new myClass(); "String: Hello world"

Explain how you can create an anonymous function to be called immediately or stored for later use.

Functions are created using the function keyword, which has the following syntax: function Name(parameters) { // body } Name(arguments); // Calling the function (function(parameters) { // body })(arguments); var func = function(parameters) { // body }; func(arguments);

Describe the difference between an if-else code block and a switch-case code block and explain when you would use one over the other.

In addition to the syntax differences, the switch-case structure is better in terms of clarity and performance when the set of checks can be reduced to comparing one expression against a discrete set of constant values. When the conditions are not constants, an if-else structure is the only option. For example, in the following situation, the switch-case option is better: function getUrl(selectionString) { switch(selectionString) { case "userweb": return "http://userweb.epic.com"; break; case "brainbow": return "http://brainbow/"; break; case "home": case "guru": return "http://guru/"; break; default: return "http://www.epic.com"; break; } } If-else: function getUrl(selectionString) { if(selectionString==="userweb") { return "http://userweb.epic.com"; } else if(selectionString==="brainbow") { return "http://brainbow/"; else if(selectionString==="guru" || selectionString==="home") { return "http://guru/"; } else { return "http://www.epic.com"; } }

Describe the difference between initializing a variable without declaring it and declaring a variable without initializing it.

Initializing a variable without declaring it In this case, the variable globalVar will become globally available as soon as initializeWithoutDeclaring is executed: function initializeWithoutDeclaring() { globalVar = "test"; //Notice that the var keyword is missing } function alertTheVariable() { alert(globalVar); } initializeWithoutDeclaring(); //Initializes globalVar alertTheVariable(); // Displays "test" in an alert popup Declaring a variable without initializing it In this case, the variable will be local if it was declared within a function, or global if declared outside a function. In either case, its value is undefined until it is initialized. var globalVar; function test() { var localVar; alert(localVar); localVar="local"; alert(localVar); } alert(globalVar); //Displays "undefined" globalVar="global"; alert(globalVar); //Displays "global" test(); //Displays "undefined" followed by "local" alert(localVar); //Will not compile as localVar is out of scope

Describe the kind of methods available in the Math object

Math contains properties for mathematical constants as well as static functions for mathematical functions. Math is an object not a class, so it has no constructors. [edit] Math.E Math.PI abs ceil exp floor log max min pow(x,y) x to the power of y random round sqrt

Describe the difference between an operator (+,-,*,/,%,^) and an operator-assignment (+=,-=,*=,/=,%=,^=)

The assignment version of the operator both performs the operation on the right-hand and left-hand operands, and assigns the result to the left-hand operand. For example, the following two expressions are equivalent: a = a + b; a += b;

Explain how you can determine if a number is valid and finite

The best way to perform this test is the isFinite function: Example Equivalent Expression Result isFinite(+"5"); isFinite(5); true isFinite(+"abc"); isFinite(NaN); false isFinite(5/0); isFinite(Infinity); false isFinite(-5/0); isFinite(-Infinity); false

Explain what happens when a variable that is part of a closure's context is modified

The context of a closure can only be modified from within the closure itself, at least with value types. Any changes made to context variables will be remembered by the closure the next time it is called: Note: You can still access reference types that are included in a closure's context, provided that you have a local copy of the reference: function createIncrementerStartingAt(a) { ///<summary>This is a non-closure function that returns a closure function</summary> return function() { return a.num++; } } var args = {num:5}; var incrementer = createIncrementerStartingAt(args); incrementer(); // returns 5 args.num =10; incrementer(); // returns 10

Describe the difference between "in" and "hasOwnProperty"

The in operator does not distinguish between a property stored directly on an object and a property from the object's prototype: On the other hand, hasOwnProperty only returns true for properties directly on the object: Note: Because in is so permissive, JsHint complains about for-in loops that don't mask the properties being accessed. One way to apply the masking is: for(prop in obj) { if(obj.hasOwnProperty(prop)) { // Code using the property } }

Describe the difference between the operators ==, ===, != and !==

The operators "is equal to" (==) and "is not equal to" (!=) will perform a type conversion before evaluating equivalence. The operators "is identical to" (===) and "is not identical to" (!==) will not perform a type conversion first. For example: Expression Result Expression Result 5==5 true 5=="5" true 5!=5 false 5!="5" false 5===5 true 5==="5" false 5!==5 false 5!=="5" true Because the conversion rules for == and != are complex and non-intuitive, it is Epic's convention to always use === and !== instead.

Describe the difference between creating a new array using the new keyword vs. the square-bracket notation

The only difference is the superficial syntax differences between the two methods: var ary1 = new Array(1,2,3,4); var ary2 = [1,2,3,4]; ary1 instanceof Array; //true ary2 instanceof Array; //true InfoBubble.gif Note: By convention, Epic prefers the square-bracket notation because it is more concise

Explain what happens when a property is deleted from an object

The property is completely removed from the object. Accessing the property again will return undefined, which is the same as accessing a property that was never in the object. var obj={a:1, b:2, c:3}; showProperties(obj); //"{a:1,b:2,c:3}" "b" in obj; // true delete obj.b; showProperties(obj); //"{a:1,c:3}" "b" in obj; // false

Explain what happens when a string and number are compared using a relational operator.

The string will be converted to a number before the comparison takes place. If the string is non-numeric, then the conversion will result in NaN and the comparison will always be false: Expression After Conversion Result 5<"1" 5<1 false 5>"1" 5>1 true 5<"a" 5<NaN false 5>"a" 5>NaN false

Describe the difference between a while loop and a do-while loop

The while loop checks the condition before the first loop iteration: The do-while loop executes the first iteration, and then checks the condition:

Explain how JavaScript can be included in a page

There are three ways that JavaScript can be added to a page: As a separate file, included using <script type="text/javascript" src="MyFile.js"></script> As an in-line script, included using <script type="text/javascript">alert("this is a test");</script> As part of an HTML element's attribute. For example: <span onclick="javascript:alert('this is a test');">Click me!</span> The first option is preferred by Epic because it is the most decoupled from the content of the page, making it the most extensible. InfoBubble.gif Note: Various frameworks offer alternate ways to include external scripts. For example, ASP.NET uses the ScriptManager control

Describe the difference between the Logical AND and the logical OR operators, and give examples of their output.

Unlike most languages, the result of the logical AND/OR operators is not always true or false: A = B || C; //A is assigned B if B is true when converted to a Boolean. Otherwise A is equal to C A = B && C; //A is assigned B if B is false when converted to a Boolean. Otherwise A is equal to C Notice that A takes on the actual value of B or C, not the Boolean conversion of B or C. This leads to some interesting examples: Expression Result document.write("abc"||"123"); "abc" document.write("abc"&&"123"); "123" One situation where this unique behavior of the logical OR operator is used is when you want to initialize a variable only if it hasn't already been initialized: var myVar = myVar || {}; In this example, myVar will be assigned back to itself if it already exists as a non-null object. Otherwise, if it is null or undefined, it will be initialized to a new object.

Explain how inheritance works in JavaScript and trace its execution through the child and parent class code.

Unlike other object-oriented programming languages, JavaScript doesn't natively support inheritance in its syntax. However, you can get many of the same code-reuse advantages of inheritance by chaining prototypes together. You can either define your own inherit method for this, or use a third-party library, such as Microsoft Ajax.

Difference between strong and weak typing

Weak typing (used by JavaScript) means that a variable can contain any kind of data, while strong typing means a variable may only contain the kind of data specified.

Explain what happens when you use the "+" and "+=" operators with a string

When the plus operator (+) is used with a string as either operand, the other operand will be converted to a string and the two operands will be concatenated together. For example: "abc" + 123 "abc123" "abc" + true "abctrue" "abc" + null "abcnull" "abc" + undefined "abcundefined" "abc" + {} "abc[object Object]" The add-assign operator (+=) also concatenates, but additionally assigns the result back to the left-hand operand.

Describe the difference between the length property of arrays and functions

With arrays, the length property is adjusted whenever elements are added to the array. It doesn't actually reflect the number of values in the array, only the position of the maximum value. Also, the length property of an array can be set to adjust the elements contained in the array. For example: var ary=[1,2,3]; //ary = [1, 2, 3] ary.length = 3 delete ary[2]; //ary = [1, 2, ] ary.length = 3 ary[5]="test"; //ary = [1,2, , , , "test"] ary.length = 6 ary.length=2; //ary = [1,2] ary.length = 2 With functions, the length property represents the number of named parameters: var myFunction = function(a,b,c) {}; //myFunction.length = 3 Setting the length of a function has no effect. Note: Remember, you can pass more arguments than parameters to a function. Additional arguments can be accessed through the arguments array

Number to STring

s = n + ""; s = String(n); s = n.toString(); // base 10 s = n.toString(base); // given base

how does slice work?

slice(start,end) - Selects the elements starting at the given start argument, and ends at, but does not include, the given end argument. var ary=[0,1,2,3,4]; var ary2=ary.slice(2,4); //ary2=[2,3]

how does splice work?

splice(index,howMany,item1,...,itemN) - Adds/removes items to/from an array, and returns the removed item(s). var chars = ["B", "O", "A", "M"]; chars.splice(2,0,"L","K"); // returns [], chars=["B","O","L","K","A","M"] chars.splice(0,1); // returns ["B"], chars=["O","L","K","A","M"] chars.splice(3,2,"B"); // returns ["A","M"], chars=["O","L","K","B"]

Describe the difference between the typeof and instanceof keywords

typeof is a unary operator that returns the string representation of the primitive JavaScript type of a value. The only possible results of typeof are "number", "string", "boolean", "object", "function" and "undefined". For example: typeof 1; // "number" typeof "test"; // "string" typeof true; // "boolean" typeof new Date(); // "object" typeof function(){}; // "function" typeof null; // "object" typeof undefined; // "undefined" On the other hand, instanceof is an operator with two operands that returns a boolean. The result is true if the left-hand operand is an object created from the constructor function on the right-hand operand. For example: 1 instanceof Number; //false new Number(1) instanceof Number; //true "test" instanceof String; //false new String("test") instanceof String; //true [] instanceof Array //true

Explain how the value of object properties can be accessed using a for-in loop

var obj={a:1, b:2, c:3}, prop, value; for(prop in obj) { value=obj[prop]; alert(value); }


Kaugnay na mga set ng pag-aaral

Exam 6 Mobility -Immobility Prep U

View Set

Chapter 08: Communication and Conflict

View Set

Health Assessment PrepU Chapter 3

View Set

History of Economic Thought Final Exam

View Set

Bus 242 Chapter 29 Computer privacy and speech

View Set