Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
Why this is a valid syntax in javascript?
const arr = [(firstName = 'hello')]

Why the above code is valid code in javascript. I didn't understand why this is not throwing any error.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Here's what that code does and any it's valid.

That code does this:

firstName = 'hello';
const arr = ['hello'];

...except 'hello' is only evaluated once. (In the case of a literal like 'hello' it doesn't matter that it's only evaluated once, but it would if 'hello' were instead a function call returning a string.)

It's valid because:

  • Using the result of an assignment operation is valid; the result of an assignment operation is the value being assigned. So the expression firstName = 'hello' results in the value 'hello'.

  • The grouping operator (()) can be used where any expression can be used; the result of the grouping operation is the result of the expression within it.

  • [x] creates an array with x in it.

  • const arr = /*...*/ creates a constant (a read-only variable) and assigns it the result of evaluating the initializer expression (the expression on the right-hand side of the =).

So all of the parts are valid and they're assembled in a valid way. The identifier arr is declared; the firstName = 'hello' assignment expression is evaluated, setting firstName and resulting in 'hello'; the grouping operation ('hello') is evaluated resulting in 'hello'; the array literal ['hello'] is evaluated creating an array; and the arr constant is initialized with the array reference.

One wrinkle is that it looks like firstName is an undeclared identifier (your code doesn't declare it anywhere, there's no let firstName or similar). If it's really undeclared, then this is one of the unfortunate quirks of JavaScript in loose mode: assigning to an undeclared identifier implicitly creates a global variable (I call it "The Horror of Implicit Globals"). This is one of many reasons to use strict mode ("use strict" at the top of the file, or use JavaScript native modules ["ESM"]; the body of a class definition is also always strict). In strict mode, assigning to an undeclared identifier is the error it always should have been.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!