Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Simple web server example - why do I have to put the property name in quotes?

Simple web server example - why do I have to put the property name in quotes?

Problem

Consider the following example:

var http = require('http');
var server = http.createServer(function(request, response) {
  response.writeHead({
    'content-type': 'text/plain'
  });
  response.end('Hello world!');
});

server.listen(8000);

Why do I have to put the content-type property name into quotes? Isn't writeHead expecting a plain JS object? Why can't I write something like:

{
  content-type: 'text/plain'
}
Problem courtesy of: helpermethod

Solution

You must quote the property name of a JavaScript object literal if the name is not a valid identifier (i.e. something you could use as a variable name); integers are apparently ok too. Since the dash character (-) is not a valid part of an identifier you must quote the string.

var o;
o = {content-type: 'text/plain'}; // => SyntaxError: Unexpected token "-"
o = {'content-type': 'text/plain'}; // => OK
o = {contentType: 'text/plain'}; // => OK
o = {123: 456}; // => OK
o = {$x: 123}; // => OK
o = {π: 234}; // => OK
Solution courtesy of: maerics

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Simple web server example - why do I have to put the property name in quotes?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×