Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a variable be treated like an object? [closed]

Tags:

javascript

This is something which I am confused.

I can define perfectly an object like this :

var person = {};

and use the dot notation to assign properties, however I have seen a simple definition like this :

var person;

and then uses

person.setName = 'Some cool name';

Does Javascript treat it as object even when is not declared as object way ? Or is that something else?

like image 267
ricardoorellana Avatar asked Mar 23 '26 00:03

ricardoorellana


1 Answers

Does Javascript treat it as object even when is not declared as object way ?

An object is a value, a variable is a container for a value. The default value of an uninitialized variable is undefined:

var person;
// same as
var person = undefined;

undefined is not an object and cannot be treated as such. The code you posted would throw an error.

> var person;
> person.setName = 'Some cool name';
Uncaught TypeError: Cannot set property 'setName' of undefined(…)
like image 107
Felix Kling Avatar answered Mar 24 '26 14:03

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!