In JavaScript, arrays are objects, functions are objects, regular expressions are objects, and, of course, objects are objects.
An object is a container of properties, where a property has a name and a value. A property name can be any string, including the empty string.
An object literal is a pair of curly braces surrounding zero or more name/value pairs
Objects in JavaScript are class-free
The || operator can be used to fill in default values:
Objects are passed around by reference. They are never copied:
Every object is linked to a prototype object from which it can inherit properties. All objects created from object literals are linked to Object.prototype, an object that comes standard with JavaScript.
Functions in JavaScript are objects. Objects are collections of name/value pairs having a hidden link to a prototype object. Objects produced from object literals are linked to Object.prototype. Function objects are linked to Function.prototype (which is itself linked to Object.prototype).
Function objects are created with function literals:
Function name is optional. When it doesn’t have a name, it is called an “anonymous function”. Above example is an anoymous function; it is just assigned to a variable but it doesn’t have a name.
JS Variable Scope example:
Curly brackets don’t start a new scope. Prettty bad if you ask me (having come from Java background).
Variable Hoisting: Variable declarations are hoisted to the top of the scope (could be local/functional or global). Example:
Function Declaration Overrides Variable Declaration When Hoisted
Both function declaration and variable declarations are hoisted to the top of the containing scope. And function declaration takes precedence over variable declarations (but not over variable assignment). As is noted above, variable assignment is not hoisted, and neither is function assignment. As a reminder, this is a function assignment: var myFunction = function () {}.
Here is a basic example to demonstrate:
It is important to note that function expressions, such as the example below, are not hoisted.
In strict mode, an error will occur if you assign a variable a value without first declaring the variable. Always declare your variables.