Fallenreaper
Fallenreaper

Reputation: 10684

can js objects be reassigned dynamically to a different type?

i wanted to know if js ws similar to php in the sense that I can reassign an object and it will work. Ex: Click 1 button and X = "5", Click other button and Y = new Array(4); X = Y;

I was unsure if js was just pointers and would allow this, or if there was some sort of typecast error.... as my default use is that of a string. When they click the alternate button essentually, they are going to try to append to it or just convert it to an array.

Maybe an easy way around this is just to make it be an array from the getgo, and just reference 0 unless otherwise told.

Thoughts?

Upvotes: 0

Views: 66

Answers (3)

NimChimpsky
NimChimpsky

Reputation: 47290

Its called dynamic typing and can have many benefits.

The tripe equals operator stops any type conversion.

Upvotes: 0

jackwanders
jackwanders

Reputation: 16020

Javascript is loosely typed; any variable can be reassigned to any value at any time.

var X = 5;
X = [1,2,3];
X = {name: 'John', town: 'London'};

No problems here. However, like @SamuelRossille said, you probably want to steer clear of such code to avoid confusion

Upvotes: 1

Samuel Rossille
Samuel Rossille

Reputation: 19858

Javascript syntax allows that. But it's not recomended to use this "feature" because it will make your code harder to understand.

Upvotes: 1

Related Questions