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);

0

1 Answer 1

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.

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

1 Comment

A good answer that can become even better if you can add a link to an official documentation page that backs up your statement.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.