QUESTION:
True or False: the terms “scope” and “context” refer to the same thing in JavaScript.
Click for Answer
False
Explanation:
Scope pertains to the visibility of variables and in contrast, context refers to the object to which a method belongs (which can be changed by using call or apply).
QUESTION:
If you omit the “var” keyword when creating a variable in a function, it becomes a property of what object?
Click for Answer
Explanation:
When omitting the “var” keyword, the variable you create becomes an “implied global”. However, implied globals are not variables in a function. As a result of this mistake, an implied global actually becomes a property of the window object. Although the window object is considered the “global” scope, it is an object, and any variable declared in the global scope (intentionally or otherwise), actually becomes a property of the window object.
QUESTION:
How do you determine if a JavaScript instance object was created from a specific constructor or not?
Click for Answer
QUESTION:
True or False: Once you create an object, you can add, remove or change properties of that object at any time.
Click for Answer
QUESTION:
True or False: You can only instantiate a JavaScript constructor function once.
Click for Answer
Explanation:
You can make as many instances as you want. There is no limit.
QUESTION:
When you create a function inside of a method, what does the “this” keyword refer to when used in that function?
Click for Answer
The “window” object
Explanation:
Inside of a function, the “this” keyword always refers to the window object. On the other hand, when a function is a property of an object, the “this” keyword always refers to the object to which that method belongs.
Example:
|
var myObject = { color : "red", test : function(){ function testThis(){ console.log(this.color); //undefined console.log(window === this); //true }; testThis(); console.log(this.color); //red console.log(window === this); //false return "done!" } }; myObject.test(); |
In the above example, the output to your JavaScript console should be:
- undefined
- true
- red
- false
- “done!”
The reason for the output is: The testThis function inside of the myObject.test method attempts to log the value of “this.color“. However, that function is NOT a method, it is just a function declaration, thus “this” refers to the window object. In this code, the window object, does not have a “color” property, and accordingly “this.color” is undefined. Next, the testThis function inside of the myObject.test method compares, window to the “this” keyword (just to prove the previous point). Again, because the testThis function inside of the myObject.test method is NOT a method, it is a property of the window object, and therefore “this” DOES equal the window object.
Next, the myObject.test method attempts to log the value of “this.color”. Since the test metod is a property of the myObject object, and the myObject object has a property named “color”, the value of that property is logged to the console. Next, the myObject.test method attempts to compares window to the “this” keyword. Since the test metod is a property of the myObject object, the “this” keywork refers to the myObject object, and the comparison to the window object returns false.
QUESTION:
Name two ways two change the context of a JavaScript method
Click for Answer
Use the call or apply methods
Explanation:
The call and apply methods can be used to specify the context of another method.
|
var objectA = { name : "I am objectA", sayName : function(){ alert("I am: " + this.name); } }, objectB = { name : "objectB", sayName : function(){ alert("I am: " + this.name); } }; objectA.sayName.call(objectB); //alerts: "I am ObjectB" objectB.sayName.apply(objectA); //alerts: "I am ObjectA" |
QUESTION:
Can a JavaScript constructor return a primitive value (e.g. a number or a string)?
Click for Answer
Explanation:
A JavaScript constructor can only return an object. When no return value is specified, it returns an instance of itself. However, if an object is specified as the return value, then that object is the return value. Thus, if any value other than an object is specified as the return value, then it returns an instance of itself.
QUESTION:
In JavaScript, are objects passed by reference or by value?
Click for Answer
In JavaScript, all objects are passed by reference. When you make a change to a reference to an object, you change the actual object. Primitive types are however, passed by value.
Explanation:
Here is a jsFiddle.net example: http://jsfiddle.net/pmMLc/
QUESTION:
What is the difference between a constructor function and a non-constructor function with respect to the word “this”
Click for Answer
QUESTION:
What is the name of the property that allows you to add properties and methods to an object, as well as every object that inherits from it?
Click for Answer
QUESTION:
True or False: An object literal can be used to create private variables.
Click for Answer
False. Only functions can be used in JavaScript to create privacy
Explanation:
All of the properties of a object literal are public and can be easily mutated. The only way to create private variable in JavaScript is by using a function. You can make a property of an object literal a function (i.e. a “method”), and use private variables in that function, but the named property will always be public.
QUESTION:
What is the name of the object that refers to the application used to view a web page?
Click for Answer
QUESTION:
True or False: The object returned by the document.getElementsByTagName() method is an array.
Click for Answer
QUESTION:
Which object.property combination provides a reference to the protocol used to view the current web page?
Click for Answer
QUESTION:
Given the below code, what line of JavaScript would allow foo.getColor to return the value of foo.color, without using the word “foo”?
|
var foo = { color : "red", getColor : function(){ //make this function return foo.color //without using the word: "foo" } } |
Click for Answer (+)
return this.color
Explanation:
When a function is a property of an object, it is called a “method”. Inside of a method, the JavaScript “this” keyword refers to the object to which the method belongs. Therefore, in foo’s getColor method, if you return “this.color”, you will thus return the value of foo’s “color” method. A key point is: the advantage to this over “return foo.color” is that when using “this” instead of “foo”, the code in the getColor method is re-usable.
QUESTION:
What is the difference between using dot notation and bracket notation when accessing an object’s property?
Click for Answer (+)
If using dot notation, the property must be a string and refer to a property that in fact exists.
When using bracket notation, any valid JavaScript expression that produces a value can be used inside the brackets, such as a variable or an an array element.
Explanation:
These are all valid lines of code:
|
foo = bar.name; foo = bar["name"]; foo = bar[5 + 5]; foo = bar[ baz() ]; foo = bar[ baz[i] ]; |
QUESTION:
What is important to remember about the last property’s value in a JavaScript object literal?
Click for Answer
QUESTION:
Given the following code, what is very likely the reason that the programmer made the first letter of “Foo” a capital letter?
Click for Answer
Foo is meant to be used as a constructor function.
Explanation:
In spite of the fact there is no technical requirement that constructor function names begin with a capital letter, it is a common convention and a pattern that most experienced JavaScript developers recognize.
QUESTION:
Given the following code, how would you instantiate the function “Foo” and assign it to the variable “bar”?
Click for Answer
QUESTION:
What are two ways in which the variable “foo” can be assigned to an empty object?
Click for Answer
- var foo = new Object();
- var foo = {};
Explanation:
When creating a new empty object, you can instantiate the Object() constructor, or you can simply create an empty object literal. For this reason, in either case, you can then add properties to the new object.
Here is a jsFiddle.net example: http://jsfiddle.net/W6X2T/
QUESTION:
True or False: When you create an object literal, you must first instantiate the Object() constructor.
Click for Answer
Explanation:
In order to create an Object Literal, you assign a variable to an object. As a matter of fact, the syntax is as simple as var foo = {}. However, a constructor function is used when creating an instance object, which is a different process.
QUESTION:
When using the addEventListener() method to create a click-handler for a DOM element, what is the value of “this” inside of the callback you specify?.
Click for Answer
QUESTION:
True or False: A JavaScript array is not an object
Click for Answer
QUESTION:
If a string is a primitive value, why does it have a split() method?
Click for Answer
QUESTION:
True or False: A function can have its own properties and methods.
Click for Answer
True
Explanation:
Functions as a matter of fact, inherit from Object. Therefore, you can add properties and methods to a function at any time. Run the following code in your JavaScript console and then you will see this behavior:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
//create a function function foo(){}; //assign a property foo.color = 'red'; //assign a method foo.sayHello = function(){ alert("hello!"); }; //inspect the object console.dir(foo); //inspect the properties and methods of off //execute the method foo.sayHello();// "hello!" //overwrite a method foo.sayHello = function(){ alert("this is a different message"); }; //execute the method foo.sayHello();// "his is a different message" |
Thanks a lot..It is so helpful.
hi kevin,
about the question :
QUESTION:
In JavaScript, are objects passed by reference or by value?
And your answer is all objects are passed by reference.
But in my opinion, everything is pass by value, but in case of object, the “value” which is passed here is “reference”.
That’s just my own knowledge, I think that there are no “pass by reference”, just only pass by value and depending on what type of data is, what the value pass is ( value or its address, what we called reference).
Sorry if it’s wrong.
Hi hungnh1704,
Thanks for your comment.
In JavaScript, primitives are passed by value, and objects are passed by refernce.
Here are two links that might help you:
http://docstore.mik.ua/orelly/webprog/jscript/ch11_02.htm
http://snook.ca/archives/javascript/javascript_pass
Let me know if you still have any questions.
Best Wishes,
Kevin
I tend to think about the pass by reference vs by value stuff in this manner. An objects properties are passed by reference, but the object it self is still passed by value. If you assign the variable passed to a function to a different object, that assignment is not propagated to the outer scope.
var testObj = {orignal: ‘object’};
var testReference = function (obj) {
obj = {new: ‘object’};
};
testReference(testObj);
console.log(‘testObj’, testObj);
testObj here is still the original object. Does this make sense, or do i have my terminology wrong?
Hi Derek,
Thanks for y our comment. It’s an interesting point and really great example that demonstrates it.
The way I look at your example is: The “obj” parameter is a private variable. When you assign a new object to it, you wipe out the reference to the passed-in object. There is no longer any connection between obj and testObj.
Here is an example of what I mean:
var testObj = {orignal: ‘object’};
var testReference = function (obj) {
//obj = {new: ‘object’};
obj.newProperty = true;
console.dir(obj);
};
testReference(testObj);
console.dir(testObj);
You should see the following in your console:
orignal “object”
newProperty true
(the above output appears twice)
So, the changes you make inside the function to the passed-in object’s property do in-fact persist outside of the function. The object is passed by reference (as per my example). But when you overwrite that passed-in reference (as per your example), you essentially have a new object.
Let me know if you disagree.
Best Wishes,
Kevin
Hey Kevin,
I think everything you said makes perfect sense. I think the confusion for a lot of beginners is that if the object is passed by reference, they think re-assigning the variable should persist outside the function. JavaScript doesn’t work this way because of its scoping. However, languages like PHP do it this way. Which makes it confusing.
Warning! PHP example:
“obj”);
testReference($test);
print_r($test);
?>
This prints the array(1,2,3) and in PHP land this object is said to have been passed by reference.
Sorry, example didn’t print out correctly
function testReference(&$obj) {
$obj = array(1,2,3);
}
$test = array(“test” => “obj”);
testReference($test);
print_r($test);
Hi Derek,
Thanks for y our follow-up. I can definitely understand why JavaScript would be so confusing in a situation like this, especially coming from PHP. I am not as experienced in PHP, but I do find myself scratching my head sometimes when it comes top reference/value in PHP, because I am “thinking JavaScript!” : – )
Hi Kevin- Thank you very much for the detailed explanations/examples and answers! This has been very helpful.
Hi Shawn,
Thanks for your message, I’m very happy if these question were helpful at all. Please let me know if there are any additional areas / topics that you feel would be helpful to cover.
Kevin
Thanks a lot.. Its really helpful
Excellent, extremely helpful
good article
It’s a great help. Thanks for your effort.
I need to understand one item from the above list.
Can a JavaScript constructor return a primitive value (e.g. a number or a string)? The answer was ‘No’.. if i have a custom constructor function, it can return anything.. can u plz explain it further..
Hi Vinod,
Thanks for your comment.
Every function in JavaScript returns a value. You can return any value from a function. For example, this function returns the string “hello”:
function foo(){
return “hello”;
}
I could have returned the number 5, the boolean “false” or an array. You can return ANY valid JavaScript value from a JS function. If you do NOT explicitly return a value. the function returns: “undefined”.
Constructors behave differently. they can only return an object. If you do NOT explicitly return a value from a constructor, the new instance of the constructor is returned. That new instance is an object.
If you want to explicitly return a value from a constructor, that value MUST be an object. If you attempt to return a primitive value (e.g. a string or a number), the instance object is returned instead.
So, for example:
1) in this case, I try to return a string, but the instance object will be returned instead (returning a primitive is not allowed):
function Foo(){
this.color = “red”;
return “hello”;
}
console.dir(new Foo()) // object -> color : red
2) In this case, I return an array, and it works because it is an object:
function Foo(){
this.color = “red”;
return [‘a’, ‘b’, ‘c’];
}
console.dir(new Foo()) // object -> 0 : ‘a’, 1 : ‘b’, 2: ‘c’
3) In this case, I do not explicitly return a value, so the instance object is returned:
function Foo(){
this.color = “red”;
}
console.dir(new Foo()) // object -> color : red
Please let me know if you still have any questions about this.
Best Wishes,
Kevin
You have created a very excellent website for Javascript basic .
Great work !!
Hey Kevin thanks for your explanation regarding the topic. Am little bit confused with ‘closures’, if you don’t mind, can you explain please.
Hi Vivek,
Here are a few links that will hopefully give you an overview of JavaScript closures:
http://blog.kevinchisholm.com/javascript/javascript-closures-basics/
http://blog.kevinchisholm.com/tag/closure/
After taking a look at these links (the first one has a video), please let me know if you still have any questions.
Best Wishes,
Kevin
Nice article. Thanks for covering up the basic details of Javascript. But , I think you should have included a bit on closures 🙂