0

While typing the value {2,4,45,50} on console displays 50, but assigning the {2,4,45,50} to variable getting the error

 var a = {2,4,45,50}
 Uncaught SyntaxError: Unexpected number

What is the concept on this.

asked Dec 28, 2021 at 7:18
10
  • 8
    its [] for arrays, the console just treats your {} like a block and gives you the last value Commented Dec 28, 2021 at 7:19
  • @govinda Do you mean var a = [2, 4, 45, 50]? Commented Dec 28, 2021 at 7:21
  • in that case why are we getting the error on assign to variable , should set 50 to the variable as per my understanding Commented Dec 28, 2021 at 7:22
  • It is not a valid json object, you cannot just put numbers in a JSON Commented Dec 28, 2021 at 7:24
  • 1
    @Govindaraj {1, 2, 3} does not make an array in JS, nor is it a valid expression, so of course assigning it to a variable will throw -- the {} creates a block, or a set of statements, and the console typically gives you the last value when given a set of expressions -- even typing 1, 2, 3, 4, 5 into the console yields 5 Commented Dec 28, 2021 at 7:31

1 Answer 1

3

its [] for arrays, the console just treats your {} like a block and gives you the last value – skara9

As Skara mentioned, [] is for arrays. {} is for tables, so when you assign it to a variable since it's a table it's expecting a key and value, for example: {a: 1, b:2, 3:4}. If you want an array then change {} to [], otherwise, you should assign a key and value for the table.

If you would like to log a specific value of an array you can do so using an index, index starts from 0 to the number of values. For example:

 var a = [2,4,45,50]
 console.log(a[0])
 //Expected output is 2

If you wanted to use a table and log the value of the first key, which in this case would be a, then you would do:

 var test = {a:2, b:4, c:45, d:50}
 console.log(test.a)
 //Expected output is 2 because 2 is assigned to a

You could also just log the whole array and/or table.

answered Dec 28, 2021 at 7:37

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.