1

Following is the javascript code which is returning undefined but didn't get why Javascript being loosely typed language is returning undefinedhere. What is going on under the hood in memory ?

var myVar = "My String";

myVar.name = "Test"; 

console.log(myVar.name);
Nesh
  • 2,389
  • 7
  • 33
  • 54

1 Answers1

5

Primitives can't have properties. Your assignment is silently failing. Use strict mode to make the error visible.

'use strict';
var myVar = "My String";

myVar.name = "Test"; 

console.log(myVar.name);

Uncaught TypeError: Cannot create property 'name' on string 'My String'

MDN has a big section on how strict mode can convert mistakes into errors.

Snow
  • 3,820
  • 3
  • 13
  • 39
  • A good answer that can become even better if you can add a link to an official documentation page that backs up your statement. – axiac Jan 26 '21 at 20:18