JavaScript Functions
- Consider the following code snippet :
function constfunctions()
{
var functions = [];
for(var k = 0; k < 10; k++)
functions [k] = function() { return k; };
return functions ;
}
var functions = constfunctions();
functions [5]()
What does the last statement return ?
-
View Hint View Answer Discuss in Forum
NA
Correct Option: A
The code above creates 10 closures, and stores them in an array. The closures are all defined within the same invocation of the function, so they share access to the variable k. When constfuncs() returns, the value of the variable k is 10, and all 10 closures share this value. Therefore, all the functions in the returned array of functions return the same value.
- Consider the following code snippet :
var Total=eval("5*5+10");
-
View Hint View Answer Discuss in Forum
NA
Correct Option: A
eval() is a function property of the global object. The argument of the eval() function is a string. If the string represents an expression, eval() evaluates the expression. If the argument represents one or more JavaScript statements, eval() evaluates the statements.
- Do functions in JavaScript necessarily return a value?
-
View Hint View Answer Discuss in Forum
NA
Correct Option: D
Functions generally have a return statement and hence usually returns a value. Some functions which does not have a return statement returns value by default during execution.
- Consider the following code snippet :
var tensquared = (function(n) {return n*n;}(100));
Will the above code work ?
-
View Hint View Answer Discuss in Forum
NA
Correct Option: D
Function name is optional for functions defined as expressions. Function expressions are sometimes defined and immediately invoked.
- Consider the following code snippet :
var string2Number=parseInt("456pqr");
-
View Hint View Answer Discuss in Forum
NA
Correct Option: D
The parseInt() function parses a string and returns an integer. The function returns the first integer contained in the string or 0 if the string does not begin with an integer.