Strange Behavior in JavaScript

Sukhpinder Singh - May 12 '21 - - Dev Community

There are numerous occasions where JavaScript behaves strangely.

I love the frameworks written on top of javascript but do not prefer to write code in javascript.

Please find below cases where javascript behave differently:

Scenario 1

As shown below, see addition and subtraction.

11+1 //12

'11'+1 //111

11-1 //10

'11'-1 //10 //What is hell? right?
Enter fullscreen mode Exit fullscreen mode

Scenario 2

JavaScript is very loosely concerning data types.

let name="Sukhpinder";setTimeout(function(){ name="Singh"});

console.log(name); //Sukhpinder
Enter fullscreen mode Exit fullscreen mode

Scenario 3

I was overwhelmed with the event loop because JS does not merely execute code from top to bottom, waiting when interrupted.

function add(a,b){ return a+b;}

//One parameter missing it wont work add(3); //Nan

//One parameter extra don't care add(1,2,3); //3
Enter fullscreen mode Exit fullscreen mode

Scenario 4

Not only data types, everything is designed very loosely coupled in JavaScript.

0.1+0.2 //0.30000000000000004

2.3*100 //229.99999999999997
Enter fullscreen mode Exit fullscreen mode

Scenario 5

Imprecise operations in Javascript, the same problem can be seen in other programming languages like Python.

console.log(!![]) //true

console.log([]==true) //false
Enter fullscreen mode Exit fullscreen mode

Scenario 6

It does not know what to say about below, which is entirely illogical.

Array.prototype.push("Hello");

let empty=[];

console.log(empty[0]); //Hello

console.log(empty.length); //0
Enter fullscreen mode Exit fullscreen mode

Overall, JavaScript is more accessible to write because for several reasons. On the other hand, JavaScript makes you feel insecure, as described in different scenarios above.

Thank you for reading and I hope you liked the article..!! Please share your thoughts in the comment section.

Buy Me A Coffee

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .