Is defining every variable at the top always the best approach? - javascript

I've heard that it is a good technique to define your variables at the top of a function, so you don't end up with variable hoisting problems. This:
// Beginning of file
function something(){
var a, b, c = 1, d, e;
// Do something
}
// End of file
is a good example (excluding the bad variable names, of course).
My question is: Is this always the best approach? What if you are working with a lot of variables? Should they really all just be plopped on one line?

I'd highly suggest giving Code Complete 2 by Steve McConnell a read. His argument is that you should neither declare all of your variables in one line, nor should should declare them all at the top of a routine. So, don't do this:
function foo() {
var a,
b,
c,
d;
/**
* 20 lines that use a and b
*/
/**
* 10 lines that use c and d
*/
}
Instead, you should declare your variables close to where they are needed. In the above code, that might look like this:
function foo() {
var a,
b;
/**
* 20 lines that use a and b
*/
var c,
d;
/**
* 10 lines that use c and d
*/
}
The benefits are that you can understand at a quick glance what variables are used by a block of code by just looking at the declarations above it. You don't need to read the code to see what variables are set, just which are declared.
Don't write code for the compiler or for the computer. Write it for developers. Your code should be as easy to read as possible, and require as little effort as possible to understand a particular section of code.

"Should they really all just be plopped on one line?"
I don't think so.
Here is how I would write that (ignoring names):
function something(){
var a,
b,
c = 1,
d,
e;
// Do something
}
This only looks silly in the above because 1) the names suck 2) the variables are not assigned in the "declaration" -- most code can be written with immutable (assigned-once) variables and I find this to simplify code. I use this for multiple reasons including clarity and resistance to formatting changes (that is, I can change the initial values, add/or remove declarations, etc, without mucking about the formatting of the other lines).
"Is defining every variable at the top always the best approach?"
I don't think so.
For instance, here is how I write loops:
for (var i = 0; i < x; i++) {
var elm = elms[i];
...
}
And some people will go "BUT THE VAR IS HOISTED TO THE TOP OF THE FUNCTION!" or "A VARIABLE IS FUNCTION-SCOPED!". Well, indeed. However, that allows me to easily visually see that this is an error, even if the JavaScript engine won't help:
for (var i = 0; i < x; i++) {
var elm = elms[i];
...
}
...
// valid JS but since I consider this construct *invalid*
// I know this is a *bug* in my code
alert(elm);
As far as when I assign to variables caught in closures: it depends. If the variable is used in only a single closure I generally put it right above. This lets me know it should only be used in that closure. If the variable is shared (e.g. self) I put it above all the applicable closures -- generally in the "variable declaration section" of the function. This lets me know it has a "function-wide scope" (read: likely to be used in multiple bindings).
To address the "for-each closure issue" -- just learn the language. Keeping variable "declarations" close to the closure does not affect this in anyway. If the construct is not understood, it really doesn't matter how the code is written.
I use these approaches to/because:
Have consistent easy-to-scan code.
Write code that tells me when it's wrong.
I prefer code that is amendable to altering without changing structure.
Self-documenting code means less comments.
I like to "read vertically"
Happy coding.

In languages with block scope, it is usually recommended that variables be declared at the site of first use.
But because JavaScript does not have block scope, it is wiser to declare all of a function's variables at the top of the function. This way you don't fool yourself or other people about the variable's scope.
EDIT: Many people work with several languages simultaneously. Often JavaScript is the only one among them without the block scope.

This is a style question. Not a functionality question.
The javascript parser will take this code
function() {
dostuff();
var i = 4;
}
and turn it into :
function() {
var i;
dostuff();
i = 4;
}
As for the style question. No thank you I thought we left that behind with ANSI C.
What you want to do is declare functions at the top of their "scope"
If the "scope" of a variable is the entire function then declare them at the top. If the "scope" is a subset of a function then declare them at the start of the subset.
treat "scope" as logical scope rather then function scope.
This should ensure maximum readability.

This is really just a matter of preference. For example, if my method only contains a for loop, then I won't extract the loop variables to the top:
var func = function(arr) {
for (var i = 0, len = arr.length; i < len; i++) {
// array processing here
}
}
Almost all other times though I will place ALL variables at the top for hoisting reasons. If you find that there are too many variables at the top of your function, it could be an indication that your method is doing too much work, and should consider extracting a portion of it into some sort of helper method. This will let you organize your variables based on functionality.

I would venture to say that in older structures (such as the C\C++ days) it was important to initialize your variables and assign them a start value. But with the way things have been going, I'm finding that declaring them "when necessary" is a valid implementation. Unless scope is playing a part (for instance you need variable a not only in that function, but also in other functions, too), I would declare on-the-go.
Maybe it's just way of thinking, but I tend to declare things based on scope (If the variable is needed only within an if condition or a few lines of code, I'll declare it there (rather than at the top of my function/class). If I don't go through that code path, I think of it as saving the memory allocation and it won't be declared for "no reason".)
I could be completely wrong, however. Either way, JavaScript will allow you to declare your variables in any fashion you deem easiest to read.

Related

JS Variable Scope Lookup vs Allocation

If I am applying a function to a javascript array i.e.
var a = [1,2,3,4];
var x;
a.forEach(function(val) {
x = val + 1;
// do some stuff with x
});
Is it better to leave the variable declaration in the outer scope or to put the declaration inside the function? i.e.
var a = [1,2,3,4];
a.forEach(function(val) {
var x = val + 1;
// do some stuff with x
});
What I do not know is if the memory allocation for x is more expensive than the variable lookup process.
If you do not need the variable outside the forEach callback, put it inside. It is simply cleaner that way. Memory is not an issue.
Its better to put it into the loop. There is no performance difference. However using the scope the right way is a good starting point to detect errors:
var something = 5;
a.forEach(el => something = el);
console.log(something); // what is something? Why is it set?
What I do not know is if the memory allocation for x is more expensive than the variable lookup process
It depends. It depends on the exact code, the size of the array, how frequently the code is run, how many scopes there are between the code accessing the variable and the scope where the variable is declared, what optimizations the JavaScript engine on which the code is running does, etc.
So: Write the clearest, simplest code you can, and if you run into a performance problem related to that code, profile changes to see how to address it. Anything else is premature optimization and a waste of your time.
However: With the example given, if you declare it within the callback, x will be a local stack variable, and those are extremely cheap to allocate (in terms of execution time). I can't see that it would really matter either way (if you declare it outside, it's just one scope away), but it happens that in this case, the simplest, cleanest code (declaring it within the callback) is at least likely not to be worse than the alternative, and I'd say almost certainly better. But again: If it's an issue, profile the real code.
Practically, this change control two parameters: Scope and initiation.
Scope: if you need to use this var outside the loop, so you need to declare it out side, else you can drop it in and each iteration and the scope will declare, its probably saves memory outside the scope.
Initiation: in big programs the initiation can be critic time,
each time who the loop takes place you need to declare the var and its wasting time...

Does encapsulating Javascript code in objects affect performance?

I am wondering if it is more or less efficient to encapsulate the main body of your JavaScript code in an object? This way the entire scope of your program would be separated from other scopes like window.
For example, if I had the following code in a JavaScript file:
/* My main code body. */
var somevar1=undefined;
var somevar2=undefined;
var somevarN=undefined;
function somefunction(){};
function initialize(){/* Initializes the program. */};
/* End main code body. */
I could instead encapsulate the main code body in an object:
/* Encapsulating object. */
var application={};
application.somevar1=undefined;
application.somevar2=undefined;
application.somevarN=undefined;
application.somefunction=function(){};
application.initialize=function(){/* Initializes the program. */};
My logic is that since JavaScript searches through all variables in a scope until the right one is found, keeping application specific functions and variables in their own scope would increase efficiency, especially if there were a lot of functions and variables.
My only concern is that this is bad practice or that maybe this would increase the lookup time of variables and functions inside the new "application" scope. If this is bad practice or completely useless, please let me know! Thank you!
I’ve no idea what the performance implications are (I suspect they’re negligible either way, but if you’re really concerned, test it), but it’s very common practice in JavaScript to keep chunks of code in their own scope, rather than having everything in the global scope.
The main benefit is reducing the risk of accidentally overwriting variables in the global scope, and making naming easier (i.e. you have window.application.initialize instead of e.g. window.initialize_application).
Instead of your implementation above, you can use self-calling functions to create an area of scope just for one bit of code. This is known as the module pattern.
This has the added advantage of allowing you to create “private” variables that are only accessible within the module, and so aren’t accessible from other code running in the same global object:
/* Encapsulating object. */
var application=( function () {
var someprivatevar = null// This can't be accessed by code running outside of this function
, someprivatefunction = function () { someprivatevar = someprivatevar || new Date(); };
return {
somevar1: undefined
, somevar2: undefined
, somevarN: undefined
, somefunction: function(){}
, getInitialized: function () { return someprivatevar; }
, initialize: function (){/* Initializes the program. */ someprivatefunction(); }
};
})();
application.initialize();
application.getInitialized();// Will always tell you when application was initialized
I realize you asked a yes or no question. However, my answer is don't worry about it, and to back that up, I want to post a quote from Eloquent Javascript, by Marijn Haverbeke.
The dilemma of speed versus elegance is an interesting one. You can
see it as a kind of continuum between human-friendliness and
machine-friendliness. Almost any program can be made faster by making
it bigger and more convoluted. The programmer must decide on an
appropriate balance....
The basic rule, which has been repeated by many programmers and with
which I wholeheartedly agree, is to not worry about efficiency until
you know for sure that the program is too slow. If it is, find out
which parts are taking up the most time, and start exchanging elegance
for efficiency in those parts.
Having easy to read code is key to my issue here, so I'm going to stick with the modular approach even if there is a slightly longer lookup chain for variables and functions. Either method seems to have pros and cons as it is.
On the one hand, you have the global scope which holds several variables from the start. If you put all of your code right in the global scope, your list of variables in that scope will include your own as well as variables like innerWidth and innerHeight. The list to search through when referencing variables will be longer, but I believe this is such a small amount of overhead it is ridiculous to worry about.
On the other hand, you can add just one object to the global scope which holds all of the variables you want to work with. From inside this scope, you can reference these variables easily and avoid searching through global variables like innerWidth and innerHeight. The con is that when accessing your encapsulated variables from the global scope you would have a longer lookup chain such as: globalscope.customscope.myvar instead of globalscope.myvar or just myvar.
When I look at it this way, it seems like a very trivial question. Perhaps the best way to go about it is to just encapsulate things that go together just for the sake of decluttering code and keep focus on readability rather than having a mess of unreadable code that is only slightly more efficient.

Are there downsides to using var more than once on the same variable in JavaScript

Before asking my question, let me give a disclaimer. I know what var does, I know about block scope, and I know about variable hoisting. I'm not looking for answers on those topics.
I'm simply wondering if there is a functional, memory, or performance cost to using a variable declaration on the same variable more than once within a function.
Here is an example:
function foo() {
var i = 0;
while (i++ < 10) {
var j = i * i;
}
}
The previous could just have easily been written with the j variabled declared at the top:
function foo() {
var i = 0, j;
while (i++ < 10) {
j = i * i;
}
}
I'm wondering if there is any actual difference between these two methods. In other words, does the var keyword do anything other than establish scope?
Reasons I've heard to prefer the second method:
The first method gives the appearance of block scope when it's
actually function scoped.
Variable declarations are hoisted to
the top of the scope, so that's where they should be defined.
I consider these reasons to be good but primarily stylistic. Are there other reasons that have more to do with functionality, memory allocation, performance, etc.?
In JavaScript - The Good Parts Douglas Crockford suggests that by using the second method and declaring your variables at the top of their scope you will more easily avoid scope bugs.
These are often caused by for loops, and can be extremely difficult to track down, as no errors will be raised. For example;
function() {
for ( var i = 0; i < 10; i++ ) {
// do something 10 times
for ( var i = 0; i < 5; i++ ) {
// do something 5 times
}
}
}
When the variables are hoisted we end up with only one i. And thus the second loop overwrites the value, giving us an endless loop.
You can also get some bizarre results when dealing with function hoisting. Take this example:
(function() {
var condition = true;
if(condition) {
function f() { console.log('A'); };
} else {
function f() { console.log('B'); };
}
f(); // will print 'B'
})();
This is because function bodies are hoisted and the second function overwrites the first.
Because searching for bugs like this is hard and regardless of any performance issues (I rarely care about a couple of microseconds), I always declare my variables at the top of the scope.
There will not be any differences during execution time. There might be a imperceptibly small difference in interpretation/compilation time, but that of course will be implementation dependent. There also might be a few bytes different in the size of the file, which could also affect download time. I don't think either of these are worth being bothered about.
As you already know, any variable declaration will be hoisted to the top of the function. The important thing to note is that this occurs during the interpretation/compilation process, not during execution.
Before a function is executed, the function must be parsed. After each function is parsed, they will both have all of the variable declarations moved to the top, which means that they will be identical and there will be no execution time cost incurred.
For the same reason, there are no memory cost differences. After parsing, there will be no differences at all.
Since you are not asking about style I am not telling you which I think is better. But I will say that the only reason you should prefer one over the other is style.
Style
Subjective. I prefer the approach that keeps the var close to the usage site, but I always keep the scoping rules in mind. I also avoid combining multiple declarations into a single var and prefer multiple var statements.
Memory allocations
Variables are not objects: not applicable. Due to the hoisting rules, the variable "slot" has the same lifetime in all cases.
Performance
No. There should be no difference in terms of performance. While an implementation could technically really mess this up - they don't.
The only way to answer this (besides looking at every implementation in minutia) is to use a benchmark.
Result: noise differences on modern browsers
The 2nd way saves the 4 characters in the the javascript file - but in terms of the actual code generation or execution speed I don't believe there is any difference at all.
Your example will function exactly the same. It could be even more unclear than your example to use 'var' in a block, though. Say, for example you want to update a variable that is outside of the scope (by not using 'var') conditionally, or use a local 'var' instead. Even if that condition is false, 'j' becomes local. It turns out not to be as trivial as it appears to do that.
var j = 1;
function foo () {
j = 2;
if (false) {
var j = 3; // makes `j = 2` local simply for being in the same function
}
console.log(j);
}
foo(); // outputs 2
console.log(j); // outputs 1
That's one tricky case that may not work as you expect just by looking at the code.
There are no downsides to declaring every 'var' on top, only up-sides.

Why is Coffeescript of the opinion that shadowing is a bad idea

I've wanted to switch to Coffeescript for a while now and yesterday I thought I'm finally sold but then I stumbled across Armin Ronachers article on shadowing in Coffeescript.
Coffeescript indeed now abandoned shadowing, an example of that problem would be if you use the same iterator for nested loops.
var arr, hab, i;
arr = [[1, 2], [1, 2, 3], [1, 2, 3]];
for(var i = 0; i < arr.length; i++){
var subArr = arr[i];
(function(){
for(var i = 0; i < subArr.length; i++){
console.log(subArr[i]);
}
})();
}
Because cs only declares variables once I wouldn't be able to do this within coffeescript
Shadowing has been intentionally removed and I'd like to understand why the cs-authors would want to get rid of such a feature?
Update: Here is a better example of why Shadowing is important, derived from an issue regarding this problem on github
PS: I'm not looking for an answer that tells me that I can just insert plain Javascript with backticks.
If you read the discussion on this ticket, you can see Jeremy Ashkenas, the creator of CoffeeScript, explaining some of the reasoning between forbidding explicit shadowing:
We all know that dynamic scope is bad, compared to lexical scope, because it makes it difficult to reason about the value of your variables. With dynamic scope, you can't determine the value of a variable by reading the surrounding source code, because the value depends entirely on the environment at the time the function is called. If variable shadowing is allowed and encouraged, you can't determine the value of a variable without tracking backwards in the source to the closest var variable, because the exact same identifier for a local variable can have completely different values in adjacent scopes. In all cases, when you want to shadow a variable, you can accomplish the same thing by simply choosing a more appropriate name. It's much easier to reason about your code if a local variable name has a single value within the entire lexical scope, and shadowing is forbidden.
So it's a very deliberate choice for CoffeeScript to kill two birds with one stone -- simplifying the language by removing the "var" concept, and forbidding shadowed variables as the natural consequence.
If you search "scope" or "shadowing" in the CoffeeScript issues, you can see that this comes up all the time. I will not opine here, but the gist is that the CoffeeScript Creators believe it leads to simpler code that is less error-prone.
Okay, I will opine for a little bit: shadowing doesn't matter. You can come up with contrived examples that show why either approach is better. The fact is that, with shadowing or not, you need to search "up" the scope chain to understand the life of a variable. If you explicitly declare your variables ala JavaScript, you might be able to short-circuit sooner. But it doesn't matter. If you're ever unsure of what variables are in scope in a given function, you're doing it wrong.
Shadowing is possible in CoffeeScript, without including JavaScript. If you ever actually need a variable that you know is locally scoped, you can get it:
x = 15
do (x = 10) ->
console.log x
console.log x
So on the off-chance that this comes up in practice, there's a fairly simple workaround.
Personally, I prefer the explicitly-declare-every-variable approach, and will offer the following as my "argument":
doSomething = ->
...
someCallback = ->
...
whatever = ->
...
x = 10
...
This works great. Then all of a sudden an intern comes along and adds this line:
x = 20
doSomething = ->
...
someCallback = ->
...
whatever = ->
...
x = 10
...
And bam, the code is broken, but the breakage doesn't show up until way later. Whoops! With var, that wouldn't have happened. But with "usually implicit scoping unless you specify otherwise", it would have. So. Anyway.
I work at a company that uses CoffeeScript on the client and server, and I have never heard of this happening in practice. I think the amount of time saved in not having to type the word var everywhere is greater than the amount of time lost to scoping bugs (that never come up).
Edit:
Since writing this answer, I have seen this bug happen two times in actual code. Each time it's happened, it's been extremely annoying and difficult to debug. My feelings have changed to think that CoffeeScript's choice is bad times all around.
Some CoffeeScript-like JS alternatives, such as LiveScript and coco, use two different assignment operators for this: = to declare variables and := to modify variables in outer scopes. This seems like a more-complicated solution than just preserving the var keyword, and something that also won't hold up well once let is widely usable.
The main issue here isn't shadowing, its CoffeeScript conflating variable initialization and variable reassignment and not allowing the programmer to specify their intent exactly
When the coffee-script compiler sees x = 1, it has no idea whether you meant
I want a new variable, but I forgot I'm already using that name in an upper scope
or
I want to reassign a value to a variable I originally created at the top of my file
This is not how you forbid shadowing in a language. This is how you make a language that punishes users who accidentally reuse a variable name with subtle and hard to detect bugs.
CoffeeScript could've been designed to forbid shadowing but keep declaration and assignment separate by keeping var. The compiler would simply complain about this code:
var x = blah()
var test = ->
var x = 0
with "Variable x already exists (line 4)"
but it would also complain about this code:
x = blah()
test = ->
x = 0;
with "Variable x doesn't exist (line 1)"
However, since var was removed, the compiler has no idea whether you meant meant "declare" or "reassign" and can't help.
Using the same syntax for two different things is not "simpler", even though it may look like it is. I recommend Rich Hickey's talk, Simple made easy where he goes in depth why this is so.
Because cs only declares variables once the loop will not work as intended.
What is the intended way for those loops to work? The condition in while i = 0 < arr.length will always be true if the arr is not empty, so it will be an infinite loop. Even if it's only one while loop that won't work as intended (assuming infinite loops are not what you're looking for):
# This is an infinite loop; don't run it.
while i = 0 < arr.length
console.log arr[i]
i++
The correct way of iterating arrays sequentially is using the for ... in construct:
arr = [[1,2], [1,2,3], [1,2,3]]
for hab in arr
# IDK what "hab" means.
for habElement in hab
console.log habElement
I know that this answer sound like going off on a tangent; that the main point is why CS discourages variable shadowing. But if examples are to be used to argument in favour of or against something, the examples ought to be good. This example doesn't help the idea that variable shadowing should be encouraged.
Update (actual answer)
About the variable shadowing issue, one thing that it worth clarifying is that the discussion is about whether variable shadowing should be allowed between different function scopes, not blocks. Within the same function scope, variables will hoist the whole scope, no matter where they are first assigned; this semantic is inherited from JS:
->
console.log a # No ReferenceError is thrown, as "a" exists in this scope.
a = 5
->
if someCondition()
a = something()
console.log a # "a" will refer to the same variable as above, as the if
# statement does not introduce a new scope.
The question that is sometimes asked is why not adding a way to explicitly declare the scope of a variable, like a let keyword (thus shadowing other variables with the same name in enclosing scopes), or make = always introduce a new variable in that scope, and have something like := to assign variables from enclosing scopes without declaring one in the current scope. The motivation for this would be to avoid this kind of errors:
user = ... # The current user of the application; very important!
# ...
# Many lines after that...
# ...
notifyUsers = (users) ->
for user in users # HO NO! The current user gets overridden by this loop that has nothing to do with it!
user.notify something
CoffeeScript's argument for not having a special syntax for shadowing variables is that you simply shouldn't do this kind of thing. Name your variables clearly. Because even if shadowing would be allowed it would be very confusing to have two variables with two different meanings with the same name, one in an inner scope and one in an enclosing scope.
Use adequate variable names according to how much context you have: if you have little context, e.g. a top-level variable, you'll probably need a very specific name to describe it, like currentGameState (especially if it's not a constant and its value will change with time); if you have more context, you can get away with using less descriptive names (because the context is already there), like loop variables: killedEnemies.forEach (e) -> e.die().
If you want to know more about this design decision, you may be interested in reading Jeremy Ashkenas opinions in these HackerNews threads: link, link; or in the many CoffeeScript issues where this topic is discussed: #1121, #2697 and others.

What is the reason behind JSLint saying there are "too many var statements"

JSLint (with the onevar flag turned on) is flagging some javascript code that I have with the following:
Problem at line 5 character 15: Too many var statements.
I am happy to fix these errors, but I'd like to know, am I doing it for performance or because it is just a bad practice and has a greater potential to introduce bugs in my javascript code. What is the reason behind the onevar flag?
I did look at the JSLint docs for the var keyword but it doesn't specifically talk about why multiple var statements in the same function are bad.
Here is an attempt at an example. Explain how the code will benefit from only having 1 var statement:
function Test(arg) {
var x = arg + 1,
y = cache.GetItem('xyz');
if (y !== null) {
// This is what would cause the warning in JSLint
var request = ajaxPost(/* Parameters here */);
}
}
Javascript does not have block scope. In other languages with it (like c), if you declare a variable in the if statement, you can not access it outside of it, but in javascript you can. The author of JSLint believes it is a bad practice, since you (or other readers) might get confused and think that you can no longer access the variable, but you actually can. Therefore, you should declare all your variables at the top of the function.
The official reason is here, by Douglas Crockford.
To quote:
In many languages, a block introduces a scope. Variables introduced in
a block are not visible outside of the block.
In JavaScript, blocks do not introduce a scope. There is only
function-scope. A variable introduced anywhere in a function is
visible everywhere in the function. JavaScript's blocks confuse
experienced programmers and lead to errors because the familiar syntax
makes a false promise.
JSLint expects blocks with function, if, switch, while, for, do, and
try statements and nowhere else.
In languages with block scope, it is usually recommended that
variables be declared at the site of first use. But because JavaScript
does not have block scope, it is wiser to declare all of a function's
variables at the top of the function. It is recommended that a single
var statement be used per function. This can be declined with the vars
option.
Just declare your vars in one place like this:
var request,x,y;
If the "onevar" option is set to true if only one var statement per function is allowed.
if (funct['(onevar)'] && option.onevar) {
warning("Too many var statements.");
}
The reasoning is already described.
Recommendation is to use this form:
var myVar1 = document.getElementById("myDiv1"),
myVar2 = document.getElementById("myDiv2");
or this:
var myVar1, myVar2;
myVar1 = document.getElementById("myDiv1");
myVar2 = document.getElementById("myDiv2");
But this doesn't look very nice, especially if you want to document vars.
So you can just disable this warning temporarly:
/*jslint vars: true*/
/**
* #returns {HTMLDivElement}
*/
var myVar1 = document.getElementById("myDiv1");
/**
* #returns {HTMLDivElement}
*/
var myVar2 = document.getElementById("myDiv2");
/*jslint vars: false*/
Warning: make sure that this is done at the top of a function.
I think this is done because jslint couldn't reliably determine if vars were declared at the top of function or not.
Just a guess here, but it may be time for functional decomposition. Functions should do one thing and do it well.
Too many vars is suggestive of a function that's trying to do too much. Or a case where you should be using an array.
The idea is that you should use an object instead of individual vars. So where you have got:
var x = arg + 1,
y = cache.GetItem('xyz');
Change it to:
var dimensions = {};
dimensions.x = arg + 1;
dimensons.y = cache.GetItem('xyz');
dimensions.request = ...
You can then access these variables through the object, its neater to have one object per function to contain that functions variables. Then you won't get the warning.

Categories