+ 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

9th Jan 2022, 10:43 AM
👑 Tchybooxuur!
👑 Tchybooxuur! - avatar
13 Answers
+ 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
9th Jan 2022, 10:56 AM
Josh
Josh - avatar
+ 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
9th Jan 2022, 11:00 AM
Josh
Josh - avatar
+ 7
9th Jan 2022, 11:04 AM
Josh
Josh - avatar
+ 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.
9th Jan 2022, 12:49 PM
Josh
Josh - avatar
+ 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
9th Jan 2022, 10:49 AM
Lisa
Lisa - avatar
+ 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();
9th Jan 2022, 11:01 AM
Lisa
Lisa - avatar
+ 5
Kapama, Joshua && Lisa: Thanks a lot guys 👌🏾
9th Jan 2022, 12:18 PM
👑 Tchybooxuur!
👑 Tchybooxuur! - avatar
+ 5
Kapama, Joshua: Thanks a lot. You are most helpful.
9th Jan 2022, 2:36 PM
👑 Tchybooxuur!
👑 Tchybooxuur! - avatar
+ 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?
9th Jan 2022, 12:22 PM
👑 Tchybooxuur!
👑 Tchybooxuur! - avatar
+ 4
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
9th Jan 2022, 10:38 PM
Goke Ekundayo
Goke Ekundayo - avatar
+ 4
Thanks Goke Ekundayo 👍🏼
9th Jan 2022, 10:47 PM
👑 Tchybooxuur!
👑 Tchybooxuur! - avatar
+ 3
👑 Tchybooxuur! Happy to help
10th Jan 2022, 1:25 AM
Goke Ekundayo
Goke Ekundayo - avatar
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
8th Jun 2022, 5:19 PM
K. sainath Reddy
K. sainath Reddy - avatar