Satish Patro
Satish Patro

Reputation: 4394

Can not able to print value of a object

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

Upvotes: 0

Views: 77

Answers (1)

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

Upvotes: 3

Related Questions