CoffeeScript Cheat Sheet

Here’s a CoffeeScript cheat sheet:

Variables

# Variable declaration
variableName = value

# Constants
CONSTANT_NAME = 42

Functions

# Function definition
square = (x) -> x * x

# Anonymous function
add = (a, b) -> a + b

# Default parameters
multiply = (a, b=2) -> a * b

Strings

# String interpolation
name = "Alice"
greeting = "Hello, #{name}!"

# Multiline strings
multiLineString = """
  This is a
  multiline string.
"""

Arrays

# Array declaration
numbers = [1, 2, 3]

# Access elements
firstNumber = numbers[0]

# Slicing
slicedArray = numbers[1..2]

Objects

# Object declaration
person =
  name: "Bob"
  age: 30

# Access properties
personName = person.name

Conditionals

# If statement
if temperature > 30
  console.log "It's hot!"

# Ternary operator
message = if score > 50 then "Pass" else "Fail"

Loops

# For loop
for number in [1..5]
  console.log number

# While loop
count = 0
while count < 5
  console.log count
  count++

Classes

# Class definition
class Animal
  constructor: (@name) ->

  makeSound: ->
    console.log "Some generic sound"

# Inheritance
class Dog extends Animal
  makeSound: ->
    console.log "Woof!"

CoffeeScript and JavaScript Interoperability

# JavaScript code within CoffeeScript
javascriptCode = '''
  var x = 10;
  console.log(x);
'''
eval(javascriptCode)

Function Binding

# Binding functions to a context
class MyClass
  constructor: ->
    @value = 42

  getValue: ->
    console.log @value

# Create an instance
obj = new MyClass()

# Bind function to the instance
boundFunction = obj.getValue.bind(obj)

# Now calling boundFunction maintains the context
boundFunction()

This CoffeeScript cheat sheet covers some basic syntax and features. CoffeeScript is designed to be a more concise and readable alternative to JavaScript. For more detailed information, refer to the official CoffeeScript documentation.