0

in javscript

I can't able to fetch value from a object.

When printing whole object is printing. But, when I am trying to access only 1 field it is showing error

function add_new_row()
{
  let gg = 
  {
    "1st_col" : '99',
    "2nd_col" : '88',
    "3rd_col" : ['77', '66'],
    "4th_col" : '55',
  }
  console.log(gg); //{1st_col: "99", 2nd_col: "88", 3rd_col: Array(2), 4th_col: "55"}
  console.log(gg.1st_col); //Error here

  //this is the line where I called this function in button HTML
}

The error that is thrown is:

Uncaught ReferenceError: add_new_row is not defined
    at HTMLInputElement.onclick (index2.html:120)
    onclick @ index2.html:120
2
  • Given your code, it is impossible for console.log(gg.1st_col); to throw Uncaught ReferenceError: add_new_row is not defined.
    – Snow
    May 16, 2019 at 3:02
  • In this particular case, you can use brackets to access the property, like: console.log(gg["1st_col"]); You can check the MDN for valid identificators when using dot notation...
    – Shidersz
    May 16, 2019 at 3:05

1 Answer 1

3

You can not access via dot notation if the fields name starts with a number. It's a convention rule defined in lexical analysis of javascript compiler for vars naming.

This is valid:

gg.first_col
gg._1st_col
gg.a1st_col

If you use the bracket notation is valid to refer to these fields in that way:

gg["1st_col"]

--- edit ---

These are the basic rules for defining variable names in javascript:

  • Names should begin with lowercase string.
  • Names cannot contain symbols or begin with symbols.
  • Names cannot begin with a number.
  • Names can contain a mix of uppercase strings, lowercase strings, and numbers.

Source: https://scotch.io/courses/10-need-to-know-javascript-concepts/declaring-javascript-variables-var-let-and-const

2
  • Intresting. We need to study documentation to know all these? Or is there any other way to know this type of rules? May 16, 2019 at 4:01
  • 1
    Yes, you can investigate more about it in the documentation. These are the basic rules for defining variable names: 1. Names should begin with lowercase string. 2. Names cannot contain symbols or begin with symbols. 3. Names cannot begin with a number. 4. Names can contain a mix of uppercase strings, lowercase strings, and numbers. May 16, 2019 at 5:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.