Search code examples
javascriptoopobjectkey

What is the difference between obj[name] and obj['name'] in JavaScript


I have an Object 'Obj' with property name.

var Obj = {name: "NamePropertyValue", '': "EmptyPropertyValue", null: 'NullPropertyValue'}

console.log(Obj["name"]);  >>> Output is : NamePropertyValue

console.log(Obj["null"]);  >>> Output is : NullPropertyValue
console.log(Obj[null]);  >>> Output is : NullPropertyValue

But for below case output is EmptyPropertyValue and not NamePropertyValue. WHY?

console.log(Obj[name]);  >>> Output is : EmptyPropertyValue

What is 'name' in Javascript?Why by default it has empty string value and not 'undefined'

var abc;    
console.log(abc);  >>> undefined
var name;
console.log(name);  >>>      (it gives empty string and not undefined. Why?)

Solution

  • What is the difference between obj[name] and obj['name'] in JavaScript

    name is a variable. 'name' is a string.

    The value between the square brackets is always evaluated as a string.

    var name = "name";
    Obj[name] === Obj["name"]
    
    var name = "other";
    Obj[name] !== Obj["name"]
    

    What is 'name' in Javascript?Why by default it has empty string value and not 'undefined'

    It is the name of the window.