Category Archives: JavaScript

Read Only Variables in Javascript

It is not recommended to define variables in the global scope.

However, if you need to, you should prevent the scenario that another developer (or you someplace else in your code) will override it.

If you don’t have to support old browsers, use Object.defineProperty:

Object.defineProperty(window,”e5Var”,{value: 1, writeable: false});
e5Var = 2;
console.log(e5Var); //1

Still, if someone redeclares the variable further in the code using “var” it will not work.

Object.defineProperty(window,”e5Var”,{value: 1, writeable: false});
var e5Var = 2;
console.log(e5Var); //2


Function Templates at Work

Ever since I’ve read Angus Croll’s post “Understanding javascript closures” I’ve been intrigued by the idea of creating function templates with closures, but until now it was never the suitable solution for my needs.

Last week the opportunity finally showed up…

I have a web application that does a lot of asynchronous work on the server, and uses to communicate the progress status to the client.

I was asked to create a REST API for this application.

The challenge was to keep the usage the same in the web app, while supressing the progress report in the REST API and sending JSON to the response on success or failure.

The web app needs to be available always in order to emit messages. The API needs the response stream available when  the process ends.

Passing these variables to all of the functions would be possible, but not very elegant.

The solution I chose was to encapsulate the communication function.

for the web app I created a function template that closes on the socket id, and for the API I created a function template that closes on the “res” variable.

The products of these templates were passed as parameters to the functions that do the actual work, and called whenever the progress status changed.

This is a simplified version of the result :

exports.startProcessAPI = function (req, res) {

var templateReportFunc = function (res)  {

return function (report) {



},reportFunc = templateReportFunc(res);



exports.startProcess = function (socket) {

var templateReportFunc = function (socket_id)  {

return function (report) {

io.sockets[socket_id].emit("report sent", report);


},reportFunc = templateReportFunc(;




Creating function templates in order to “close” on variables that are useful further in the code’s execution can be very helpful, especially when there are separate execution paths that require different variables.