SlideShare a Scribd company logo
COFFEESCRIPT 
AN INTRODUCTION FOR NODE DEVELOPERS 
BY: MEHDI VALIKHANI 
SOFTWARE ENGINEER @ ALPHATISE 
Follow me: @mehdivk | 
mehdi@alphatise.com
IT'S JUST JAVASCRIPT 
COFFEESCRIPT IS A PROGRAMMING LANGUAGE THAT 
TRANSCOMPILES TO JAVASCRIPT. 
SYNTACTIC SUGAR TO JAVASCRIPT
IT'S MATURE AND PRODUCTION-READY 
DEVELOPED BY: JEREMY ASHKENAS 
INITIAL COMMIT: DECEMBER 13TH, 2009 
FIRST RELEASE: DECEMBER 24H, 2009 
VERSION 1.0: FEBRUARY 2010 
CURRENT VERSION: 1.8
WHO'S USING 
COFFEESCRIPT? 
DROPBOX 
GITHUB
WRITE LESS, DO MORE 
HUMAN-READABLE CODE 
STAY AWAY FROM WEIRD JS BEHAVIOUR 
SAY GOODBYE TO PROTOTYPE! USE CLASSES 
ANY MANY MORE ...
COFFEESCRIPT SYNTAX
NO MORE VAR ; ( ) 
async = require 'async' 
console.log async.VERSION 
var async = require('async'); 
console.log(async.VERSION);
FUNCTIONS 
IT'S PART OF OUR EVERYDAY LIFE IN JS WORLD 
LET'S BE AGILE!
addUser = (user, cb) -> 
model = new User 
#DO SOMETHING 
model.save (err, result) -> 
cb null, result 
var addUser = function(user, cb) { 
var model = new User(); 
//DO SOMETHING 
model.save(function(err, result){ 
cb(err, result); 
}); 
}
IMPLICIT RETURN 
someFunction = (param1, param2) -> 
param1 * param2 * param2 
console.log someFunction 100, 200 
var someFunction; 
someFunction = function(param1, param2) { 
return param1 * param2 * param2; 
} 
console.log(someFunction(100, 200));
OBJECTS 
GET RID OF THOSE { } , 
bus = 
routeNumber: 273 
from: 'Wynyard' 
to: 'Chatswood' 
via: 'North Sydney, Pacific Highway' 
var bus = { 
routerNumber: 273, 
from: 'Wynyad', 
to: 'Chatswood', 
via: 'North Sydney, Pacific Highway' 
}
query = 
status: 
$in: ['active', 'pending_for_approval'] 
payment: 
$nin: ['invoice', 'free'] 
tc: 
$exists: true 
var query = { 
status: { 
$in: ['active', 'pending_for_approval'] 
}, 
payment: { 
$nin: ['invoice', 'free'] 
}, 
tc: { 
$exists: true 
} 
}
STRING INTERPOLOATION 
meetup = 'Node' 
msg = "#{meetup} meeup is awsome!" 
console.log msg 
var meetup = 'Node'; 
var msg = meetup + ' meetup is awsome!'; 
console.log(msg);
CLASSES 
BETTER INHERITANCE WITHOUT PROTOTYPE 
WE SHOULDN'T USE LIBRARIES TO HAVE CLASSES IN JS
class Cache 
generateCacheKey: (key) -> 
throw new Error 'Not Implemented' 
getPeriod: -> 
120 * 60 
store: (key, data) -> 
throw new Error 'Not Implemented' 
clearCache: (key) -> 
#DO SOMETHING 
class RedisCache extends Cache 
generateCacheKey: (key) -> 
"redis_cache_#{key}" 
store: (key, data) -> 
period = @.getPeriod() 
#STORE IN REDIS
DESTRUCTURING OBJECTS 
{Router} = require 'express' 
router = new Router 
var express = require('express'); 
var Router = experss.Router; 
router = new Router();
DESTRUCTURING ARRAYS 
student = 'Mehdi Valikhani' 
[firstName, lastName] = student.split ' ' 
var student, ref, firstName, lastName; 
student = 'Mehdi Valikhani'; 
ref = student.split(' '); 
firstName = ref[0]; 
lastName = ref[1];
DESTRUCTING ARGUMENTS 
calculator = ({width, height}) -> 
width * height 
options = 
width: 10 
height: 5 
alert calculator options
EXISTENTIAL OPERATOR ? 
REMOVE THOSE NULL OR UNDEFINED CHECKES FROM CODE 
if err? 
#log to logger 
cb err 
if (typeof err !== "undefined" && err !== null) 
//log to logger 
cb(err);
INSTALL COFFEESCRIPT 
npm install -g coffee-script
EXECUTE A SCRIPT 
coffee /path/to/script.coffee
COMPILE A SCRIPT 
coffee -c /path/to/script.coffee
NODE + COFFEE 
FROM SCRATCH 
REST API DEVELOPMENT USING EXPRESS + NODE + COFFEE
CODE STRUCTURE 
+ lib 
+ books 
Book.coffee //Our Mongoose Model 
router.coffee //router for books API 
+ node_modules 
+ body-parser //from JSON responses 
+ coffee-script //compiler of Coffee files 
+ express //express framework 
app.coffee //express app config 
package.json // NO DESCRIPTION 
index.js //ACTUAL MAGIC HAPPENS HERE!
app.coffee 
bodyParser = require 'body-parser' 
express = require 'express' 
userRouter = require './lib/books/router' 
app = express() 
app.use bodyParser.json() 
app.use '/users', userRouter 
module.exports = app
lib/books/router.coffee 
{Router} = require 'express' 
Book = require './Book' 
router = new Router 
fetchBook = (req, res, next) -> 
req.paramBook = Book 
next() 
getBook = (req, res) -> 
res.json(req.paramBook) 
router.route('/:book_id') 
.all(fetchBook) 
.get(getBook) 
module.exports = router
index.js 
require('coffee-script/register'); 
var app = require('./app'); 
app.listen(1984, function(){ 
console.log('App is available via http://127.0.0.1:1984'); 
});
RUN THE APP 
node index.js 
nodemon -e js,coffee index.js
NODE + COFFEE 
AN EXISTING PROJECT
ADD FOLLOWING CODE TO YOUR STARTER FILE 
require('coffee-script/regiter');
THAT'S IT! 
Add .coffee files, write your code in coffee 
require other .js or .coffee files as always
RUN THE APP 
node index.js 
nodemon -e js,coffee index.js
DEBUGGING 
COFFEESCRIPT 
APPLICATIONS
USE "DEBUGGER" AS ALWAYS 
fetchBook = (req, res, next) -> 
debugger 
req.paramBook = Book 
next() 
node debug index.js
BUT DON'T FORGET! 
in debug mode, you will be faced with compiled 
JS code 
break in lib/books/router.coffee:11 
9 
10 fetchBook = function(req, res, next) { 
11 debugger; 
12 req.paramBook = Book; 
13 return next(); 
debug> repl 
Press Ctrl + C to leave debug repl 
> req.params.book_id 
'123' 
>
JAVASCRIPT SCOPING 
in JavaScript, the scope of a variable is 
defined by its location within the source code 
(it is apparent lexically) and nested 
functions have access to variables declared in 
their outer scope. - mozilla.org
Question: What's result of running this code? 
name = 'Alex' 
greeting = -> 
name = 'James' 
console.log "Hey #{name}!" 
greeting() 
console.log "Hey #{name}!"
A: 
> Hey James! 
> Hey James! 
B: 
> Hey James! 
> Hey Alex!
"A" IS CORRECT ANSWER 
> Hey James! 
> Hey James!
THIS IS COMPILED-TO-JS VERSION OF ABOVE 
CODE 
var greeting, name; 
name = 'Alex'; 
greeting = function() { 
name = 'James'; 
return console.log("Hey " + name + "!"); 
}; 
greeting(); 
console.log("Hey " + name + "!");
TWO IMPORTANT FACTS 
ABOUT COFEESCRIPT SCOPING 
Variable shadowing is not allowed 
variable is created at the moment of the first assignment to it
"VARIABLE SHADOWING IS NOT ALLOWED" 
DOESN'T MEAN 
YOU CAN'T DEFINE A VARIABLE MORE THAN 
ONCE IN DIFFERENT FILES 
IT MEANS 
YOU CAN'T DEFINE IT MORE THAN ONCE IN A 
SINGLE FILE
SO WHAT SHOULD I DO IF I WANT TO HAVE 
SHADOWS? 
It's not a good practice, don't do that! 
It decreases readbility of your code! 
Brings more confusion to your code 
With shadowing you can't access our variables anymore (with 
same name)
USE `` TO BRING VAR BACK 
name = 'Alex' 
greeting = -> 
` var name 
` 
name = 'James' 
console.log "Hey #{name}!" 
greeting() 
console.log "Hey #{name}!" 
It a kind of hack! Don't do that!
SHADOW IT USING FUNCTION PARAMETER 
name = 'Alex' 
greeting = (name = '')-> 
name = 'James' 
console.log "Hey #{name}!" 
greeting() 
console.log "Hey #{name}!" 
Better first solution!
USE COFEESCRIPT'S CLOSURE FEATURE 
This is much much better! 
name = 'Alex' 
greeting = -> 
do (name = '') -> 
name = 'James' 
console.log "Hey #{name}!" 
greeting() 
console.log "Hey #{name}!"
MORE INFO ABOUT LEXICAL SCOPING: 
https://github.com/raganwald-deprecated/ 
homoiconic/blob/master/2012/09/actually-YOU-dont- 
understand-lexical-scope.md 
https://github.com/raganwald-deprecated/ 
homoiconic/blob/master/2012/09/lexical-scope-in- 
coffeescript.md
USEFUL RESOURCES 
CoffeeScript Docs 
Your best friend 
CoffeeConsole: A Google Chrome Extention 
Don't translate CoffeeScript to JS, try to learn as new langage 
CoffeeScript Ristretto 
Teaches CoffeeScript as new language instrad of translating to 
JS 
The Little Book On CoffeeScript 
CoffeeScript Style Guide 
Best Practices
Thank you!

More Related Content

What's hot

Using Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyUsing Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in Ruby
LaunchAny
 
Developing apps using Perl
Developing apps using PerlDeveloping apps using Perl
Developing apps using Perl
Anatoly Sharifulin
 
Lightweight Webservices with Sinatra and RestClient
Lightweight Webservices with Sinatra and RestClientLightweight Webservices with Sinatra and RestClient
Lightweight Webservices with Sinatra and RestClient
Adam Wiggins
 
Writing Software not Code with Cucumber
Writing Software not Code with CucumberWriting Software not Code with Cucumber
Writing Software not Code with Cucumber
Ben Mabey
 
Ruby as a glue language
Ruby as a glue languageRuby as a glue language
Ruby as a glue language
quakewang
 
Ansible を完全にマスターする
Ansible を完全にマスターするAnsible を完全にマスターする
Ansible を完全にマスターする
Keisuke Kamada
 
Slim RedBeanPHP and Knockout
Slim RedBeanPHP and KnockoutSlim RedBeanPHP and Knockout
Slim RedBeanPHP and Knockout
Vic Metcalfe
 
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other ToolsCool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
Ryan Weaver
 
Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)
andrewnacin
 
Magical WordPress Development with Vagrant
Magical WordPress Development with VagrantMagical WordPress Development with Vagrant
Magical WordPress Development with Vagrant
Chris Olbekson
 
Keeping it small - Getting to know the Slim PHP micro framework
Keeping it small - Getting to know the Slim PHP micro frameworkKeeping it small - Getting to know the Slim PHP micro framework
Keeping it small - Getting to know the Slim PHP micro framework
Jeremy Kendall
 
Palestra VCR
Palestra VCRPalestra VCR
Palestra VCR
Cássio Marques
 
The Peanut Butter Cup of Web-dev: Plack and single page web apps
The Peanut Butter Cup of Web-dev: Plack and single page web appsThe Peanut Butter Cup of Web-dev: Plack and single page web apps
The Peanut Butter Cup of Web-dev: Plack and single page web appsJohn Anderson
 
Great Developers Steal
Great Developers StealGreat Developers Steal
Great Developers Steal
Ben Scofield
 
Cucumber Ru09 Web
Cucumber Ru09 WebCucumber Ru09 Web
Cucumber Ru09 Web
Joseph Wilk
 
Building Cloud Castles - LRUG
Building Cloud Castles - LRUGBuilding Cloud Castles - LRUG
Building Cloud Castles - LRUG
Ben Scofield
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Rack
sickill
 
Dancer's Ecosystem
Dancer's EcosystemDancer's Ecosystem
Dancer's Ecosystem
Alexis Sukrieh
 
Sinatra Rack And Middleware
Sinatra Rack And MiddlewareSinatra Rack And Middleware
Sinatra Rack And Middleware
Ben Schwarz
 
Quality Use Of Plugin
Quality Use Of PluginQuality Use Of Plugin
Quality Use Of Plugin
Yasuo Harada
 

What's hot (20)

Using Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyUsing Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in Ruby
 
Developing apps using Perl
Developing apps using PerlDeveloping apps using Perl
Developing apps using Perl
 
Lightweight Webservices with Sinatra and RestClient
Lightweight Webservices with Sinatra and RestClientLightweight Webservices with Sinatra and RestClient
Lightweight Webservices with Sinatra and RestClient
 
Writing Software not Code with Cucumber
Writing Software not Code with CucumberWriting Software not Code with Cucumber
Writing Software not Code with Cucumber
 
Ruby as a glue language
Ruby as a glue languageRuby as a glue language
Ruby as a glue language
 
Ansible を完全にマスターする
Ansible を完全にマスターするAnsible を完全にマスターする
Ansible を完全にマスターする
 
Slim RedBeanPHP and Knockout
Slim RedBeanPHP and KnockoutSlim RedBeanPHP and Knockout
Slim RedBeanPHP and Knockout
 
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other ToolsCool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
 
Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)Best Practices in Plugin Development (WordCamp Seattle)
Best Practices in Plugin Development (WordCamp Seattle)
 
Magical WordPress Development with Vagrant
Magical WordPress Development with VagrantMagical WordPress Development with Vagrant
Magical WordPress Development with Vagrant
 
Keeping it small - Getting to know the Slim PHP micro framework
Keeping it small - Getting to know the Slim PHP micro frameworkKeeping it small - Getting to know the Slim PHP micro framework
Keeping it small - Getting to know the Slim PHP micro framework
 
Palestra VCR
Palestra VCRPalestra VCR
Palestra VCR
 
The Peanut Butter Cup of Web-dev: Plack and single page web apps
The Peanut Butter Cup of Web-dev: Plack and single page web appsThe Peanut Butter Cup of Web-dev: Plack and single page web apps
The Peanut Butter Cup of Web-dev: Plack and single page web apps
 
Great Developers Steal
Great Developers StealGreat Developers Steal
Great Developers Steal
 
Cucumber Ru09 Web
Cucumber Ru09 WebCucumber Ru09 Web
Cucumber Ru09 Web
 
Building Cloud Castles - LRUG
Building Cloud Castles - LRUGBuilding Cloud Castles - LRUG
Building Cloud Castles - LRUG
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Rack
 
Dancer's Ecosystem
Dancer's EcosystemDancer's Ecosystem
Dancer's Ecosystem
 
Sinatra Rack And Middleware
Sinatra Rack And MiddlewareSinatra Rack And Middleware
Sinatra Rack And Middleware
 
Quality Use Of Plugin
Quality Use Of PluginQuality Use Of Plugin
Quality Use Of Plugin
 

Similar to CoffeeScript, An Introduction for Nodejs developers

Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasminePaulo Ragonha
 
CoffeeScript-Ruby-Tuesday
CoffeeScript-Ruby-TuesdayCoffeeScript-Ruby-Tuesday
CoffeeScript-Ruby-TuesdayEddie Kao
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
Troy Miles
 
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHP
Mariano Iglesias
 
Scripting Embulk Plugins
Scripting Embulk PluginsScripting Embulk Plugins
Scripting Embulk Plugins
Sadayuki Furuhashi
 
Socket applications
Socket applicationsSocket applications
Socket applicationsJoão Moura
 
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryRemedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryTatsuhiko Miyagawa
 
Playing With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsPlaying With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.js
Mike Hagedorn
 
Boxen: How to Manage an Army of Laptops and Live to Talk About It
Boxen: How to Manage an Army of Laptops and Live to Talk About ItBoxen: How to Manage an Army of Laptops and Live to Talk About It
Boxen: How to Manage an Army of Laptops and Live to Talk About It
Puppet
 
Coffee scriptisforclosers nonotes
Coffee scriptisforclosers nonotesCoffee scriptisforclosers nonotes
Coffee scriptisforclosers nonotes
Brandon Satrom
 
Symfony Live 2018 - Développez votre frontend avec ReactJS et Symfony Webpack...
Symfony Live 2018 - Développez votre frontend avec ReactJS et Symfony Webpack...Symfony Live 2018 - Développez votre frontend avec ReactJS et Symfony Webpack...
Symfony Live 2018 - Développez votre frontend avec ReactJS et Symfony Webpack...
Alain Hippolyte
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
David Furber
 
A piece of sugar in your client-side development
A piece of sugar in your client-side developmentA piece of sugar in your client-side development
A piece of sugar in your client-side development
Nicolas Blanco
 
A Self Replicating Serverless Function
A Self Replicating Serverless FunctionA Self Replicating Serverless Function
A Self Replicating Serverless Function
Michael Adda
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
Forziatech
 
Cloud Automation with Opscode Chef
Cloud Automation with Opscode ChefCloud Automation with Opscode Chef
Cloud Automation with Opscode Chef
Sri Ram
 
Vidoop CouchDB Talk
Vidoop CouchDB TalkVidoop CouchDB Talk
Vidoop CouchDB Talk
Chris Anderson
 
Guide to Node.js: Basic to Advanced
Guide to Node.js: Basic to AdvancedGuide to Node.js: Basic to Advanced
Guide to Node.js: Basic to Advanced
Espeo Software
 

Similar to CoffeeScript, An Introduction for Nodejs developers (20)

Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
CoffeeScript-Ruby-Tuesday
CoffeeScript-Ruby-TuesdayCoffeeScript-Ruby-Tuesday
CoffeeScript-Ruby-Tuesday
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
 
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHP
 
Scripting Embulk Plugins
Scripting Embulk PluginsScripting Embulk Plugins
Scripting Embulk Plugins
 
Socket applications
Socket applicationsSocket applications
Socket applications
 
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryRemedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
 
Playing With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsPlaying With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.js
 
Play framework
Play frameworkPlay framework
Play framework
 
Boxen: How to Manage an Army of Laptops and Live to Talk About It
Boxen: How to Manage an Army of Laptops and Live to Talk About ItBoxen: How to Manage an Army of Laptops and Live to Talk About It
Boxen: How to Manage an Army of Laptops and Live to Talk About It
 
Coffee scriptisforclosers nonotes
Coffee scriptisforclosers nonotesCoffee scriptisforclosers nonotes
Coffee scriptisforclosers nonotes
 
Symfony Live 2018 - Développez votre frontend avec ReactJS et Symfony Webpack...
Symfony Live 2018 - Développez votre frontend avec ReactJS et Symfony Webpack...Symfony Live 2018 - Développez votre frontend avec ReactJS et Symfony Webpack...
Symfony Live 2018 - Développez votre frontend avec ReactJS et Symfony Webpack...
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 
A piece of sugar in your client-side development
A piece of sugar in your client-side developmentA piece of sugar in your client-side development
A piece of sugar in your client-side development
 
Node.js
Node.jsNode.js
Node.js
 
A Self Replicating Serverless Function
A Self Replicating Serverless FunctionA Self Replicating Serverless Function
A Self Replicating Serverless Function
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
 
Cloud Automation with Opscode Chef
Cloud Automation with Opscode ChefCloud Automation with Opscode Chef
Cloud Automation with Opscode Chef
 
Vidoop CouchDB Talk
Vidoop CouchDB TalkVidoop CouchDB Talk
Vidoop CouchDB Talk
 
Guide to Node.js: Basic to Advanced
Guide to Node.js: Basic to AdvancedGuide to Node.js: Basic to Advanced
Guide to Node.js: Basic to Advanced
 

Recently uploaded

Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
Boni García
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 

Recently uploaded (20)

Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 

CoffeeScript, An Introduction for Nodejs developers

  • 1. COFFEESCRIPT AN INTRODUCTION FOR NODE DEVELOPERS BY: MEHDI VALIKHANI SOFTWARE ENGINEER @ ALPHATISE Follow me: @mehdivk | mehdi@alphatise.com
  • 2. IT'S JUST JAVASCRIPT COFFEESCRIPT IS A PROGRAMMING LANGUAGE THAT TRANSCOMPILES TO JAVASCRIPT. SYNTACTIC SUGAR TO JAVASCRIPT
  • 3. IT'S MATURE AND PRODUCTION-READY DEVELOPED BY: JEREMY ASHKENAS INITIAL COMMIT: DECEMBER 13TH, 2009 FIRST RELEASE: DECEMBER 24H, 2009 VERSION 1.0: FEBRUARY 2010 CURRENT VERSION: 1.8
  • 4. WHO'S USING COFFEESCRIPT? DROPBOX GITHUB
  • 5. WRITE LESS, DO MORE HUMAN-READABLE CODE STAY AWAY FROM WEIRD JS BEHAVIOUR SAY GOODBYE TO PROTOTYPE! USE CLASSES ANY MANY MORE ...
  • 7. NO MORE VAR ; ( ) async = require 'async' console.log async.VERSION var async = require('async'); console.log(async.VERSION);
  • 8. FUNCTIONS IT'S PART OF OUR EVERYDAY LIFE IN JS WORLD LET'S BE AGILE!
  • 9. addUser = (user, cb) -> model = new User #DO SOMETHING model.save (err, result) -> cb null, result var addUser = function(user, cb) { var model = new User(); //DO SOMETHING model.save(function(err, result){ cb(err, result); }); }
  • 10. IMPLICIT RETURN someFunction = (param1, param2) -> param1 * param2 * param2 console.log someFunction 100, 200 var someFunction; someFunction = function(param1, param2) { return param1 * param2 * param2; } console.log(someFunction(100, 200));
  • 11. OBJECTS GET RID OF THOSE { } , bus = routeNumber: 273 from: 'Wynyard' to: 'Chatswood' via: 'North Sydney, Pacific Highway' var bus = { routerNumber: 273, from: 'Wynyad', to: 'Chatswood', via: 'North Sydney, Pacific Highway' }
  • 12. query = status: $in: ['active', 'pending_for_approval'] payment: $nin: ['invoice', 'free'] tc: $exists: true var query = { status: { $in: ['active', 'pending_for_approval'] }, payment: { $nin: ['invoice', 'free'] }, tc: { $exists: true } }
  • 13. STRING INTERPOLOATION meetup = 'Node' msg = "#{meetup} meeup is awsome!" console.log msg var meetup = 'Node'; var msg = meetup + ' meetup is awsome!'; console.log(msg);
  • 14. CLASSES BETTER INHERITANCE WITHOUT PROTOTYPE WE SHOULDN'T USE LIBRARIES TO HAVE CLASSES IN JS
  • 15. class Cache generateCacheKey: (key) -> throw new Error 'Not Implemented' getPeriod: -> 120 * 60 store: (key, data) -> throw new Error 'Not Implemented' clearCache: (key) -> #DO SOMETHING class RedisCache extends Cache generateCacheKey: (key) -> "redis_cache_#{key}" store: (key, data) -> period = @.getPeriod() #STORE IN REDIS
  • 16. DESTRUCTURING OBJECTS {Router} = require 'express' router = new Router var express = require('express'); var Router = experss.Router; router = new Router();
  • 17. DESTRUCTURING ARRAYS student = 'Mehdi Valikhani' [firstName, lastName] = student.split ' ' var student, ref, firstName, lastName; student = 'Mehdi Valikhani'; ref = student.split(' '); firstName = ref[0]; lastName = ref[1];
  • 18. DESTRUCTING ARGUMENTS calculator = ({width, height}) -> width * height options = width: 10 height: 5 alert calculator options
  • 19. EXISTENTIAL OPERATOR ? REMOVE THOSE NULL OR UNDEFINED CHECKES FROM CODE if err? #log to logger cb err if (typeof err !== "undefined" && err !== null) //log to logger cb(err);
  • 20. INSTALL COFFEESCRIPT npm install -g coffee-script
  • 21. EXECUTE A SCRIPT coffee /path/to/script.coffee
  • 22. COMPILE A SCRIPT coffee -c /path/to/script.coffee
  • 23. NODE + COFFEE FROM SCRATCH REST API DEVELOPMENT USING EXPRESS + NODE + COFFEE
  • 24. CODE STRUCTURE + lib + books Book.coffee //Our Mongoose Model router.coffee //router for books API + node_modules + body-parser //from JSON responses + coffee-script //compiler of Coffee files + express //express framework app.coffee //express app config package.json // NO DESCRIPTION index.js //ACTUAL MAGIC HAPPENS HERE!
  • 25. app.coffee bodyParser = require 'body-parser' express = require 'express' userRouter = require './lib/books/router' app = express() app.use bodyParser.json() app.use '/users', userRouter module.exports = app
  • 26. lib/books/router.coffee {Router} = require 'express' Book = require './Book' router = new Router fetchBook = (req, res, next) -> req.paramBook = Book next() getBook = (req, res) -> res.json(req.paramBook) router.route('/:book_id') .all(fetchBook) .get(getBook) module.exports = router
  • 27. index.js require('coffee-script/register'); var app = require('./app'); app.listen(1984, function(){ console.log('App is available via http://127.0.0.1:1984'); });
  • 28. RUN THE APP node index.js nodemon -e js,coffee index.js
  • 29. NODE + COFFEE AN EXISTING PROJECT
  • 30. ADD FOLLOWING CODE TO YOUR STARTER FILE require('coffee-script/regiter');
  • 31. THAT'S IT! Add .coffee files, write your code in coffee require other .js or .coffee files as always
  • 32. RUN THE APP node index.js nodemon -e js,coffee index.js
  • 34. USE "DEBUGGER" AS ALWAYS fetchBook = (req, res, next) -> debugger req.paramBook = Book next() node debug index.js
  • 35. BUT DON'T FORGET! in debug mode, you will be faced with compiled JS code break in lib/books/router.coffee:11 9 10 fetchBook = function(req, res, next) { 11 debugger; 12 req.paramBook = Book; 13 return next(); debug> repl Press Ctrl + C to leave debug repl > req.params.book_id '123' >
  • 36. JAVASCRIPT SCOPING in JavaScript, the scope of a variable is defined by its location within the source code (it is apparent lexically) and nested functions have access to variables declared in their outer scope. - mozilla.org
  • 37. Question: What's result of running this code? name = 'Alex' greeting = -> name = 'James' console.log "Hey #{name}!" greeting() console.log "Hey #{name}!"
  • 38. A: > Hey James! > Hey James! B: > Hey James! > Hey Alex!
  • 39. "A" IS CORRECT ANSWER > Hey James! > Hey James!
  • 40. THIS IS COMPILED-TO-JS VERSION OF ABOVE CODE var greeting, name; name = 'Alex'; greeting = function() { name = 'James'; return console.log("Hey " + name + "!"); }; greeting(); console.log("Hey " + name + "!");
  • 41. TWO IMPORTANT FACTS ABOUT COFEESCRIPT SCOPING Variable shadowing is not allowed variable is created at the moment of the first assignment to it
  • 42. "VARIABLE SHADOWING IS NOT ALLOWED" DOESN'T MEAN YOU CAN'T DEFINE A VARIABLE MORE THAN ONCE IN DIFFERENT FILES IT MEANS YOU CAN'T DEFINE IT MORE THAN ONCE IN A SINGLE FILE
  • 43. SO WHAT SHOULD I DO IF I WANT TO HAVE SHADOWS? It's not a good practice, don't do that! It decreases readbility of your code! Brings more confusion to your code With shadowing you can't access our variables anymore (with same name)
  • 44. USE `` TO BRING VAR BACK name = 'Alex' greeting = -> ` var name ` name = 'James' console.log "Hey #{name}!" greeting() console.log "Hey #{name}!" It a kind of hack! Don't do that!
  • 45. SHADOW IT USING FUNCTION PARAMETER name = 'Alex' greeting = (name = '')-> name = 'James' console.log "Hey #{name}!" greeting() console.log "Hey #{name}!" Better first solution!
  • 46. USE COFEESCRIPT'S CLOSURE FEATURE This is much much better! name = 'Alex' greeting = -> do (name = '') -> name = 'James' console.log "Hey #{name}!" greeting() console.log "Hey #{name}!"
  • 47. MORE INFO ABOUT LEXICAL SCOPING: https://github.com/raganwald-deprecated/ homoiconic/blob/master/2012/09/actually-YOU-dont- understand-lexical-scope.md https://github.com/raganwald-deprecated/ homoiconic/blob/master/2012/09/lexical-scope-in- coffeescript.md
  • 48. USEFUL RESOURCES CoffeeScript Docs Your best friend CoffeeConsole: A Google Chrome Extention Don't translate CoffeeScript to JS, try to learn as new langage CoffeeScript Ristretto Teaches CoffeeScript as new language instrad of translating to JS The Little Book On CoffeeScript CoffeeScript Style Guide Best Practices