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( + 18000000), httpOnly: true }); // +5 Hours expiry });

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


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?

Problem courtesy of: Amol M Kulkarni


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.


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

Solution courtesy of: ruffrey


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 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

Discussion courtesy of: Michael Tkachuk

Request.cookies is just an object. You can access any member of an object by using either of the methods that you wrote. 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(; //"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.

Discussion courtesy of: Ari

This recipe can be found in it's original form on Stack Over Flow .

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

本文标题:What is the difference between request.cookies['name'] and ...

技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(58)