This week's book giveaway is in the Server-Side JavaScript and NodeJS forum.
We're giving away four copies of Modern JavaScript for the Impatient and have Cay Horstmann on-line!
See this thread for details.
Win a copy of Modern JavaScript for the Impatient this week in the Server-Side JavaScript and NodeJS forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Modern JavaScript for the Impatient: safe programming?

 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a previous post you mentioned 'safe' programming. Do you have any specific reccomendations?
Thanks, Tom
 
author
Posts: 280
31
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Of course, safety is a big subject. But let's start with the basics. When you use a language that isn't statically typed, it is much more common to write code that runs and then does something unintended. JavaScript makes it worse by silently allowing type conversions instead of throwing an exception. Lots of values can be converted to numbers, and everything can be converted to strings, and there are confusing rules what gets converted when.

My recommendation is to program as if you used a statically typed language. In your head, and in your documentation, have a fixed type for each variable, function parameter and return value. And don't rely on conversions.

It is ok to say "this parameter is a string or a list of strings". That is common in JavaScript. Just be sure to document it.

I draw the line at "this parameter is a number or a string containing a number". Just constrain it to a number, and pass parseFloat(str) if you have a string.

And it pays off to be very clear about "string or undefined", or "string or null", or "string or null or undefined". Don't be tempted by shortcuts with == or "Boolishness".  

Isn't that an advertisement for TypeScript? It would be if TypeScript was better aligned with modern JavaScript.

Of course, getting the types right is only one part of safety. You still have to worry about cross-site risks, cookie theft, injection attacks, etc. That is independent of the language.

Cheers,

Cay
 
Consider Paul's rocket mass heater.
    Bookmark Topic Watch Topic
  • New Topic