Javascript Flashcards
How many types of number does Javascript have?
A single number type (represented by a 64bit float internally)
Is NaN equal to NaN?
No - it is equal to nothing else, therefore the only way to test for it is to use the function isNaN(number)
In Javascript, is ‘C’ + ‘a’ + ‘t’ === “Cat”?
Yes
Do strings have methods?
Yes - think of things like String1.toUppercase();
In Javascript do blocks create new scope?
No - so variables should be declared at the top of a function
What values typically evaluate to false?
false, null, undefined, ‘’, 0, NaN
What does the string ‘false’ evaluate to in Javascript
True
What is the ‘for in’ structure in Javascript?
A for loop.
for (var myvar in obj) { // Loop through }
What is a label in a break statement?
You can break to another location (labelled by label). i.e.
break myLabel;
What are the simple types in JavaScript?
numbers, strings, booleans, null and undefined
Are numbers, strings and booleans objects?
No - but they do have methods
Objects in JavaScript are…
Mutable keyed collections
Do you need to have a class in JavaScript to create an object?
No, objects in JavaScript are class free.
What is an object literal?
A pair of curly braces surrounding zero or more name/value pairs. i.e.
var empty_object = { };
var stooge = {
“first-name”: “jerome”,
“last-name”: “Howard”
};
What names must be enclosed in quotes in an object literal?
Names that don’t conform to normal variable naming conventions.
How do retrieve a variable from an object literal?
Using the [ ] operator
myObj[“name”]
How can you fill in a “default” value when assigning a value from an object literal?
var val = obj[“first-name”] || “(none)”;
(i.e. it will either provide the first-name element of the object or “(none)”
What happens when you try to retrieve values from “undefined”?
Throws a TypeError exception.
How do you prevent JavaScript throwing an exception when you accidentally try to access an element of an object that is undefined?
Use the && operator
flight.equipment // undefined
flight.equipment.model // throw “TypeError”
flight.equipment && flight.equipment.model // undefined
(I guess it fails on the left hand operand like other languages and doesn’t execute the right hand operand)
Objects in Javascript are passed by…
reference
What does setting “defer” on a script tag do?
It indicates to the browser that the script can start downloading immediately, but it wont’ be run until the page is loaded. It should only be used when using external
How would you specify the defer attribute in XHTML?
defer=”defer”
What is the async attribute used for?
To specify that a script can be run as soon as it is loaded (not wait for the page)
What is the potential issue with having multiple external scripts labeled as async?
They may run out of order, so there should be no dependancies between them.
What options are available to prevent code being interpreted as HTML when embedding javascript in XHTML?
Use the html codes for > or < signs (or they will be interpreted as tags) - or use < ! [CDATA [ block
What is quirksmode?
It was a mode that IE used in version 5.5 - turning it on made it behave like I.E. 5 (non-standard) and switching it to standards mode (5.5) made it behave in a more standards compliant way.
In ANY browser, how do you turn off quirksmode?
By adding a correct doctype. (i.e. HTML 4.01 strict, XHTML or HTML5)
In ANY browser, how do you enable “almost standards mode”?
By using the transitional and frameset doctypes
What is the only only element that can be included in the body tag, but not in the noscript tag?
script
How do you inform a user that they require a javascript enabled browser?
By using the noscript tag < body> < noscript> < p>You require Javascript dude > < /noscript> < / body>
The first letter of a Javascript identifier must be…
a letter, an underscore or a dollar sign
How do you enable strict mode in Javascript?
Place
“use strict”
at the top of the script
Is it possible to leave out the ‘;’ in a statement?
Yes - although not recommended.
Variables in javascript are ….. typed.
Loosely
Is the following valid? var message = "hi"; message = 100;
Yes - but not recommended (you are changing the type of the variable, which could be confusing)
What is the difference between using var and not using var to declare a variable?
Using var makes the variable local to the block. I.e.
function foo() { var message = "Hi"; }
message will be destroyed when execution leaves that function block.
Global variables (declared without using var) are not recommended - how do you detect their use in your code?
By setting “use strict” on the script, a ReferenceError will be thrown
How do you declare multiple variables in a single line?
var message = "hi", found = false, age = 29;
If you have received the following the error - what happened?
Uncaught SyntaxError: Unexpected eval or arguments in strict mode
You declared a variable named eval or arguments in strict mode (which is not allowed).
What operator do you use to determine the type of a variable?
typeof varName;
What results does typeof return?
undefined boolean string number object function
Functions are considered …… in ECMAscript?
objects (although they have some unique properties to themselves)
If a variable is declared using var and not assigned anything, what is it’s value?
undefined
Should you ever explicitly set the value of a variable to undefined?
No - setting them to null is fine - but not to undefined
How do you convert a variable to a boolean type?
Use the boolean casting function
Boolean(var);
What types are converted to true if passed to the Boolean function (and consequently an if statement)?
true
Any non-empty string
Any non-zero number including infinity (negative numbers too)
Any object
What types are converted to false if passed to the Boolean function (and consequently an if statement)?
false (empty string) 0, NaN null undefined
Is this a valid octal number? var octalNum2 = 079;
No - there is a number 9 in there, which is out of range for a valid octal number - the 0 will be discarded and the number will be 79
Is this a valid octal number? var octalNum1 = 070;
Yes - the leading 0 is important to tell Javascript that this is an octal number (and the numbers are within range (0-7))
Numbers using octal or hex format are treated as ….. in all artithmetic operations?
decimal
There is only one numeric type in Javascript (number) how do you define a floating point number?
Just give it a decimal. var floatNum = 1.1;
ECMAScript always looks for ways to convert floats back to ints, why is that?
They take twice as much memory as an int.
How do you determine the smallest and largest numbers that can be represented in ECMAScript?
Number.MIN_VALUE;
Number.MAX_VALUE;
What does the following expression return?
NaN == NaN
False (NaN is not equal to ANYTHING)
How do you test if a number is NaN?
isNaN(variable);
What happens if you apply isNaN to an object?
The objects method “valueOf()” is called, if that doesn’t work, then it calls the “toString()” method
What are the three functions used to convert non-numeric values to numbers?
Number()
parseInt()
parseFloat()
What unary operator works the same way as the Number() function?
Unary +
What is wrong with the following statement - and how would you fix it?
parseInt(“070”);
The user may be intending 070 to be parsed as an octal number. However, it will be parsed as a string and give 70. To fix it pass parseInt the radix
parseInt(“070”, 8);
What is the difference between parseInt and parseFloat?
There is no radix mode as parseFloat only ever parses decimal values.
Are strings mutable or immutable in ECMAScript?
immutable
How do you convert a value to a string?
Most values have a .toString() method -
var age = 11;
age.toString();
Or add an empty string to it…
age + “”;
NOTE: When used on a number, you can pass it the radix of the value to convert to binary etc.
What does the hasOwnProperty method do on an object?
Checks to see if the method being queried exists on that object, and not part of a prototype
What are the base methods for an object in ECMAScript?
constructor hasOwnProperty(propertyName) isPrototypeOf(object0 propertyIsEnumerable(propertyName) toLocaleString() toString() valueOf()
(All objects have these in ECMAScript)
What happens in this instance?
var stringNum = “1”;
++stringNum;
stringNum is converted to a string then incremented.
What happens in the following instance? var stringNum = "1"; var num = +stringNum;
The value of stringNum is converted to a number and assigned to num.
Can the order that object properties appear in a “for-in” statement be predicted?
No, object properties are unordered in ECMA script
What is the ‘with’ statement?
A convenience statement, it basically negates the need to explictly call an object repeatedly in a given block of code // NOTE: search, hostname and href // are properties of location with(location) { var qs = search.substring(1); var hostname = hostname; var url = href; }
When is using the with statement invalid and an error?
In strict mode, it is not allowed (NOTE: It also has a negative impact on performance, and makes debugging difficult) - not good in production code
What data types does switch work with in ECMA Script?
All data types, including expressions, i.e.
case num > 0 && num <= 10:
How do you access the arguments passed to a function?
ECMA Script has an ‘array’ like structure that can be accessed in the function called ‘arguments’. Use length to find out how many arguments.
arguments.length;
Is function overloading possible in ECMA Script?
No - if two functions have the same name, the final function is the one used.
What is wrong with the following code? var name = "Steveybigs"; name.age = 27;
You can’t add properties to a primitive type (strings are primitives in Javascript) - Note, you wont get an error, but accessing name.age is undefined.
What is wrong with the following code? var person = new Object(); person.name = "Bill chumpbucket";
Nothing - it is perfectly valid to add properties to an object (reference type) in Javascript.
var obj1 = new Object(); var obj2 = obj1; obj1.name = "Dickhead"; alert(obj2.name);
What will be printed out
Dickhead. Because obj2 and obj1 now point to the same object, adding the property ‘name’ on either obj2 or obj1 results in it being accessable from either variable.
All function arguments are pass by…
value
function setName(obj) { obj.name = "hershey"; obj = new Object(); obj.name = "Greg"; } var person = new Object(); setName(person); alert(person.name);
What will be printed?
“hershey”. Remember, variables, even objects are passed by value, not by reference.
You can of course change the properties of an object as if it were pass by reference, but that’s because what is passed is a COPY of the objects reference. Not the actual reference (so internals can be changed by reference, but you can’t change the actual object because it’s a copy, not the actual reference).
typeof can be used to determine what type a variable is - but why isn’t it useful for reference types?
Because it will simply tell you it’s an object. To determine specificaly what type of object, use instanceof.
alert(person instanceof MyObject);
What is the execution context?
It determines what other data a variable or function has access to, as well as how to behave.
In a browser, the global context is said to be…
the window object
(so all global variables and functions are created as properties and methods of the window object.
When a function is executing, it’s context is pushed onto…
the context stack
and it is popped when finished, returning the context to the previously executing context
What is a scope chain?
When code is executed in a context, a scope chain of variable objects is created. It always starts at the variable object of the context whose code is executing and works it’s way back to global scope. This is then used to resolve usage of variable names, starting at the closest scope and working its’ way back to global scope.
In c, the iterator variable in a for loop is local to the for loop - what about Javascript?
No - it’s available outside the for block, as Javascript does not have block level variable scope.
When a variable is declared, it is added to the most immediate context, in the case of a ‘with’ block - what is the most immediate context?
The containing functions local scope.
Why is it important to break the link between a native javascript variable and a DOM object when it is no longer used?
Because DOM objects use reference counting. Javascript uses mark and sweep. DOM objects with Javascript objects can lead to circular references.
Use null to sever the connection.
Is a reference type a class?
No - there are no classes in ECMAScript
Why are Object reference types so useful?
They can be quickly created and have properties added - useful for passing data around in a program quickly.
Define an object literal named ‘person’ with properties name and age.
var person = {
name : “Jizzbomb”,
age: 29
};
What is potentially different with the way you declare properties when using object literal notation?
You can use strings and numbers as the identifiers.
Write an object literal statement that is the same as: var person = new Object();
var person = { }; // Not really recommended
What is unusual about constructor behavior when defining an object via object literal notation?
The constructor is never called.
How would you use an object literal to pass data to a function?
function displayInfo(args) { /* do stuff */ } displayInfo({ name: "Foobaz", age: 20 });
What is the difference between
person[“name”] and
person.name
Nothing - they effectively do the same thing.
What is the advantage of using bracket notation when accessing properties in an object?
You can pass variables into the brackets.
What makes an array different in ECMAScript compared to other languages?
Each slot can hold it’s own data type
Write five different ways to create an array in ECMAScript?
var myArray = new Array(); var myArray = new Array(20); // Set the size var myArray = new Array("Red", "yellow", "Green"); var myArray = Array("Greg"); // You can ommit the 'new' var myArray = ["red", "blue", "Green"];
Is this a valid way of creating an array? var values = [1, 2, ];
Yes, but AVOID it, as it creates an array with 2 OR 3 elements (note the trailing comma) depending on browser. And the last item MAY be undefined.
What is similar about creating objects and arrays using the literal notation?
The constructors are not called for either.