Login Register






javascript confusion filter_list
Author
Message
javascript confusion #1
While learning javascript i got confused and i need help figuring out the difference between :
var n=1    and var n=new Number(1);
var text="hello"   and var text=new String("hello");
and same for arrays .
can someone clarify this for me ?


Everyone should learn how to code, it teaches you how to think.

You don't have to be a Genius to know how to code you just need to be determined.

The computer is incredibly fast, accurate, and stupid; man is unbelievably slow, inaccurate, and brilliant; together they are powerful beyond imagination.

Reply

RE: javascript confusion #2
By doing 'var = Number(1)' you are specifying that the variable is a number.
For numbers it doesen't realy matter, but if you specify 'Date(1)' the system knows it's a date, not a number.
In JS var can have multiple types so by using 'Something(something)' you make sure that your variable is being stored as the type you want it to be stored.
I don't know how to explain this any better, hope this helps.

Reply

RE: javascript confusion #3
about date your right but for stings numbers and booleans using var is the same at least for me,am not sure but ...
(This post was last modified: 01-30-2017, 06:02 PM by Vi-Sion.)


Everyone should learn how to code, it teaches you how to think.

You don't have to be a Genius to know how to code you just need to be determined.

The computer is incredibly fast, accurate, and stupid; man is unbelievably slow, inaccurate, and brilliant; together they are powerful beyond imagination.

Reply

RE: javascript confusion #4
JavaScript, similar to Java, has implicit constructors for many classes, so the examples you listed are equivalent. The reason Number has a constructor is JavaScript has no primitive types (afaik), so it's not a wrapper like the Java Integer class, but an explicit constructor. You could copy the example for the strings directly to Java, replacing "var" with "String", and it would work perfectly fine.
Code:
> "hello"===String("hello") true > 8===Number(8) true

With arrays, the explicit array constructor created an array with n empty spaces
Code:
> var arr=new Array(4); > arr [ , , ,  ] > arr.length 4

A fair warning, JavaScript is a fickle bitch that makes no sense at times. For example:
Code:
> ++[[]][+[]]+[+[]]+[] '10'



(01-30-2017, 05:44 PM)Vi-Sion Wrote: while this didn't work
Code:
function tellFortune(jobTitle, location, partner, numKids) {    document.write('You will be a ' + jobTitle + ' in ' + location + ' and married to ' +   partner + ' ' + ' with ' + numKids + ' kids.';); }

could someone explain why ?

This doesn't work because you have a semicolon at the end of your string, inside the parenthesis. Fix:
Code:
document.write('You will be a ' + jobTitle + ' in ' + location + ' and married to ' + partner + ' ' + ' with ' + numKids + ' kids.');
(This post was last modified: 01-30-2017, 06:22 PM by Inori.)
It's often the outcasts, the iconoclasts ... those who have the least to lose because they
don't have much in the first place, who feel the new currents and ride them the farthest.

Reply

RE: javascript confusion #5
(01-30-2017, 06:04 PM)Inori Wrote: JavaScript, similar to Java, has implicit constructors for many classes, so the examples you listed are equivalent. The reason Number has a constructor is JavaScript has no primitive types (afaik), so it's not a wrapper like the Java Integer class, but an explicit constructor. You could copy the example for the strings directly to Java, replacing "var" with "String", and it would work perfectly fine.
Code:
> "hello"===String("hello") true > 8===Number(8) true

With arrays, the explicit array constructor created an array with n empty spaces
Code:
> var arr=new Array(4); > arr [ , , ,  ] > arr.length 4

A fair warning, JavaScript is a fickle bitch that makes no sense at times. For example:
Code:
> ++[[]][+[]]+[+[]]+[] '10'



(01-30-2017, 05:44 PM)Vi-Sion Wrote: while this didn't work
Code:
function tellFortune(jobTitle, location, partner, numKids) {    document.write('You will be a ' + jobTitle + ' in ' + location + ' and married to ' +   partner + ' ' + ' with ' + numKids + ' kids.';); }

could someone explain why ?

This doesn't work because you have a semicolon at the end of your string, inside the parenthesis. Fix:
Code:
document.write('You will be a ' + jobTitle + ' in ' + location + ' and married to ' + partner + ' ' + ' with ' + numKids + ' kids.');

i noticed the semicolon error thats why i've edited my post .
So from what i've understood going withvar or creating an object using new is quite the same and i could use both , correct me if i'm wrong.


Everyone should learn how to code, it teaches you how to think.

You don't have to be a Genius to know how to code you just need to be determined.

The computer is incredibly fast, accurate, and stupid; man is unbelievably slow, inaccurate, and brilliant; together they are powerful beyond imagination.

Reply

RE: javascript confusion #6
(01-30-2017, 06:36 PM)Vi-Sion Wrote: So from what i've understood going with var or creating an object using new is quite the same and i could use both , correct me if i'm wrong.

You can use both, but it's better to use the implicit constructor if it's available as it follows convention.
It's often the outcasts, the iconoclasts ... those who have the least to lose because they
don't have much in the first place, who feel the new currents and ride them the farthest.

Reply

RE: javascript confusion #7
contrary to what i've seen most people say about Javascript there are primitive types. This can be confusing, however, since Javascript is so weakly typed that even primitive types can be coerced and act like an object.

Their are 6 primitive Javascript types according to official MDN Documentation:
https://developer.mozilla.org/en-US/docs...structures

They are:
boolean
null
undefined
number
string
symbol (new in ECMAScript 6)

if you create
Code:
var hello = 20
and say
Code:
typeof hello
you will get
Code:
Number
not Object.

but, this is confusing. you can also do something like this in Javascript:
Code:
var someString = "adafsd"; console.log(someString.length);
and get the length of the string. Clearly, there are no primitives then!

This is false, someString in this case is just being coerced into an Object. This String object is only used for a fraction of a fraction of a millisecond before being picked up by garbage collection, but it is there.

So, in your case,
Code:
var n=new Number(1);
is creating a new Number Object

while

Code:
var n = 1;

is creating n as a primitive type.

https://developer.mozilla.org/en-US/docs...cts/Number
^ There is the documentation for the Javascript Number() object

Because Javascript will coerce the primitive into an object temporarily, you may ask 'well can i assign values to primitives?', and the answer is... kind of, but no.
Consider this:
Code:
var primitive = "hello!"; primitive.vowels = 2; primitive.vowels; //undefined

in this case, primitive.vowels is created for a split second. BUT it is quickly picked up by garbage collection and comes out as undefined.


Objects such as Number() String() Array() only serve as wrappers around your primitive, and they can be coerced with primitives. So you can say

Code:
var someNum = new Number(4); var sumOfNum = someNum + 4; console.log(sumOfNum); // 8
so you will get 8 because the js object someNum can be coerced into a primitive.


P.S

IMO Javascript typing/coercion is can be wildly confusing in real use and certainly one of Javascripts weaknesses. It really slows down JS code since the engine has to figure out what to coerce/how to type things than if Javascript were a more strongly-typed language ultimately slowing down your code.
(This post was last modified: 01-30-2017, 07:30 PM by insidious.)
[Image: pBD38Xq.png]
Email: insidious@protonmail.ch

[+] 1 user Likes insidious's post
Reply

RE: javascript confusion #8
Your post was very helpfull thank you , one more thing what about arrays ?
array isn't a primitive type but you can do this var nbrs=[1,2,3,4];


Everyone should learn how to code, it teaches you how to think.

You don't have to be a Genius to know how to code you just need to be determined.

The computer is incredibly fast, accurate, and stupid; man is unbelievably slow, inaccurate, and brilliant; together they are powerful beyond imagination.

Reply

RE: javascript confusion #9
(01-31-2017, 12:26 PM)Vi-Sion Wrote: Your post was very helpfull thank you , one more thing what about arrays ?
array isn't a primitive type but you can do this var nbrs=[1,2,3,4];

There's nothing special about this way of declaring arrays in JavaScript, even though in other languages it might mean something different in Javascript it's all the same. As a consequence, you can expect to be able to use all the Array() Objects methods/prototypes with your array no matter how you create it.

Again, as per Javascript MDN reference (My personal favorite and imo the best js documentation out there)
The documentation describes three ways to create a Javascript Array Object:
Code:
var arr = [element0, element1, ..., elementN]; var arr = new Array(element0, element1[, ...[, elementN]]); var arr = new Array(arrayLength);

These are all essentially equal and really just depend on your own preferences/use case for declaring a Javascript Array Object.

I suppose the creators of JavaScript did not see a need for a static array implementation, one in which you would not be able to dynamically add or remove elements/change the size of the array since it is stored on the Stack. In other languages, and where I suspect your confusion stems from, a static implementation may be preferred since it's simpler, more efficient, and faster than allocating memory on the heap and dynamically creating your arrray that way. This static implementation would use the syntax for creating an array how you describe. For example, in C creating a static array would look like this:
Code:
int main() { static int arr[10]; // static array of size 10 OR int arr = { 10, 4, 3, 2, 1} // fixed-length array stored on Stack of size 5 }

On the other hand, a dynamic array would look something like this:
Code:
int main() { int arr = malloc(10); //array on heap of size 10 }
You could then resize that array through the
Code:
realloc
method

in Java equal implementations would be:
Code:
int[] arr = {10, 4, 3, 2} //fixed-length array on stack of length 4 ArrayList <Integer> arr = new ArrayList<Integer>(); //in Java 'ArrayList' is the dynamic version of arrays, in this case you can think of 'new' as allocating memory on the Heap

Since JavaScript was created to be largely a web-language, however, the need for this was simply not taken into account.

If you look online, and search "Javascript Arrays" you will probably see a bunch of Blog articles arguing over the different ways to instantiate/create a Javascript array. Some will say "
Code:
var arr = new Array(4);
is superior because your specifying a fixed length and that makes your code faster" or "NEVER create an array like
Code:
var arr = ['el1', 'el2', 'el3', 'el4']
it's BAD" or "ALWAYS USE
Code:
var arr = ['lol', 'the internet never lies', 'bs el']
it's the BEST way!". I like to chock these articles up to psuedo-computer science. It all comes down to the same thing, and unless there is something especially different about a certain javascript engine you are using, then it really doesn't matter and it's nothing to worry about. All these articles serve to do is confuse the humble JavaScript beginner and create pre-existing notions of false concepts.

Create your arrays however you feel is the best way for you. No matter how you do it, it's all going to be the same thing, you'll be able to use the same prototypes, the same methods, and modify them in the same ways.


P.S It's certainly worth reading through the MDN Documentation on the JavaScript Array() Object. The "Description" section may be especially of use when using JavaScript Array properties such as 'length' or clear up some confusion regarding how to access javascript elements (IE: arr[0] and why you can't do arr.0).
https://developer.mozilla.org/en-US/docs...ects/Array
(This post was last modified: 01-31-2017, 06:48 PM by insidious.)
[Image: pBD38Xq.png]
Email: insidious@protonmail.ch

[+] 1 user Likes insidious's post
Reply