SlideShare a Scribd company logo
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?
Javascript: the important bits
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

ODP
ES6 PPT FOR 2016
PDF
Workshop 5: JavaScript testing
PDF
Workshop 10: ECMAScript 6
PDF
Inversion Of Control
PPTX
Workshop 1: Good practices in JavaScript
PDF
FalsyValues. Dmitry Soshnikov - ECMAScript 6
PDF
Understanding Asynchronous JavaScript
PDF
Testing your javascript code with jasmine
ES6 PPT FOR 2016
Workshop 5: JavaScript testing
Workshop 10: ECMAScript 6
Inversion Of Control
Workshop 1: Good practices in JavaScript
FalsyValues. Dmitry Soshnikov - ECMAScript 6
Understanding Asynchronous JavaScript
Testing your javascript code with jasmine

What's hot (20)

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

Viewers also liked (18)

PDF
Observe, Question, Design.
PPTX
Ghost recon
PPTX
Inbound 2012 Square 2 Marketing Presentation v2
PPT
mengenal tajwid
PDF
Major1 week2 presentation
PPTX
Study Case: Black Swan
DOCX
Press Complaints Commission
DOCX
Classification
PPTX
War in the middle east powerpoint
PDF
Observe. Question. Design
PPTX
Mengenal jaringan internet 2
PPTX
Simple Storyboard
PPT
Squishy[1]
PPTX
Webiste plan1
PPTX
Advertisment..
PPT
PPT
Mengenal khat
PPT
Auditing unit 1
Observe, Question, Design.
Ghost recon
Inbound 2012 Square 2 Marketing Presentation v2
mengenal tajwid
Major1 week2 presentation
Study Case: Black Swan
Press Complaints Commission
Classification
War in the middle east powerpoint
Observe. Question. Design
Mengenal jaringan internet 2
Simple Storyboard
Squishy[1]
Webiste plan1
Advertisment..
Mengenal khat
Auditing unit 1
Ad

Similar to Javascript: the important bits (20)

PDF
Javascript: The Important Bits
PPTX
All of Javascript
PPT
jQuery with javascript training by Technnovation Labs
PPTX
Awesomeness of JavaScript…almost
PPT
JavaScript Misunderstood
PDF
KEY
JavaScript Neednt Hurt - JavaBin talk
PPT
JavaScript Workshop
PPTX
All of javascript
PDF
HTML5 for the Silverlight Guy
KEY
KEY
User Interface Development with jQuery
PPT
Reversing JavaScript
PDF
A Deep Dive into Javascript
PPT
PPT
JavaScript - An Introduction
PDF
JavaScript: Patterns, Part 1
PPT
JavaScript Tutorial
PDF
Scalable JavaScript
Javascript: The Important Bits
All of Javascript
jQuery with javascript training by Technnovation Labs
Awesomeness of JavaScript…almost
JavaScript Misunderstood
JavaScript Neednt Hurt - JavaBin talk
JavaScript Workshop
All of javascript
HTML5 for the Silverlight Guy
User Interface Development with jQuery
Reversing JavaScript
A Deep Dive into Javascript
JavaScript - An Introduction
JavaScript: Patterns, Part 1
JavaScript Tutorial
Scalable JavaScript

Recently uploaded (20)

PDF
KodekX | Application Modernization Development
PPTX
Web Security: Login Bypass, SQLi, CSRF & XSS.pptx
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Modernizing your data center with Dell and AMD
PDF
Dell Pro 14 Plus: Be better prepared for what’s coming
PDF
REPORT: Heating appliances market in Poland 2024
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
PPTX
CroxyProxy Instagram Access id login.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
PDF
Transforming Manufacturing operations through Intelligent Integrations
PDF
DevOps & Developer Experience Summer BBQ
PPTX
Belt and Road Supply Chain Finance Blockchain Solution
PDF
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
KodekX | Application Modernization Development
Web Security: Login Bypass, SQLi, CSRF & XSS.pptx
Understanding_Digital_Forensics_Presentation.pptx
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
Automating ArcGIS Content Discovery with FME: A Real World Use Case
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Modernizing your data center with Dell and AMD
Dell Pro 14 Plus: Be better prepared for what’s coming
REPORT: Heating appliances market in Poland 2024
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
CroxyProxy Instagram Access id login.pptx
Chapter 3 Spatial Domain Image Processing.pdf
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
A Day in the Life of Location Data - Turning Where into How.pdf
Transforming Manufacturing operations through Intelligent Integrations
DevOps & Developer Experience Summer BBQ
Belt and Road Supply Chain Finance Blockchain Solution
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?

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?
  • 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'); });