+ 13
SOLOLEARN JAVASCRIPT CHALLENGE QUESTION... 🤔
Why does this throw an error? class A { for(var i=0; i<3; i++) console.log(i); } var x = new A(); //output: //UncaughtSyntaxError: unexpected token 'var' //Line: 2 https://www.sololearn.com/post/1468443/?ref=app
14 ответов
+ 7
Lisa
in fact, if you do not have a constructor method, JavaScript will add an invisible and empty constructor method.
https://www.w3schools.com/jsref/jsref_constructor_class.asp
+ 7
Javascript classes operate in strict mode that's why it will throw some errors.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
+ 7
Yes Lisa, that's the idea behind it.
https://code.sololearn.com/cHDmHG69fCtJ/?ref=app
+ 7
Of course as said the body of class operates in strict mode means the syntax should be valid, you can leave the constructor empty but in a legal accepted class syntax.
+ 5
I am not sure but I suppose that it has to do with the fact that the loop does not run in a constructor or method
+ 5
Kapama, Joshua okay, thanks.
But then the constructor will be empty, right? The for loop would still run out of a constructor or method...
If I put the loop in a constructor, there is no error
class A {
constructor() {
for(var i=0; i<3; i++)
console.log(i);
}
}
var x = new A();
+ 5
Kapama, Joshua && Lisa:
Thanks a lot guys 👌🏾
+ 5
Kapama, Joshua:
Thanks a lot. You are most helpful.
+ 5
Its because u did not add a constructor function, you can leave it empty but its best practise to define variables and functions within jt
+ 4
Kapama, Joshua:
It means therefore that, explicitly declaring properties etc in the class (and not in a method or constructor) is prohibited in this strict mode right?
Is there a list of permitted syntaxes in a class' strict mode?
+ 4
Thanks Goke Ekundayo 👍🏼
+ 4
👑 Tchybooxuur! Happy to help
0
Let a=[1, 3,5][2];
Let b={x:4,y:10}.y;
Let c="199" [0];
Console.log(a+b+c) ;
What is output of above code..explain in detail.. Can anyone explain me plzzzz
0
The error in your code is due to the use of a for loop directly inside the class body. In JavaScript, class bodies can only contain method definitions or property initializers, but not standalone statements like a for loop.
If you want to execute code when an instance of the class is created, you can use the constructor method. Here's an example of how you can modify your code:
class A {
constructor() {
for (var i = 0; i < 3; i++) {
console.log(i);
}
}
}
var x = new A();
In this modified code, the for loop is placed inside the constructor method of the class, and it will be executed when an instance of the class is created.
You can get refrence here : https://innostax.com/?s=Javascript