Hacker News new | ask | show | jobs
by z3t4 2826 days ago
If you do arithmetic's it's converted to Number, if you concatenate it's converted to string. It's however unfortunate that + is used for both concatenation and addition. The advantage is flexibility and convenience. You can for example have functions that takes almost anything as input and does what you want, so that you do not have to tell the computer in detail what types to use.

For example in Node.JS callback convention the last argument is always the callback functions, even if the function takes 4 arguments, you can put the callback in the 3:rd argument and it will figure out which one is the callback function. Then the first parameter in the callback function is either null or an Error.

Another example is RegeExp where you can write if( str.match(/foo/) ) instead of if ( str.match(foo) === null )

It's also convenient that empty strings are "falsy" which allow you to write if(!foo) instead of if( foo==="" || foo===undefined || foo===0 )

1 comments

Ok, but I really don't think that any of those conveniences outweigh the downsides of total lack of typing.

Also - you can use the == 'falsiness' whilst still in a strict scenario.

If you take the typing argument one step further, into Typescript, the advantages of just some basic typing become considerably more clear as the compiler/transpiler picks up loads of problems that wouldn't be found otherwise.

The only problem I can see is mixing strings and numbers. But there are probably more errors someone pro types would say is type errors while someone pro dynamic/loose typing would say is not ... Here's a nasty bug that took me like two hours to debug (this is only two lines, but imagine a sea of code where such thing could easily hide). Can you spot it ?

    var foo = [];
    foo.push["bar"];
You could say it's a type error. It's however not caught by neither TypeScript or Flow.
If you want to type an array, you can do that in Typescript.

let x:number[] = []; x.push("x");

Here, the transpiler will catch the error of trying to push a string to a number array.

Typing is your friend, and it will in almost all cases help you write cleaner and safer code.