0

I am new to web programming; trying to add custom properties to Javascript in-build object. The below code works as expected.

window.myName = "John 1";
alert(window.myName);  // Displays 'John 1'

However, the below code displays 'Undefined', would like to understand why it so?.

window.myName.lastName = "John 2"; 
alert(window.myName.lastName); // Displays 'Undefined', why?
Dhanapal
  • 14,239
  • 35
  • 115
  • 142
  • I wonder how you missed that `Uncaught TypeError: Cannot set property 'lastName' of undefined` – Alon Eitan Feb 19 '18 at 12:03
  • The cause of this behaviour is mentioned in the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Distinction_between_string_primitives_and_String_objects. The statement `window.myName.lastName = "John 2"` generates a temporary `String` object that wraps the value of `window.myName`. The property `lastName` of this temporary object is set to `"John 2"`, the literal string stored in `windows.myName` is not affected. The temporary object vanishes as the statement completes. – axiac Feb 19 '18 at 12:16

2 Answers2

2

This undefined is because you define an string not an object in the first step:

window.myName = "John 1";

myName is defined, but is a string var, not an object, thus is can not have properties as you can read in documentation

Knowing this.... you can get your expected result defining myName as an object:

window.myName = {}
window.myName.lastName = "John 2"; 

You will get a result when

window.myName.lastName

OUTPUT:

"John 2"
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
  • I think OP expected the string to act like an object, something which your answer doesn't cover – Adelin Feb 19 '18 at 12:03
  • I'd also add that OP can use `window.myName = new String("John 1")`, in which case he/she can assign properties – Adelin Feb 19 '18 at 12:08
1

You are adding property in object that object is not defined so first defined object and after add dynamic property. Check below-

if(typeof window.myName ==="undefined") {
    window.myName = {};  // If object is not defined then define empty object myname
}
window.myName.lastName = "John 2"; 
alert(window.myName.lastName); // Now it will show John2
Devraj verma
  • 407
  • 3
  • 14