Not sure this problem is because of a bug in jsFiddle or my misunderstanding of the round bracket of javascript. I have this code:
let x = 5
(x > 0) && console.log('hello')
This doesn't work. However, the following without bracket works.
x > 0 && console.log('hello')
My impression is that i can use the round brackets in condition to group things together. I have no idea why my first line of code does not work. Is it my misunderstanding of round bracket?
I am actually trying to teach someone a more advance example in this jsFiddle code. https://jsfiddle.net/x616atk0/
It does not work, because you're missing a semicolon after let x = 5
The code should be:
let x = 5;
(x > 0) && console.log('hello');
Otherwise, your code can be translated to this:
let x = 5(x > 0) && console.log('hello');
And of course 5
isn't a function, and x
(which you're using in the expression which evaluated value will be passed as argument) isn't defined yet.
The error is misleading because you're using the same variable that you're defining as argument. If you had
let x = 5
(5 > 0) && console.log('hello');
You would get: TypeError: 5 is not a function
which is exactly the problem.
This is why semicolons are important!
Do you recommend using semicolons after every statement in JavaScript?
yes, I absolutely do