What is the difference between request.cookies['name'] and request.cookies.name in Node.js + Express

Consider I am saving a cookie in my Node.js app where I am using express framework's cookieParser middleware.

app.use(express.cookieParser());

app.get('/setCookie', function(req, res){
   res.cookie('String_cookieName', 'String_value', { expires: new Date(Date.now() + 18000000), httpOnly: true }); // +5 Hours expiry
});

And while reading them back, I came across two choices:

  1. request.cookies['String_cookieName']
  2. request.cookies.name

Both will return me the string_value, which I have set for my cookie ('String_cookieName') else if expired undefined will be returned.

But my question is which one is faster/efficient in terms of performance?

Request.cookies is just an object. You can access any member of an object by using either of the methods that you wrote. object.xxx is typically used when you already know the name of the field you are accessing, where as brackets are generally used when the field name is dynamic; for example:

var variable = "foo";
object[variable] = "bar";

variable = "test";
object[variable] = "qwax"

console.log(object.foo); //"bar"
console.log(object.test); //"qwax"

As far as I know, neither is significantly faster than the other, so if you are accessing a static field, you can use them interchangeably.

The performance is effectively the same, see jsperf.

A lot of the cookies examples use square brackets with the property as a string because often have characters which are not directly accessible using using dot notation.

Example:

cookies['connect.sid']  // OK
cookies.connect.sid     // error

There is no difference. It's just JavaScript has two ways of accessing fields of objects.

On my opinion it is better to use plain notation like request.cookies.name then request.cookies['name'] unless you are looping through many fields of an object and apply the same action for each of them.

//lets say you have object like one below: var someObj = {};
someObj.x1 = 1; 
someObj.x2 = 2; 
someObj.x3 = 3; 
someObj.x4 = 4;
someObj.x5 = 5; 
... 
someObj.x20 = 20;

//And if you want to output properties 3 to 12 
//you can do like that
for(var i = 3; i<12; ++i)
{
   console.log(someObj['x' + i]); 
}

Otherwie just use plain notation, that way you'll keep code more readabale, and it will be easier to understand by fellow developers