3

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/

Sydney
  • 1,349
  • 1
  • 14
  • 20

2 Answers2

7

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

Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98
  • No it isn't, javascript has something called Automatic Semicolon Insertion, which in some edge cases, will bite you. Yours is an edge case. use semicolons. – Marcos Casagrande Apr 23 '18 at 23:17
3

You forgot to put semicolons at the end of your lines, which is resulting in the error. When you do this:

let x = 5
let y = 4
x > 0 && console.log('code 4')
(x > 0) && (y > 0) && console.log('code 5');

because the third line ends in a ), the interpreter thinks you're calling the result of console.log with the (x > 0) argument:

let x = 5
let y = 4
x > 0 && console.log('code 4')(x > 0) && (y > 0) && console.log('code 5');

But console.log returns undefined: it doesn't return a function, so of course you can't call it as a function.

Always use semicolons if you're just still learning the language, or you can easily trip yourself up.

Also, what you're doing is not a good way of doing things; while it's an interesting language quirk, it's better to test for conditions explicitly using if or the ternary operator than to use && for that.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thanks for the tip. i actually followed this method from a React tutorial to control what should be rendered. – Sydney Apr 23 '18 at 23:20