Javascript 2 Flashcards
Why is the statement “use strict”; a string literal?
Because of backwards compatibility. There is no sideeffect to evaluating a string literal, so in engines that don’t support strict mode, they will work fine.
What is the biggest issue with ‘strict mode’;
When concatenating files for deployment, you may have libraries that don’t use strict mode, or files that don’t use strict mode. However, the act of concatenating them may cause files that weren’t written with strict mode in mind to have it enabled.
What is one way of getting around the “strict mode” file concatenation issue?
Wrap the code in immediately invoked function expressions and use “use strict” at the top of each function.
What is an IIFE?
Immediately Invoked Function Expression - a function that is called as soon as it is loaded - with no need for the user to call it explicitly.
What will the following produce:
var num1 = 1; var num2 = 2.34;
console. log(typeof num1);
console. log(typeof num2);
number
number
(NOTE: All javascript numbers are of type number)
All numbers in javascript are treated as 64bit (double precision floating point) numbers - with one exception. What is that?
When using bit wise operators. The number is converted to a 32bit, big-endian, twos compliment number
How would you print the value of a number in binary?
var num = 128; num.toString(2);
The number in the parameters defines the radix - 2 = binary
Are the following equivalent?
console. log((0.1 + 0.2) + 0.3); console. log(0.1 + (0.2 + 0.3));
No - they should be - but floating point math is inaccurate at best - and you can’t guarantee it is associative (unlike in maths, where it would be).
3 + true = 4 // This is true in Javascript
What is this process called?
Coercion, the values are coerced into the type appropriate to make the statement work.
Which operators perform coercian?
The maths operators - however, ‘+’ is a bit subtle, since when you use a string in the expression, it will convert the value to a string, rather than a number.
What does “2” + 3 == in Javascript?
“23”
Note - not a number
What does (1 + 2) + “3” == in javascript?
“33”
Because addition groups to the left
What is the biggest issue with coercions?
A number that is null won’t fail in a maths operation - it will be converted to 0. This could hide errors.
var x = NaN; x === NaN;
What is the result?
false
NaN is not equal to itself.
Because there are other values that can be coerced to NaN - what is the most reliable way for testing for NaN?
var a = NaN; a !== a; // true
This works because NaN is the only value in Javascript that is not equal to itself.
Write a utility function that tests for NaN - reliably.
function isReallyNaN(x) { return x !== x; }
Can an object be coerced into being a primitive?
Yes - particularly objects to strings
“the math object” + Math; // “the math object: [object Math]”
How is an object converted to a string?
By calling the toString method (this is done implicitly in a coercion, or the user can do it themselves as required).
What is the issue with the valueOf method in regards to coercion?
valueOf only really works well on objects that are supposed to be numbers (i.e. a Number object). So when adding two objects using the ‘+’ operator, javascript isn’t really sure of the intent, is it concatenation, or addition, and blindly calls the valueOf method - but this may not have been intended.
What is ‘truthiness’?
When an object is coerced into a boolean expression.
There are seven falsy values in Javascript - what are they?
Null, NaN, 0, -0, “”, false, and undefined
What is the error in the following code?
function point(x) { if (!x) { x = 100; } }
x is relying on coercion, unfortunately 0 is a valid number for this function, but would be evaluated to false. So we need to use a different test.
if (typeof x === undefined) {
x = 100;
}
Type errors can be hidden by…
implicit coercions
The + operator is overloaded to do addition or concatenation depending on…
it’s argument types
Objects are coerced to number via…
valueOf
Objects are coerced to strings via…
toString
Objects with a valueOf method should provide a toString method that does what?
Returns a string representation of the number generated by valueOf
Rather than using ‘truthiness’ for testing undefined values, what should you use?
typeof or comparison to ‘undefined’.
What is different between the ECMA script standard and Javascript in regards to how ‘null’ is reported by the operator ‘typeof’?
According to the standard null should be it’s own type, however Javascript reports null as an object.
What are the five primitive types in Javascript?
booleans, numbers, strings, null, undefined
Strings are primitive types in Javascript, and yet you can create a string using new. Why?
var string = new String(‘superstring’);
This is a ‘boxed’ type - it’s a string wrapped in an object.
What is the result of the following code? var str1 = "My fun string"; var str2 = new String("My fun string");
console. log(str1 == str2);
console. log(str1 === str2);
true
true
The object is coerced to a string.
What is the result of the following code? var str1 = new String("My fun string"); var str2 = new String("My fun string");
console. log(str1 == str2);
console. log(str1 === str2);
false
false
The comparisons are actually checking that the objects are the same - they are obviously two different objects (this code does NOT check the value of the objects).
What is the result of the following?
“hello”.newProperty = 10;
console.log(“hello”.newProperty);
And why?
undefined
Strings are implicitly wrapped by the string object, which allows you to add properties to it. However, this serves no purpose, as when you reference it in this manner, a new string is created each time. Hence the undefined value.
Getting and setting properties on primitives does what?
Implicitly creates an object wrapper.
Object wrappers have the same behavior as their primitive types when testing for equality - true or false?
False - they do not behave in the same way - making it difficult to compare values when using the object wrappers.
Is using the == operator okay with mixed types?
You should avoid using it with mixed types.
When reading data from a form, should you just use coercion to test for equality?
No - use Number or the unary + operator to convert to a true number before testing.
When values are of the same type - is there any difference between the == and === operators?
No - but you should use the === anyway - as it tells other programmers reading your code that you are definitely not expecting coercion to occur in this segment of code.
What coercion takes place when you have:
null == undefined
None; always true
What coercion takes place when you have
null or undefined == anything other than null or undefined
None: always false
What coercion takes place when you have
Primitive String, Number, Boolean == Date Object
Primitive => number
Date Object => Primitive (first try toString, then valueOf)
What coercion takes place when you have
Primitive String, Number, Boolean == Non Date Object
Primitive => number
Non Date Object => Primitive (first try valueOf, then toString)
What coercion takes place when you have
Primitive String, Number, Boolean == Primitive String, Number, Boolean
Primitive => number
What is a good rule of thumb with regards to using the == operator for things like dates?
Create explicit application logic, for instance a function that takes a date object and formats it in a way that you will use in your application - this makes the intention explicit.
Semi colons are only ever inserted…
before the } token, after one or more newlines, or at the end of program input.
Semicolons are only ever inserted when the next input token cannot be parsed.
Is the following legal code?
function area(r) { r = +r return Math.PI * r * r }
No - as the +r does not have a semicolon after it, and the return statement is not on a new line - so the automatic semicolon insertion doesn’t work in this context. This would be an error.
Is a semicolon added in this context?
a = b
f();
Yes - because:
a = b f();
is not valid code - so the JS engine will attempt to add a semicolon after the b - before the next token it couldn’t parse f().
Is a semicolon added in this context?
a = b
(f());
No - because:
a = b(f());
is valid code - a semicolon would not be required.
Even if you are not deliberately using semi-colon completion functionality - it can hide or cause some weird errors - why is that?
Some characters can be problematic, because by leaving the semicolon off on the previous line - they may still form a valid - yet unintetional statement. The characters to look out for are:
(, [, +, -, and /.
The issue is most common with parenthesis (i.e. function brackets) and array literals.
Is the following code 1 or 2 statements?
a = b
[“r”, “g”, “b”].forEach(function (key) {
background[key] = foreground[key] / 2;
}
1 - because no semicolon was inserted after b, and because b[] is a valid statement, the JS engine did not add a semicolon - and this will cause an error.
Why might you a semicolon preceding a statement as in the following code?
a = b
var x
;(f());
If a programmer is using the ‘auto semicolon’ feature of JS - then it is pragmatic to add a semicolon in front of any of the “problematic” characters in JS. (i.e. the (, [, +, -, and / characters). This is to avoid errors that can be caused when the previous line and the current line inadvertently create a valid (but incorrect) statement.
When is the ‘global object’ created?
Whenever a JavaScript interpreter is started, for instance when a new page is loaded in a browser.
What is created as part of the ‘global object’?
Definitions for NaN, undefined, Infinity, global functions such as isNaN, parseInt etc and constructor functions such as Date(), RegExp(), String(), Object(), and Array(). Also - objects such as Math and JSON
In client side JavaScript, what serves as the global object?
The window object
Instead of using this - it has it’s own self referential name, window.
A ‘truthy’ value converts to…
true
A ‘falsy’ value converts to…
false
In nested functions, what happens to variable scope?
Each function has it’s own scope
In a function, if a variable is declared without the var keyword, what happens to it’s scope?
It is essentially global. Even thought it was declared within a function, it can be accessed and called almost anywhere (even from within other functions).
A variable defined with var is…
non-configurable (i.e. can’t be deleted with ‘delete’ keyword.)
JavaScript is a …………. scoped language?
lexically (i.e. the scope of the variable can be thought of as the set of source code lines for which the variable is defined)
In a top level non-nested function, what does the scope chain consist of?
Two objects, the function itself, with it’s declared variables and parameters. And the global object and it’s variables.
Normally you access properties using the . operator. If the property that you want to access on an object is not a valid name, or a reserved name, how do you access it?
You can also use the [] (square bracket) access notation - with the name in quotes.
What is an ‘invocation expression’?
The typical format for calling (or invoking) a function. i.e. supermanfunction();
What is the order of evaluation when using ‘invocation expressions’?
The function itself is evaluated first, then any argument expressions are evaluated, which allows a list of parameters to be build up.
If an invocation expression before the parenthesis contains an access operator, what does this mean?
It is a method invocation (i.e. a method on an object)
The object that method invocation is called on becomes…
the value of the ‘this’ operator within the method itself while the body of the function is being executed.
In a top level function (i.e. at root level), the ‘this’ operator contains a different value depending on whether the script is run in strict mode or not, what are the two options?
In ECMA script 5 - if strict mode is enabled, the ‘this’ operator is ‘undefined’ on a top level function. If it is not enabled, then it refers to the global object.
Most operators in JavaScript have left to right associativity. Which ones have Right to Left associativity?
unary, assignment and ternary conditional operators.
What does the unary (+/-) operators do?
Converts the value to a number (or NaN) and returns the value.
What is the difference between the bitwise operators»_space; and»_space;>
> > shifts right and preserves the sign, whereas»_space;> shifts right and zero fills from the left.
JavaScript objects are compare by…
reference, not value. (i.e. a JavaScript object is equal to itself, but not to any other object - even if they have identical properties).
When using the === (strict equality operator) are the following equal?
null === null
undefined === undefined
yes, they are both equal
If var1 is a string of “1” and var2 is a number of 1, are they equal when using the === operator?
No - the first step in the equality test when using the === operator is to determine if they are of the same type.
The “in” operator expects the left side to be a string (or something that can be converted to a string) - what is the right side?
An object.
When does the “in” operator evaluate to true?
When the string named in the left hand side is found as a property name on the object on the right hand side.
Given an object (MyObject) that is defined as { “1”: “superman” }, would the following evaluate to true?
1 in MyObject
Yes - 1 would be converted to a string, which is in that object.
The “instanceof” operator expects the left hand side to be an object, the right hand side should be a….
class of objects
When evaluating an “instanceof” expression, what is checked on the object?
The prototype value. So if we are checking if O is an instance of F. We check F’s F.prototype value, and then search for it in O’s prototype chain. If it finds it - then O is either an instance or a superclass of F.
With logical operators you should avoid right hand side operators that…?
Have a side effect, as they may not always be called if the left hand operator is not truthy.
What is the following code doing?
function copy(o, p) { p = p || { }; }
It is applying default arguments to parameters. If the left hand side of the logical or expression is true, then it will assign that value to p. If it is not truthy, then it will receive an empty object.
Why is it a good idea to use the = within brackets when using it in large expressions?
= has very low precedence, you could get unexpected results if you don’t use parenthesis.
If you pass a string to eval(), what does it do?
It tries to parse it as JavaScript.
If you pass anything other than a string to eval(), what does it do?
Returns that value.
What does typeof null return?
object
In general, typeof may return object for a number of different types, so what is a more pragmatic approach to determining an objects type?
Use instanceof
Does delete remove a property, or set it to undefined?
It completely removes the property - trying to access it will result in undefined, however, the test ‘property’ in MyObject, will return false - demonstrating it no longer exists on the object.
What is the ‘void’ operator?
It is a unary operator that evaluates it’s operand, then discards the result. Only useful if the operand has a side effect, most commonly used in client side apps where you want to execute a command, but want the result suppressed.
What is the comma operator?
An operator ‘,’ that evaluates the left hand operand, then the right hand operand, and discards the left hand result. Only really useful if the left hand operand has a side effect. Most commonly seen in for loops:
for (i=0, j=10; i
What is a statement block?
A series of statements that are enclosed within braces. { // statements; } // NOTE: Doesn't end with a semi colon
Write a statement that initialises an array a[] to all 0’s in one line.
for (i = 0; i
If a variable is defined with the declaration operator ‘var’ can you use delete on it?
No - it will not give an error, but the variable will not be deleted either.
Can you declare a variable in a for loop with var?
Yes
Can you use var to declare the same variable more than once?
Yes - there is no issue with this (although limited use).
Functions can be declared within other functions, but can a function be declared within an if statement within the function?
No - it must be at the top level, not in an if, or while or other statement.
NOTE: It can be nested within another function, it also wont throw an error unless in strict mode.
Whats the difference between a function declaration statement and a function definition expressions?
Function declaration statements include a function name.
Are function declaration statements hoisted?
Yes, like var variables, they are hoisted to the top of the script or function.
Can switch statements be used with strings?
Yes - you can do something like:
switch(typeof x) {
case ‘number’;
break;
}
What is the format for the JavaScript for / in loop?
for (variable in object)
statement;
How do you label a statement?
mylabel: while() {
}
What is the purpose of labelling a statement?
It allows you to jump to that label using a jump statement. i.e.
mylabel: while() {
continue mylabel;
}
Can the ‘break’ statement use labels?
yes.
break mylabel;