SlideShare a Scribd company logo
1 of 29
Download to read offline
JAVASCRIPT: THE
         IMPORTANT BITS
REVIEWING JAVASCRIPT AND JQUERY FUNDAMENTALS AS WELL AS A
                   BRIEF INTRO TO NODEJS
THINK YOU KNOW JAVASCRIPT?
     typeof [] === "array"; false
     0.1 + 0.2 === 0.3; false
     a === null; false
     0 == '0'; true
     1 == '1'; true
     '' == '0'; false
     '' == 0; true
     'false' == false; false

          True or false?
THINK YOU KNOW JAVASCRIPT?
return
{
  a: "hello"
}



                What does this return?
THINK YOU KNOW JAVASCRIPT?
LET'S GET STARTED WITH THE BASICS.
VARIABLES
When declairing a variable without the "var", it puts the variable in
             global space which can be problematic.


   function hello() {
     test1 = 'hello';        // global scope
     var test2 = 'hello2';   // this function scope
   }

   hello();

   console.log(test1); // 'hello';
   console.log(test2); // undefined
SCOPING
       There is no block scoping, only function scoping:
for (var i = 0; i < 10; i++) {
  console.log(i);
}
console.log(i); // prints 10



       If you want to block the scope of the above loop:
(function () {
  for (var i = 0; i < 10; i++) {
    console.log(i);
  }
}());
var i;
console.log(i); // undefined
SCOPE IN CALLBACKS
In callbacks, you can share variables from the parent function:
 var obj = {
   objValue: 'hello',
   test: function() {
     var self = this;
       setTimeout(function() {
         console.log(this.objValue); // undefined
         console.log(self.objValue); // 'hello'
       }, 10);
   }
 }
OBJECTS AND "CLASSES"
Objects are like JSON with some class aspects known as
                      prototypes.
OBJECTS AND "CLASSES"
                            An example class:


Animal = (function() {

  function Animal(name) {
    this.name = name;
  }

  Animal.prototype.move = function() {
     return alert(this.name + ' moved.');
  };

  return Animal;

}());
COMMON JAVASCRIPT PATTERNS
IMMEDIATE EXECUTION FUNCTION
(function() {
  // Your logic here
}());



This immediately executes your logic as anonymous scope.
PRIVATE PATTERN
 var getCount = function() {
   var count = 0;
   return function() {
       return ++count;
   }
 }
 var next = getCount();
 console.log(next()); // 1
 console.log(next()); // 2



This pattern allows you to expose only what you want exposed.
INITIALIZATION
                        Variable initialization:
var value = value || 'somevalue';



                   Complex object initialization:
({
  val1: 1,
  val2: null,
  init: function() {
    this.val2 = 2;
    return this;
  }
}).init();
LET'S GO OVER JQUERY OPTIMIZATION.
SELECTOR CACHING
                                    Bad:
$('.someclass').text('replace some text.');
$('.someclass').css('color', 'red');
$('.someclass').focus();



                                   Good:
$('.someclass')
  .text('replace some text.')
  .css('color', 'red')
  .focus();
SELECTOR CACHING
                       Caching with callbacks.
var $someotherclass = $('.someotherclass');
$('.someclass').on('click', function(e) {
  $someotherclass.text('some event');
});



                             Caching "this":
$('.someclass').on('click', function(e)) {
  $this = $(this);
  $this.text('something');
  $this.hide();
});
EVENT ATTACHING
        When attaching events, use the "on" function.
$('a').on('click', function(e)) {
  console.log('A link was clicked.');
});



           What about dynamically generated links?
$(document).on('click', 'a', function(e)) {
  console.log('A link was clicked.');
});
PROPERLY STOPPING EVENTS
           Returning false is not always a good thing:
$('a').on('click', function(e) {
  console.log('Stopping propagation.');
  return false;
  // Same as:
  // e.preventDefault();
  // e.stopPropagation();
});
$('a').on('click', function(e)) {
  console.log('Another click.');
  // Never gets called because of the
  // return false in the above event.
});
BASIC JQUERY PLUGIN STRUCTURE
(function($) {
  $.fn.myLog = function() {
        return this.each(function() {
                console.log($(this));
        });
  }
}(jQuery));



                                  Usage:
$('p').myLog();
INTRODUCTION TO NODEJS
Nodejs is an event-driven language built on Google's V8 (in c).

It's package manager is known as npm and is now packaged with
                            nodejs.
NODEJS: HELLO WORLD
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello Worldn');
}).listen(1337);
console.log('Server running on port 1337');


                        Source:   http://nodejs.org/about/
NODEJS: DEPENDANCY MANAGEMENT
You can manage dependencies for your nodejs app in package.json:
   {
       "name": "sample-app",
       "version": "0.0.1",
       "dependencies": {
         "express": "2.5.x"
       }
   }




   This allows us to install our project dependencies with npm:
   npm install
NODEJS: EXPRESS SERVER
               Our hello world example in express:
var express = require('express');
app = express.createServer()
app.get('/', function(req, res) {
  res.send('Hello World');
});
app.listen(1337);
console.log('Listening on port 1337');
NODEJS: CONNECT MIDDLEWARE
Routing middleware is anything that implements the request,
           response, and next function pattern.
// Request logger
function logger(req, res, next) {
  console.log("Path requested: " + req.path);
  next();
}




                        Using this middleware:
app.get('/', logger, function(req, res) {
  res.send('Hello World');
});
QUESTIONS?
Javascript: the important bits

More Related Content

What's hot

Java Script Promise
Java Script PromiseJava Script Promise
Java Script Promise
Alok Guha
 

What's hot (20)

JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with Jasmine
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
 
06 jQuery #burningkeyboards
06 jQuery  #burningkeyboards06 jQuery  #burningkeyboards
06 jQuery #burningkeyboards
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards
 
JavaScript Basics and Trends
JavaScript Basics and TrendsJavaScript Basics and Trends
JavaScript Basics and Trends
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 
Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8Xlab #1: Advantages of functional programming in Java 8
Xlab #1: Advantages of functional programming in Java 8
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascript
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Deferred
DeferredDeferred
Deferred
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the AST
 
Java Script Promise
Java Script PromiseJava Script Promise
Java Script Promise
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
Map kit light
Map kit lightMap kit light
Map kit light
 

Viewers also liked (18)

Observe, Question, Design.
Observe, Question, Design.Observe, Question, Design.
Observe, Question, Design.
 
Ghost recon
Ghost reconGhost recon
Ghost recon
 
Inbound 2012 Square 2 Marketing Presentation v2
Inbound 2012 Square 2 Marketing Presentation v2Inbound 2012 Square 2 Marketing Presentation v2
Inbound 2012 Square 2 Marketing Presentation v2
 
mengenal tajwid
mengenal tajwidmengenal tajwid
mengenal tajwid
 
Major1 week2 presentation
Major1 week2 presentationMajor1 week2 presentation
Major1 week2 presentation
 
Study Case: Black Swan
Study Case: Black SwanStudy Case: Black Swan
Study Case: Black Swan
 
Press Complaints Commission
Press Complaints CommissionPress Complaints Commission
Press Complaints Commission
 
Classification
ClassificationClassification
Classification
 
War in the middle east powerpoint
War in the middle east powerpointWar in the middle east powerpoint
War in the middle east powerpoint
 
Observe. Question. Design
Observe. Question. Design Observe. Question. Design
Observe. Question. Design
 
Mengenal jaringan internet 2
Mengenal jaringan internet 2Mengenal jaringan internet 2
Mengenal jaringan internet 2
 
Simple Storyboard
Simple StoryboardSimple Storyboard
Simple Storyboard
 
Squishy[1]
Squishy[1]Squishy[1]
Squishy[1]
 
Webiste plan1
Webiste plan1Webiste plan1
Webiste plan1
 
Advertisment..
Advertisment..Advertisment..
Advertisment..
 
Audit:2
Audit:2Audit:2
Audit:2
 
Mengenal khat
Mengenal  khat Mengenal  khat
Mengenal khat
 
Auditing unit 1
Auditing unit 1Auditing unit 1
Auditing unit 1
 

Similar to Javascript: the important bits

Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
wpnepal
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
Ben Lin
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
Adam Crabtree
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan Stefanov
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
Piyush Katariya
 

Similar to Javascript: the important bits (20)

Java script for web developer
Java script for web developerJava script for web developer
Java script for web developer
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Javascript - Beyond-jQuery
Javascript - Beyond-jQueryJavascript - Beyond-jQuery
Javascript - Beyond-jQuery
 
Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.js
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5
 
AngularJS Testing Strategies
AngularJS Testing StrategiesAngularJS Testing Strategies
AngularJS Testing Strategies
 
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 

Recently uploaded

Recently uploaded (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 

Javascript: the important bits

  • 1. JAVASCRIPT: THE IMPORTANT BITS REVIEWING JAVASCRIPT AND JQUERY FUNDAMENTALS AS WELL AS A BRIEF INTRO TO NODEJS
  • 2. THINK YOU KNOW JAVASCRIPT? typeof [] === "array"; false 0.1 + 0.2 === 0.3; false a === null; false 0 == '0'; true 1 == '1'; true '' == '0'; false '' == 0; true 'false' == false; false True or false?
  • 3. THINK YOU KNOW JAVASCRIPT? return { a: "hello" } What does this return?
  • 4. THINK YOU KNOW JAVASCRIPT?
  • 5.
  • 6. LET'S GET STARTED WITH THE BASICS.
  • 7. VARIABLES When declairing a variable without the "var", it puts the variable in global space which can be problematic. function hello() { test1 = 'hello'; // global scope var test2 = 'hello2'; // this function scope } hello(); console.log(test1); // 'hello'; console.log(test2); // undefined
  • 8. SCOPING There is no block scoping, only function scoping: for (var i = 0; i < 10; i++) { console.log(i); } console.log(i); // prints 10 If you want to block the scope of the above loop: (function () { for (var i = 0; i < 10; i++) { console.log(i); } }()); var i; console.log(i); // undefined
  • 9. SCOPE IN CALLBACKS In callbacks, you can share variables from the parent function: var obj = { objValue: 'hello', test: function() { var self = this; setTimeout(function() { console.log(this.objValue); // undefined console.log(self.objValue); // 'hello' }, 10); } }
  • 10. OBJECTS AND "CLASSES" Objects are like JSON with some class aspects known as prototypes.
  • 11. OBJECTS AND "CLASSES" An example class: Animal = (function() { function Animal(name) { this.name = name; } Animal.prototype.move = function() { return alert(this.name + ' moved.'); }; return Animal; }());
  • 13. IMMEDIATE EXECUTION FUNCTION (function() { // Your logic here }()); This immediately executes your logic as anonymous scope.
  • 14. PRIVATE PATTERN var getCount = function() { var count = 0; return function() { return ++count; } } var next = getCount(); console.log(next()); // 1 console.log(next()); // 2 This pattern allows you to expose only what you want exposed.
  • 15. INITIALIZATION Variable initialization: var value = value || 'somevalue'; Complex object initialization: ({ val1: 1, val2: null, init: function() { this.val2 = 2; return this; } }).init();
  • 16. LET'S GO OVER JQUERY OPTIMIZATION.
  • 17. SELECTOR CACHING Bad: $('.someclass').text('replace some text.'); $('.someclass').css('color', 'red'); $('.someclass').focus(); Good: $('.someclass') .text('replace some text.') .css('color', 'red') .focus();
  • 18. SELECTOR CACHING Caching with callbacks. var $someotherclass = $('.someotherclass'); $('.someclass').on('click', function(e) { $someotherclass.text('some event'); }); Caching "this": $('.someclass').on('click', function(e)) { $this = $(this); $this.text('something'); $this.hide(); });
  • 19. EVENT ATTACHING When attaching events, use the "on" function. $('a').on('click', function(e)) { console.log('A link was clicked.'); }); What about dynamically generated links? $(document).on('click', 'a', function(e)) { console.log('A link was clicked.'); });
  • 20. PROPERLY STOPPING EVENTS Returning false is not always a good thing: $('a').on('click', function(e) { console.log('Stopping propagation.'); return false; // Same as: // e.preventDefault(); // e.stopPropagation(); }); $('a').on('click', function(e)) { console.log('Another click.'); // Never gets called because of the // return false in the above event. });
  • 21. BASIC JQUERY PLUGIN STRUCTURE (function($) { $.fn.myLog = function() { return this.each(function() { console.log($(this)); }); } }(jQuery)); Usage: $('p').myLog();
  • 23. Nodejs is an event-driven language built on Google's V8 (in c). It's package manager is known as npm and is now packaged with nodejs.
  • 24. NODEJS: HELLO WORLD var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Worldn'); }).listen(1337); console.log('Server running on port 1337'); Source: http://nodejs.org/about/
  • 25. NODEJS: DEPENDANCY MANAGEMENT You can manage dependencies for your nodejs app in package.json: { "name": "sample-app", "version": "0.0.1", "dependencies": { "express": "2.5.x" } } This allows us to install our project dependencies with npm: npm install
  • 26. NODEJS: EXPRESS SERVER Our hello world example in express: var express = require('express'); app = express.createServer() app.get('/', function(req, res) { res.send('Hello World'); }); app.listen(1337); console.log('Listening on port 1337');
  • 27. NODEJS: CONNECT MIDDLEWARE Routing middleware is anything that implements the request, response, and next function pattern. // Request logger function logger(req, res, next) { console.log("Path requested: " + req.path); next(); } Using this middleware: app.get('/', logger, function(req, res) { res.send('Hello World'); });