1

I started to learn JavaScript, and I can not catch one thing.

myDog.name = "Happy Camper"; 
myDog["name"] = "Happy Camper";

and also

var myDog = {
  "name" : "Coder",
  "legs" : 4,
  "tails" : 1,
  "friends" : ["everything!]"
};

here in everything - what is the difference with and without brackets?

Thank you.

Akxe
  • 9,694
  • 3
  • 36
  • 71
nigi
  • 11
  • 1

2 Answers2

1

In JavaScript, [] is used to determine an Array literal, but is also one of the ways to call Object keys, hence your confusion.

const myArray = []; // Returns an empty array
const someObjectValue = myObject["myKey"] // returns the value of an object's key

Please note you can also fetch an object value by using dot instead of brackets:

// They are the same thing.
const value = myObject["myKey"];
const sameValue = myObject.myKey;

They're basically two different ways of achieving the same thing.

There is one difference, thought. With brackets you can assign otherwise non-allowed keys to objects.

Example:

const myObject = {};

// Set
myObject.0 = "Hello!"; // throws error
myObject[0] = "Hello!"; // works!

myObject.some-key = "Hello!"; // throws error
myObject["some-key"] = "Hello!"; // works!

// Get
const value = myObject.0; // throws error
const value = myObject[0]; // works!

const value = myObject.some-key; // throws error
const value = myObject["some-key"]; // works!
Claudio Holanda
  • 2,455
  • 4
  • 21
  • 25
  • You should add a note about `ReferenceError`, if you assign to `variable['key']` before declaring its value. – Akxe Jan 27 '21 at 13:38
0

In the first case you are accessing data inside an object passing the key inside the brackets, in the second one using the brackets you are declaring an Array in javascript which is a list of data. Checkout this definition of array:

Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed

You could add more items into your array like:

var myDog = {
    "name" : "Coder",
    "legs" : 4, 
    "tails" : 1, 
    "friends" : [
         "everything!",
         "a little more",
         "one more thing",
          1,
         "the previous element was a number",
         "the next will be an object",
         {name: "test"}
        ]
     };

You can also access array data passing the key value inside brackets like objects but array keys are ordered numbers called index, for example.

const myArray = ["a", "b", "c"]

console.log(myArray[0])     // a
console.log(myArray[1])     // b
console.log(myArray[2])     // c

Click here for more info about arrays