The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Why = and not : ?

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
  • #153886

    As the title says why do we use = to assign variable a value and not :
    Fr instance here, in this function.
    Why cannot colon be used instead of equal sign..

    packet=new Object();
    return a+b;



    You are venturing into Object Oriented Programming. Read this couple of times before asking anymore question, it’s not that we don’t want to help, it’s because a lot of answers are right there in the text for you.

    In short answer to your question.

    // Object with literal notation!

    obj1 = { name: "Bruce Lee, 1" }
    alert(; // Bruce Lee, 1

    // Object using constructor function!

    function Person( name ) { = name; }
    var obj2 = new Person("Bruce Lee, 2");
    alert(; // Bruce Lee, 2

    As you can see with one you are defining literal notation and the other has to be instantiated.


    Specifically, in this case:

    packet=new Object();
    packet.color = "red";

    You have to use = because it’s an assignment. packet.color creates a new property in your object, and = "red" assigns a value to it. The object itself already exists; you’re adding to it.

    In contrast:

    packet = {
        color: "red"

    Here, you use : because you’re using a literal notation—you’re defining the entire object, and its properties, together. color: is a label for the object property, which is syntactically (if not practically) different, and "red" is the initial value.

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.