Since both variable1 and variable2 are defined within the enclosing function scope of the function, and since the line they are on begins with the var keyword, most JavaScript developers would expect typeof variable1 and typeof variable2 to both be undefined in the above example.
You think of it as following :
var variable1 = 3;
var variable1 = variable2;
In fact, var variable1 = variable2 = 3; is actually short-hand for:
variable2 = 3;
var variable1 = variable2;
As a result (if you are not using strict mode), the output of the code snippet would be:
Output -
variable1 defined? false
variable2 defined? true
Question 2 : Solution
Output -
printVal: this.value = 1
printVal: self.value = 1
inner printVal: this.value = undefined
inner printVal: self.value = 1
In the printVal function, both this and self refer to myObject and therefore both can properly reference and access foo.
In the inner anonymous function, though, this no longer refers to myObject. As a result, this.value is undefined in the inner function, whereas the reference to the local variable self remains in scope and is accessible there.
Note - If you convert the inner anonymous function to an arrow function, you will not get undefined. As the arrow function does not have its own this and thus points to the context of the scope where it is been called.
Question 3 : Solution
Output -
0.30000000000000004
false
You can’t be sure about the output here. It might print out 0.3 and true, or it might not. Numbers in JavaScript are all treated with floating point precision, and as such, may not always yield the expected results.
Question 4 : Solution
At the point that the program is invoked, the for loop has already completed and the variable i already has a value of 5. All the setTimeout registered for each value of i in the loop will run with the updated value of i ;which is 5, after each second as calculated by (1000 * i) ms
It is because var is a function scope and not the block scope and every callback in setTimeout will refer to the same value of i available globally to it.
for eg:
1st iteration will print the 5 after 1000 * 0 = 0s
2nd iteration will print the 5 after 1000 * 1 = 1s
3rd iteration will print the 5 after 1000 * 2 = 2s
and so on...
So the output will be ,
5 5 5 5 5
Note - if you replace var with let , you will get the output as 0, 1, 2, 3, 4. As let is a block scope.
Question 5 : Solution
Output -
array 1: length=3 last=o
array 2: length=3 last=o
In var arr2 = arr1.reverse(); the reverse() method will reverse the arr1 and stores the reference of reversed arr1. As reverse() method mutates the original array.
When we remove the last element from the reversed string using splice() method on arr2 it will mutate the arr1 as well thus gives the same value for arr1 and arr2