Which is a more efficient JavaScript code snippet?
Code 1 :
for(var num=10;num>=1;num–)
{
document.writeln(num);
}
Code 2 :
var num=10;
while(num>=1)
{
document.writeln(num);
num++;
}
a) Code 1
b) Code 2
c) Both Code 1 and Code 2
d) Cannot Compare
Answer: a
Explanation: Code 1 would be more efficient. Infact second code will go into runtime error as the value of num will never reach less than or equal to one.
Related Posts
What will be the output of the following JavaScript code?
int a=0;
for(a;a< 5;a++);
console.log(a);What will be the output of the following JavaScript code?
int size=5;
int a=5;
int size=4;
for(int j=size;j>=0;j–)
{
console.log(a);
a=a-2;
}What will be the output of the following JavaScript code?
var a= 0;
var b = 0;
while (a < 3)
{
a++;
b += a;
console.log(b);
}What will be the output of the following JavaScript code?
var a = 10;
do {
a += 1;
console.log(a);
} while (a < 5);What will be the output of the following JavaScript code?
function range(int length)
{
int a=5;
for(int i=0;i< length;i++)
{
console.log(a);
}
}range(3);Among the keywords below, which one is not a statement?
What could be the task of the statement debugger in the following JavaScript code?
function f(o)
{
if (o === undefined) debugger;
}
Join The Discussion