SlideShare a Scribd company logo
JavaScript Basics
Adam Crabtree
(Adapted from Joar Gullestad Pettersen’s
http://slideshare.net/Peanuts_Stavanger/javascript-basics-29353026)
JavaScript Data Types
String, Number, Boolean, Array, Object, Null, Undefined
Dynamic Types
• var x;
Dynamic Types
var x;

// x is: undefined
Dynamic Types
var x;

// x is: undefined

x = 5;

// x is set to a Number: 5
Dynamic Types
var x;

// x is: undefined

x = 5;

// x is set to a Number: 5

x = "Bond";

// x is changed to a String: "Bond"
Strings
var car = "Telsa Model S";
var car2 = 'Tesla Model S';
Numbers
• var x = 42;
• var y = 13.37;
• var z = 10e3;

// Written without decimals
// Written with decimals
// Exponential notation
Booleans
• var x = true;
• var y = false;
Array
var frukt = new Array();
frukt[0] = "eple";
frukt[1] = "banan";
frukt[2] = "pære";
["eple", "banan", "pære"]
Array 2
var frukt = new Array("eple", "banan", "pære");
["eple", "banan", "pære"]
Array 3
var frukt = ["eple", "banan", "pære"];
["eple", "banan", "pære"]
Array 4
• var frukt = ["eple", "banan", "pære"]
•
•
•
•

frukt.pop();

// ["eple", "banan"]

frukt.push("tomat");

// ["eple", "banan", "tomat"]

frukt.shift();

// ["banan", "tomat"]

frukt.unshift("tomat"); // ["tomat", "banan", "tomat"]
Objects
• Everything is an Object
Objects
•
•
•
•
•

Everything is an Object
Booleans can be objects or primitive data treated as objects
Numbers can be objects or primitive data treated as objects
Strings are also objects or primitive data treated as objects
Dates, Maths, Regular expressions, Arrays and functions are always objects
Object literal
An object is just a special kind of
data, with properties and methods.
var person = {
firstName: "John",
lastName: "Doe",
id: 5
};
Object literal
An object is just a special kind of data,
with properties and methods.
var person = {
firstName: "John",
lastName: "Doe",
id: 5
};
person.id; // 5
Object literal
An object is just a special kind of data,
with properties and methods.
var person = {
firstName: "John",
lastName: "Doe",
address: {

street: "Strandsvingen",
number: "14B"
}
};

person.address.street; // "Strandsvingen"
Functions
a block of code that will be executed when "someone" calls it:
function add(a, b) {
return a + b;
}
var add = function(a, b) {
return a + b;
}
Object Constructor
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
var randomPerson = new Person("John", "Doe");
Object
var randomPerson = new Object();
randomPerson.firstName = "John";
randomPerson.lastName = "Doe";
Boolean expressions
if (a == 2) {//if this is true
//do this...
}
Type coercion
• When JavaScript are unsure what you mean, It makes a guess
• Example:
if ('false') { console.log("true"); }

• «A String is obviously not true or false, you probably
mean true!»
True! 
• if (true) { alert("true"); } // alerts "true"
• if ('false') { alert("true"); } // alerts "true"

• if ([]) { alert("true"); } // alerts "true"
• if (5) { alert("true"); } // alerts "true"

• if ({}) { alert("true"); } // alerts "true"
False 
• if (false) { alert("false"); } // does nothing
• if (0) { alert("false"); } // does nothing

• if (null) { alert("false"); } // does nothing
• if (undefined) { alert("false"); } // does nothing

• if ("") { alert("false"); } // does nothing
More type coercion 
1 == "1"
true == "1"
false == "0"
More type coercion 
1 == "1"
true
true == "1"
false == "0"
More type coercion 
1 == "1"
true
true == "1"

true
false == "0"
More type coercion 
1 == "1"
true
true == "1"

true
false == "0"
true
More type coercion
1 == "1"
true
true == "1"

true
false == "0"
true
false == "0" == 1 == true == [] == ""
More type coercion 
1 == "1"
true
true == "1"

true
false == "0"
true
false == "0" == 1 == true == [] == ""
true
Confusing?
• Solution?
Confusing?
• Solution?

• Avoid bugs| and use: ===
===
1 == true
true
1 === true
false
1 == "1"
true
1 === "1"
false
Scope & global variables
• C#/Java: anything inside curly brackets, {} , defines a scope
• Example:
if (true)

{

var scopeVariable = "Test";
}
scopeVariable = "Test2"; // variable not defined
Scope & global variables
• Javascript: only functions define a new scope
• Example:
if (true) {
var scopeVariable = "Test";
}
scopeVariable; // value: "Test";
Scope & global variables
function scope1() {
var member; //is a member of the scope defined by the function example
//this function is also part of the scope of the function example

var innerScope = function() {
member= 12; // traverses scope and assigns member in scope1 to 12
};
};
Scope & global variables
function scope1() {
var member; //is a member of the scope defined by the function example
//this function is also part of the scope of the function example

var innerScope = function() {
var member= 12; // defines member in this scope and do not traverse
};
};
Scope & global variables
function scope1() {
var member;

//is a member of the scope defined by the function example

//this function is also part of the scope of the function example
var bar = function() {
member= 12; // traverses scope and assigns scope1member.foo to 12
};
};
function scope2() {
member = 15; // traverses scope and assigns global.member to 15
}
Namespaces
• Not built into JavaScript
• Problem?
JavaScript (Ad-hoc) namespace
var Peanuts = {};

// Object used as namespace
JavaScript (Ad-hoc) namespace
var Peanuts = Peanuts || {}; // in case it already
exists
«Classes» and «methods» ?
var Peanuts = Peanuts || {};
Peanuts.Calculator = {
add: function (a,b) {
return a + b;

},
subtract: function () {
return a - b;
}
};

Peanuts.Calculator.add(1, 2); // 3
Immediately invoked function expressions
• (function () {
•
// logic/code here
• })();
Why?
• Executes an expression and therefore code immediately
• Creates «privacy» for your code (function scope ftw!)
How?
• JavaScript, parenthesis can’t contain statements.
• When the parser encounters the function keyword, it knows to
parse it as a function expression and not a function declaration.
Immediately invoked function expressions
•
•
•
•
•

(function () {
// logic/code here
})();
The key thing about JavaScript expressions is that they return values.
To invoke the function expression right away we just need to tackle a couple
of parentheses on the end(like above).
Immediately invoked function expressions
• (function (innerValue) {
•
// logic/code here
• })(outerValue);
Revealing module pattern
var Peanuts = Peanuts || {};
Peanuts.Calculator = function () {
var add = function(a, b) {
return a + b;
};
var subtract = function(a, b) {

return a - b;
};
return {
add: add,
subtract: subtract
};
};

Peanuts.Calculator().add(1, 2); // 3
Revealing module pattern 2
var Peanuts = Peanuts || {};
Peanuts.Calculator = (function () {
var add = function(a, b) {
return a + b;

};
return {
add: add,
};
})();

Peanuts.Calculator.add(1, 2); // 3
Revealing module pattern 3
var Peanuts = Peanuts || {};
Peanuts.Calculator = (function () {
var PI = 3.14; // private variable!
var getCircleArea = function(r) {
return PI * r * r;

};
return {
getCircleArea: getCircleArea // public method
};
})();
Peanuts.Calculator.getCircleArea(2); // 12.56

More Related Content

PPTX
Javascript basics
Solv AS
 
PDF
JavaScript - From Birth To Closure
Robert Nyman
 
PPTX
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
Doug Jones
 
PDF
JavaScript Basics and Best Practices - CC FE & UX
JWORKS powered by Ordina
 
PDF
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy
 
PDF
Ten useful JavaScript tips & best practices
Ankit Rastogi
 
PDF
Basics of JavaScript
Bala Narayanan
 
PDF
JavaScript Patterns
Stoyan Stefanov
 
Javascript basics
Solv AS
 
JavaScript - From Birth To Closure
Robert Nyman
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
Doug Jones
 
JavaScript Basics and Best Practices - CC FE & UX
JWORKS powered by Ordina
 
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy
 
Ten useful JavaScript tips & best practices
Ankit Rastogi
 
Basics of JavaScript
Bala Narayanan
 
JavaScript Patterns
Stoyan Stefanov
 

What's hot (20)

PPT
Ajax and JavaScript Bootcamp
AndreCharland
 
ODP
Javascript
theacadian
 
PPT
Javascript
Manav Prasad
 
PDF
javascript objects
Vijay Kalyan
 
PDF
Fundamental JavaScript [UTC, March 2014]
Aaron Gustafson
 
PDF
Performance Optimization and JavaScript Best Practices
Doris Chen
 
PDF
Secrets of JavaScript Libraries
jeresig
 
PPT
A Deeper look into Javascript Basics
Mindfire Solutions
 
KEY
JavaScript Growing Up
David Padbury
 
PDF
Patterns for JVM languages - Geecon 2014
Jaroslaw Palka
 
PDF
A Re-Introduction to JavaScript
Simon Willison
 
PDF
JavaScript Programming
Sehwan Noh
 
PDF
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
PPT
JavaScript Basics
Mats Bryntse
 
PDF
JavaScript - Chapter 6 - Basic Functions
WebStackAcademy
 
PDF
Object Oriented Programming in JavaScript
zand3rs
 
PDF
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
PPTX
Art of Javascript
Tarek Yehia
 
PPSX
Javascript variables and datatypes
Varun C M
 
PPT
Beginning Object-Oriented JavaScript
Stoyan Stefanov
 
Ajax and JavaScript Bootcamp
AndreCharland
 
Javascript
theacadian
 
Javascript
Manav Prasad
 
javascript objects
Vijay Kalyan
 
Fundamental JavaScript [UTC, March 2014]
Aaron Gustafson
 
Performance Optimization and JavaScript Best Practices
Doris Chen
 
Secrets of JavaScript Libraries
jeresig
 
A Deeper look into Javascript Basics
Mindfire Solutions
 
JavaScript Growing Up
David Padbury
 
Patterns for JVM languages - Geecon 2014
Jaroslaw Palka
 
A Re-Introduction to JavaScript
Simon Willison
 
JavaScript Programming
Sehwan Noh
 
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
JavaScript Basics
Mats Bryntse
 
JavaScript - Chapter 6 - Basic Functions
WebStackAcademy
 
Object Oriented Programming in JavaScript
zand3rs
 
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
Art of Javascript
Tarek Yehia
 
Javascript variables and datatypes
Varun C M
 
Beginning Object-Oriented JavaScript
Stoyan Stefanov
 
Ad

Viewers also liked (20)

PDF
14526610 english-banana-the-second-book-
incasong
 
PPT
Vchitel_projekt
Tanya Puzir
 
PDF
Participants List For Jsm
JADE aisbl
 
PDF
Goodrich Global 产品常见问题 (地板)
Goodrich Global
 
PDF
Tulospohjainen Markkinointi Netissä
Darwin Oy
 
PPSX
♥♥♥
jennybabe
 
PPT
Asiakkaan Kohtaaminen
Darwin Oy
 
PPTX
Hyvinvointituotteen markkinointi - miten onnistut aina!
Darwin Oy
 
PDF
Chowka bhara
Arvind Krishnaa
 
PPSX
Unit 0
Rocio Torres
 
PPTX
Burns night (3ºc 2012 2013
Rocio Torres
 
PPTX
как изменился уровень жизни россиян 2011
SalesDog
 
PPT
Sosiaalisen median case-kimara
Darwin Oy
 
PDF
Modulo 2
katherinn
 
PDF
Green Energy Incentives Workbook
Darren Welker, CPA
 
PPTX
Analogical thinking
Arvind Krishnaa
 
PPTX
Onko yrityksellä mitään järkeä olla sosiaalisessa mediassa
Darwin Oy
 
PDF
Recognition of unistroke gesture sequences
Arvind Krishnaa
 
PDF
Peta persoalan
Mohammad Subhan
 
PDF
Economics of Green Growth & National Innovation Strategies
CambridgeIP Ltd
 
14526610 english-banana-the-second-book-
incasong
 
Vchitel_projekt
Tanya Puzir
 
Participants List For Jsm
JADE aisbl
 
Goodrich Global 产品常见问题 (地板)
Goodrich Global
 
Tulospohjainen Markkinointi Netissä
Darwin Oy
 
♥♥♥
jennybabe
 
Asiakkaan Kohtaaminen
Darwin Oy
 
Hyvinvointituotteen markkinointi - miten onnistut aina!
Darwin Oy
 
Chowka bhara
Arvind Krishnaa
 
Unit 0
Rocio Torres
 
Burns night (3ºc 2012 2013
Rocio Torres
 
как изменился уровень жизни россиян 2011
SalesDog
 
Sosiaalisen median case-kimara
Darwin Oy
 
Modulo 2
katherinn
 
Green Energy Incentives Workbook
Darren Welker, CPA
 
Analogical thinking
Arvind Krishnaa
 
Onko yrityksellä mitään järkeä olla sosiaalisessa mediassa
Darwin Oy
 
Recognition of unistroke gesture sequences
Arvind Krishnaa
 
Peta persoalan
Mohammad Subhan
 
Economics of Green Growth & National Innovation Strategies
CambridgeIP Ltd
 
Ad

Similar to LinkedIn TBC JavaScript 100: Intro (20)

PDF
JavaScript For CSharp Developer
Sarvesh Kushwaha
 
PDF
Stuff you didn't know about action script
Christophe Herreman
 
PPTX
JavaScript Bootcamp
Jan Maximilian Winther Kristiansen
 
KEY
JavaScript Neednt Hurt - JavaBin talk
Thomas Kjeldahl Nilsson
 
PPSX
DIWE - Programming with JavaScript
Rasan Samarasinghe
 
PDF
Javascript status 2016
Arshavski Alexander
 
PDF
Java script object model
James Hsieh
 
PDF
JavaScript(Es5) Interview Questions & Answers
Ratnala Charan kumar
 
PDF
JavaScript Beginner Tutorial | WeiYuan
Wei-Yuan Chang
 
PPT
fundamentals of JavaScript for students.ppt
dejen6
 
PPT
Basics of Javascript
Universe41
 
PPT
introduction to javascript concepts .ppt
ansariparveen06
 
PDF
Fii Practic Frontend - BeeNear - laborator3
BeeNear
 
PPT
Wakanday JS201 Best Practices
Juergen Fesslmeier
 
PPTX
JavaScript Literacy
David Jacobs
 
PPTX
Java script for web developer
Chalermpon Areepong
 
PPT
An introduction to javascript
MD Sayem Ahmed
 
PPTX
Javascript 101
Shlomi Komemi
 
KEY
Week3
Will Gaybrick
 
JavaScript For CSharp Developer
Sarvesh Kushwaha
 
Stuff you didn't know about action script
Christophe Herreman
 
JavaScript Neednt Hurt - JavaBin talk
Thomas Kjeldahl Nilsson
 
DIWE - Programming with JavaScript
Rasan Samarasinghe
 
Javascript status 2016
Arshavski Alexander
 
Java script object model
James Hsieh
 
JavaScript(Es5) Interview Questions & Answers
Ratnala Charan kumar
 
JavaScript Beginner Tutorial | WeiYuan
Wei-Yuan Chang
 
fundamentals of JavaScript for students.ppt
dejen6
 
Basics of Javascript
Universe41
 
introduction to javascript concepts .ppt
ansariparveen06
 
Fii Practic Frontend - BeeNear - laborator3
BeeNear
 
Wakanday JS201 Best Practices
Juergen Fesslmeier
 
JavaScript Literacy
David Jacobs
 
Java script for web developer
Chalermpon Areepong
 
An introduction to javascript
MD Sayem Ahmed
 
Javascript 101
Shlomi Komemi
 

Recently uploaded (20)

PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Captain IT
 
PDF
GYTPOL If You Give a Hacker a Host
linda296484
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
CIFDAQ
 
PDF
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
PDF
Make GenAI investments go further with the Dell AI Factory - Infographic
Principled Technologies
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
CIFDAQ
 
PDF
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PPTX
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Captain IT
 
GYTPOL If You Give a Hacker a Host
linda296484
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
CIFDAQ
 
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
Make GenAI investments go further with the Dell AI Factory - Infographic
Principled Technologies
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
CIFDAQ
 
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 

LinkedIn TBC JavaScript 100: Intro

  • 1. JavaScript Basics Adam Crabtree (Adapted from Joar Gullestad Pettersen’s http://slideshare.net/Peanuts_Stavanger/javascript-basics-29353026)
  • 2. JavaScript Data Types String, Number, Boolean, Array, Object, Null, Undefined
  • 4. Dynamic Types var x; // x is: undefined
  • 5. Dynamic Types var x; // x is: undefined x = 5; // x is set to a Number: 5
  • 6. Dynamic Types var x; // x is: undefined x = 5; // x is set to a Number: 5 x = "Bond"; // x is changed to a String: "Bond"
  • 7. Strings var car = "Telsa Model S"; var car2 = 'Tesla Model S';
  • 8. Numbers • var x = 42; • var y = 13.37; • var z = 10e3; // Written without decimals // Written with decimals // Exponential notation
  • 9. Booleans • var x = true; • var y = false;
  • 10. Array var frukt = new Array(); frukt[0] = "eple"; frukt[1] = "banan"; frukt[2] = "pære"; ["eple", "banan", "pære"]
  • 11. Array 2 var frukt = new Array("eple", "banan", "pære"); ["eple", "banan", "pære"]
  • 12. Array 3 var frukt = ["eple", "banan", "pære"]; ["eple", "banan", "pære"]
  • 13. Array 4 • var frukt = ["eple", "banan", "pære"] • • • • frukt.pop(); // ["eple", "banan"] frukt.push("tomat"); // ["eple", "banan", "tomat"] frukt.shift(); // ["banan", "tomat"] frukt.unshift("tomat"); // ["tomat", "banan", "tomat"]
  • 15. Objects • • • • • Everything is an Object Booleans can be objects or primitive data treated as objects Numbers can be objects or primitive data treated as objects Strings are also objects or primitive data treated as objects Dates, Maths, Regular expressions, Arrays and functions are always objects
  • 16. Object literal An object is just a special kind of data, with properties and methods. var person = { firstName: "John", lastName: "Doe", id: 5 };
  • 17. Object literal An object is just a special kind of data, with properties and methods. var person = { firstName: "John", lastName: "Doe", id: 5 }; person.id; // 5
  • 18. Object literal An object is just a special kind of data, with properties and methods. var person = { firstName: "John", lastName: "Doe", address: { street: "Strandsvingen", number: "14B" } }; person.address.street; // "Strandsvingen"
  • 19. Functions a block of code that will be executed when "someone" calls it: function add(a, b) { return a + b; } var add = function(a, b) { return a + b; }
  • 20. Object Constructor function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } var randomPerson = new Person("John", "Doe");
  • 21. Object var randomPerson = new Object(); randomPerson.firstName = "John"; randomPerson.lastName = "Doe";
  • 22. Boolean expressions if (a == 2) {//if this is true //do this... }
  • 23. Type coercion • When JavaScript are unsure what you mean, It makes a guess • Example: if ('false') { console.log("true"); } • «A String is obviously not true or false, you probably mean true!»
  • 24. True!  • if (true) { alert("true"); } // alerts "true" • if ('false') { alert("true"); } // alerts "true" • if ([]) { alert("true"); } // alerts "true" • if (5) { alert("true"); } // alerts "true" • if ({}) { alert("true"); } // alerts "true"
  • 25. False  • if (false) { alert("false"); } // does nothing • if (0) { alert("false"); } // does nothing • if (null) { alert("false"); } // does nothing • if (undefined) { alert("false"); } // does nothing • if ("") { alert("false"); } // does nothing
  • 26. More type coercion  1 == "1" true == "1" false == "0"
  • 27. More type coercion  1 == "1" true true == "1" false == "0"
  • 28. More type coercion  1 == "1" true true == "1" true false == "0"
  • 29. More type coercion  1 == "1" true true == "1" true false == "0" true
  • 30. More type coercion 1 == "1" true true == "1" true false == "0" true false == "0" == 1 == true == [] == ""
  • 31. More type coercion  1 == "1" true true == "1" true false == "0" true false == "0" == 1 == true == [] == "" true
  • 34. === 1 == true true 1 === true false 1 == "1" true 1 === "1" false
  • 35. Scope & global variables • C#/Java: anything inside curly brackets, {} , defines a scope • Example: if (true) { var scopeVariable = "Test"; } scopeVariable = "Test2"; // variable not defined
  • 36. Scope & global variables • Javascript: only functions define a new scope • Example: if (true) { var scopeVariable = "Test"; } scopeVariable; // value: "Test";
  • 37. Scope & global variables function scope1() { var member; //is a member of the scope defined by the function example //this function is also part of the scope of the function example var innerScope = function() { member= 12; // traverses scope and assigns member in scope1 to 12 }; };
  • 38. Scope & global variables function scope1() { var member; //is a member of the scope defined by the function example //this function is also part of the scope of the function example var innerScope = function() { var member= 12; // defines member in this scope and do not traverse }; };
  • 39. Scope & global variables function scope1() { var member; //is a member of the scope defined by the function example //this function is also part of the scope of the function example var bar = function() { member= 12; // traverses scope and assigns scope1member.foo to 12 }; }; function scope2() { member = 15; // traverses scope and assigns global.member to 15 }
  • 40. Namespaces • Not built into JavaScript • Problem?
  • 41. JavaScript (Ad-hoc) namespace var Peanuts = {}; // Object used as namespace
  • 42. JavaScript (Ad-hoc) namespace var Peanuts = Peanuts || {}; // in case it already exists
  • 43. «Classes» and «methods» ? var Peanuts = Peanuts || {}; Peanuts.Calculator = { add: function (a,b) { return a + b; }, subtract: function () { return a - b; } }; Peanuts.Calculator.add(1, 2); // 3
  • 44. Immediately invoked function expressions • (function () { • // logic/code here • })();
  • 45. Why? • Executes an expression and therefore code immediately • Creates «privacy» for your code (function scope ftw!)
  • 46. How? • JavaScript, parenthesis can’t contain statements. • When the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.
  • 47. Immediately invoked function expressions • • • • • (function () { // logic/code here })(); The key thing about JavaScript expressions is that they return values. To invoke the function expression right away we just need to tackle a couple of parentheses on the end(like above).
  • 48. Immediately invoked function expressions • (function (innerValue) { • // logic/code here • })(outerValue);
  • 49. Revealing module pattern var Peanuts = Peanuts || {}; Peanuts.Calculator = function () { var add = function(a, b) { return a + b; }; var subtract = function(a, b) { return a - b; }; return { add: add, subtract: subtract }; }; Peanuts.Calculator().add(1, 2); // 3
  • 50. Revealing module pattern 2 var Peanuts = Peanuts || {}; Peanuts.Calculator = (function () { var add = function(a, b) { return a + b; }; return { add: add, }; })(); Peanuts.Calculator.add(1, 2); // 3
  • 51. Revealing module pattern 3 var Peanuts = Peanuts || {}; Peanuts.Calculator = (function () { var PI = 3.14; // private variable! var getCircleArea = function(r) { return PI * r * r; }; return { getCircleArea: getCircleArea // public method }; })(); Peanuts.Calculator.getCircleArea(2); // 12.56