# Accessing Object Properties Value
There are 2-ways to access an object’s(Properties) value in JavaScript:
1. Dot notation.
2. Square bracket notation.
Note : In case the property name that is not a valid Javascript identifier, they must be accessed and added using the “square bracket notation”.
1.) The dot notation (.) : The following illustrates how to use the dot notation to access a property of an object:
Syntax :
objectName.propertyName;
Let's see, the example of how to use the dot notation to access an object property:
Example 1:
In this code, we creates a book object and use the dot notation to access the property name(id, name) of the book object on the Console.
- <script type="text/javascript">
var book = {
id : 02,
name : "JavaScript",
};
// Dot notation
console.log(book.id); // Output : 02
console.log(book.name); // Output : JavaScript
- </script>
2.) The Square bracket notation ([]) : The following illustrates how to use the square bracket notation to access a property of an object:
Syntax :
- /* Here, wrapped property name using single quote(' ') or double quote(" ") */
objectName['propertyName'];
OR
objectName["propertyName"];
Let's see, the example of how to use the bracket notation to access an object property:
Example 2:
In this code, we creates a book object and use the square bracket notation to access the property name(id, name) of the book object on the Console.
- <script type="text/javascript">
var book = {
id : 02,
name : "JavaScript",
};
// Square bracket notation
console.log(book['id']); // Output : 02
console.log(book["name"]); // Output : JavaScript
- </script>
There are certain cases, where the property names must be accessed using the “square bracket notation” not a “dot notation”.
If the name of the property is not valid (i.e if it contains spaces or special characters), then you can't use the dot notation. You will have to use square bracket notation, Let see :
Let's try, to create an example :
- <script>
var book = {
name: "Learn JavaScript",
author: "Coder Website",
"publication date": "02 July 2016"
};
// Using dot notation
console.log(book.'publication date'); // SyntaxError : Unexpected string
console.log(book.publication date); // SyntaxError : missing ) after argument list
// Using square bracket notation
console.log(book['publication date']); //Output : 02 July 2016
- </script>
The property names can be strings or numbers. But in case the property names are numbers they must be accessed using the “square bracket notation” .
Let's try, to create an example :
- <script>
var book = {
1: 02,
name: "Learn JavaScript",
author: "Coder Website",
};
// Using dot notation
console.log(book.'1'); // SyntaxError : Unexpected string
console.log(book.1); // SyntaxError : missing ) after argument list
// Using square bracket notation
console.log(book['1']); //Output : 2
- </script>
Comments