Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

4. JavaScript JavaScript is a scripting language that has closures, unnamed func

ID: 3622580 • Letter: 4

Question

4. JavaScript
JavaScript is a scripting language that has closures, unnamed functions, and
little to do with Java.
(a) The following JavaScript program prints ”43 46 12.”
var a = 12;
function g() {
var a = 42;
return function(x) { a += x; print(a); }
}
var f = g();
f(1); f(3); print(a)
Is JavaScript statically or dynamically scoped? Why?
(b) Can JavaScript always use a stack to store local variables? Why or why
not?
(c) The following JavaScript program prints “42 12 18”
var a = 12;
function b(x) { print(a); print(x); }
function c() { print(42); return 18; }
b(c());
Does JavaScript use normal- or applicative-order evaluation? Why?
(d) Does the following JavaScript program terminate? If so, what does it
print?
function i(p, t, e) { if (p) return t(); else return e(); }
function f(a) { return i(a > 2,
function() { return a * f(a1);
},
function() { return 1; } ) }
print(f(4));

Explanation / Answer

Dear, a) Javascript is statistically scoped, since the local variable (a) is a local variable prints 43 when call f(1), and 46 when call f(3) if we call print(a) then a is called global variable, The var a =42 (here a is local variable) it shadows the global a=12 in that function. However, it has no effect in print(a), so print(a) uses the global a which is still 12. In a dynamically scoped language (unlike JS), print(a) would inherit scope from g(), so it would 46. Note that a would still be 12 at the alert, because the alert does not inherit scope from either function. b) Javascript uses stack always for local variables for efficeint use of accessing variables from stack. It is optimized to access and manipulate stack data.Accessing static and instance variables is more costly because the JVM must use a more expensive opcode and access them from the constant pool. (The constant pool holds symbolic references to all types, fields, and methods used by a type.) c) Javascript uses applicative order, since it will evaluates the arguments x before a function b() is called otherwise it will hang.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote