Skip to content
Back to posts

Useful JavaScript Patterns

Reusable JavaScript snippets for random integers, page-exit warnings, and prototype- versus closure-based objects.

Generate a random integer from m to n

JavaScript has no direct function for generating a number within a range. Math.random() returns a pseudorandom floating-point number from 0 up to, but not including, 1. It can be used to generate an integer in any range:

function getRandom(floor, ceil) {
return parseInt(Math.random() * (ceil - floor + 1) + floor)
}

Warn before closing a tab

Bind the beforeunload event. Its return value has a special purpose: preventing users from accidentally closing a page and losing edits. There is no need to call confirm; return the warning text instead:

window.onbeforeunload = function () {
return "Your changes have not been saved";
};

The warning would also appear during a form submission, when it is unnecessary. Clear the handler in the form’s submit function:

window.onbeforeunload = null;

Construct an object with a closure

For the same get_name() method, the closure pattern is faster.

Prototype pattern:

var X = function(name){ this.name = name; }
X.prototype.get_name = function() { return this.name; };

Closure pattern:

var Y = function(name) {
var y = { name: name };
return { 'get_name': function() { return y.name; } };
};

Originally published on SegmentFault.

Copyright notice

Unless otherwise stated, quietin owns the copyright in all articles. All rights reserved. Except as permitted by law or with prior written permission, reproduction or republication, in whole or in part, is prohibited. Permitted quotations must credit the author and link to the original article.