Ellatronic
Design Portfolio

Blog

JavaScript: Understanding the Weird Parts (Part 5)

JSON and Object Literals

  • JSON looks a lot like object literal syntax so a common mistake is to think they are the exact same thing.
    • JSON properties must be wrapped in quotes.
    • JSON is technically a subset of object literal syntax.
  • Anything that is valid JSON is also valid JavaScript object literal syntax but not all object literal syntax is valid JSON.
    • Like all dogs (JSON) are animals (objects) but not all animals are dogs.
JSON.stringify(objectLiteral);
  • Converts object to a JSON string, will wrap properties in quotes.
var jsonValue = JSON.parse('{"firstName": "Mary", 
                           "isAProgrammer": true}');
  • Converts JSON string to an object.

Functions are Objects

  • first class functions - everything you can do with other data types, you can do with functions; assign them to variables, pass them around, create them on the fly
  • A function is a special type of object and can have properties and methods attached to it.
  • A function's name is optional. It can be an anonymous function.
  • Think of the function code as a property attached to the function.
  • Functions can be moved around, copied, and given to other elements or areas of your code just like any other object or value.
function greet() {
    console.log('hi');
}
greet.language = 'english';
console.log(greet.language); //-> english
  • greet is the function's name. The text in the curly braces is the function's code.

Function Statements and Function Expressions

  • expression - a unit of code that results in a value; does not need to save to a variable
var a;
a = 3;
//-> 3

1 + 2;
//-> 3
  • Both of the above cases are expressions because they returned a value.
  • A statement does not return a value. Example: if statement.
function greet() { 
    console.log('hi');
} //function statement

var anonymousGreet = function() {
    console.log('hi');
} //function expression

anonymousGreet(); //-> hi
  • Function expressions are not hoisted, only the variable is hoisted.