3

I've seen developers declare an empty object and later assign properties and values to it but I mostly create an object and initialize the properties and values. Example

const data = {}
data.name = "John Doe";
data.age = 60;

What I mostly do is :

const data = {
name: "John Doe",
age: 60
}

I will like to know the difference between the two and why will you pick one over the other. Thanks

2
  • 3
    There isn't any difference in the result. I think some people whom have come from other languages than JavaScript tend to use paradigms that apply to their learned language but don't necessarily apply to JavaScript. Commented Jul 23, 2021 at 20:46
  • 1
    Use the second (albeit with indentation) - it's less to type, does not repeat the name data, and makes the structure of the object immediately visible. Commented Jul 24, 2021 at 13:59

2 Answers 2

2

Technically there is not much difference if you are declaring and assigning values immediately. But if you have to populate conditionally then the first option is better. However you can also conditionally update a populated object.

Sign up to request clarification or add additional context in comments.

Comments

1

Declaring objects in Javascript is easiest than other programming languages. For example in C# (or Java), first you must declare structure of object, then you create an instance of that.

using System;

namespace Example
{
    public struct Person
    {
        public string Name;
        public int Age;
        public Person(string name, int age)
        {
            Name = name;
            Age = age;
        }
    }

    public class Application
    {
        static void Main()
        {
            Person p1 = new Person("John Doe", 60);
            Console.WriteLine("p1 Name = {0} Age = {1}", p1.Name, p1.Age);
        }
    }
}

But in Javascript you can declare structure of object or not. Even you can modify that structure after declaring. That's amazing (maybe not). This feature of Javascript can produce many problems.

So, there is no difference. But if you declare the structure, code will be more cleaner.

For more information:

Comments

Your Answer

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.