Alex LaFroscia
@alexlafroscia
var cube, square, add;
square = function(x) {
return x * x;
};
cube = function(x) {
return square(x) * x;
};
my_function = function(x, y) {
var a, b;
a = cube(x);
b = square(y);
return a + b;
};
square = (x) -> x * x
cube = (x) -> square(x) * x
my_function = (x, y)->
a = cube x
b = square y
a + b
Net result: Less code!
var array, countNumbers, sayKeys;
array = [1, 2, 3, 4, 5];
object = {
name: 'Alex',
age: 19,
job: 'programmer'
};
countNumbers = function(arr) {
var int, i, len;
for (i = 0, len = arr.length; i < len; i++) {
int = arr[i];
console.log(int);
}
};
sayKeys = function(obj) {
var key, value;
for (key in obj) {
value = obj[key];
console.log("" + key + ": " + value);
}
};
countNumbers(array);
sayKeys(object);
array = [1, 2, 3, 4, 5]
object =
name: 'Alex'
age: 19
job: 'programmer'
countNumbers = (arr)->
for int in arr
console.log int
sayKeys = (obj)->
for key,value of obj
console.log "#{key}: #{value}"
countNumbers array
sayKeys object
var Student, alex;
Student = (function() {
function Student(options) {
this.name = options.name,
this.age = options.age,
this.job = options.job;
}
Student.prototype.introduce = function() {
return alert("Hello, I'm " + this.name);
};
return Student;
})();
alex = new Student({
name: 'Alex',
age: 19,
job: 'programmer'
});
alex.introduce();
class Student
constructor: (options)->
{@name, @age, @job} = options
introduce: ->
alert "Hello, I'm #{@name}"
alex = new Student
name: 'Alex'
age: 19
job: 'programmer'
alex.introduce() # Hello, I'm Alex
alex = new Student
name: 'Alex'
age: 19
# Executes because both exist
if alex?.name?
console.log alex.name
# Doesn't execute because alex.job
# is null
if alex?.job?
console.log alex.job
# Doesn't execute because method doesn't
# exist
alex.someOtherMethod?()
# Doesn't execute because peter is null
if peter?.job?
console.log peter.job
Check if a variable or property is null
Check if a method exists
"Soaking"
# Inline "if" statements
homeworkComplete = false
submitTheHomework() if homeworkComplete
# Multi-Line Strings
theString = """
This is my string that spans many lines.
It will preserve newlines and stuff and escape
characters where needed.
"""
# Cleaner switch statements
score = 76
grade = switch
when score < 60 then 'F'
when score < 70 then 'D'
when score < 80 then 'C'
when score < 90 then 'B'
else 'A'
# Comparisons in plain English
a = 39
return true if a is 39
return false if a is not 39
switch = true
turnOnTheLights() if switch is on