Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Object-Oriented JavaScript - Second Edition
Object-Oriented JavaScript - Second Edition

Object-Oriented JavaScript - Second Edition: If you've limited or no experience with JavaScript, this book will put you on the road to being an expert. A wonderfully compiled introduction to objects in JavaScript, it teaches through examples and practical play. , Second Edition

eBook
$9.99 $32.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Object-Oriented JavaScript - Second Edition

Chapter 2. Primitive Data Types, Arrays, Loops, and Conditions

Before diving into the object-oriented features of JavaScript, let's first take a look at some of the basics. This chapter walks you through the following:

  • The primitive data types in JavaScript, such as strings and numbers
  • Arrays
  • Common operators, such as +, -, delete, and typeof
  • Flow control statements, such as loops and if-else conditions

Variables

Variables are used to store data; they are placeholders for concrete values. When writing programs, it's convenient to use variables instead of the actual data, as it's much easier to write pi instead of 3.141592653589793, especially when it happens several times inside your program. The data stored in a variable can be changed after it was initially assigned, hence the name "variable". You can also use variables to store data that is unknown to you while you write the code, such as the result of a later operation.

Using a variable requires two steps. You need to:

  • Declare the variable
  • Initialize it, that is, give it a value

To declare a variable, you use the var statement, like this:

var a;
var thisIsAVariable; 
var _and_this_too; 
var mix12three;

For the names of the variables, you can use any combination of letters, numbers, the underscore character, and the dollar sign. However, you can't start with a number, which means that this is invalid:

var 2three4five...

Operators

Operators take one or two values (or variables), perform an operation, and return a value. Let's check out a simple example of using an operator, just to clarify the terminology:

> 1 + 2;
3

In this code:

  • + is the operator
  • The operation is addition
  • The input values are 1 and 2 (the input values are also called operands)
  • The result value is 3
  • The whole thing is called an expression

Instead of using the values 1 and 2 directly in the expression, you can use variables. You can also use a variable to store the result of the operation, as the following example demonstrates:

> var a = 1;
> var b = 2;
> a + 1;
2
> b + 2;
4
> a + b;
3
> var c = a + b;
> c;
3

The following table lists the basic arithmetic operators:

Operator symbol

Operation

Example

+

Addition

> 1 + 2;
3

-

Subtraction

> 99.99 – 11;
88.99

*

Multiplication

> 2 * 3;
6

/

Division

> 6 / 4;
1.5

%

Modulo, the remainder of a division

>...

Primitive data types

Any value that you use is of a certain type. In JavaScript, there are just a few primitive data types:

  1. Number: This includes floating point numbers as well as integers. For example, these values are all numbers: 1, 100, 3.14.
  2. String: These consist of any number of characters, for example "a", "one", and "one 2 three".
  3. Boolean: This can be either true or false.
  4. Undefined: When you try to access a variable that doesn't exist, you get the special value undefined. The same happens when you declare a variable without assigning a value to it yet. JavaScript initializes the variable behind the scenes with the value undefined. The undefined data type can only have one value – the special value undefined.
  5. Null: This is another special data type that can have only one value, namely the null value. It means no value, an empty value, or nothing. The difference with undefined is that if a variable has a value null, it's still defined, it...

Strings

A string is a sequence of characters used to represent text. In JavaScript, any value placed between single or double quotes is considered a string. This means that 1 is a number, but "1" is a string. When used with strings, typeof returns the string "string":

> var s = "some characters";
> typeof s;
"string"
> var s = 'some characters and numbers 123 5.87';
> typeof s;
"string"

Here's an example of a number used in the string context:

> var s = '1';
> typeof s;
"string"

If you put nothing in quotes, it's still a string (an empty string):

> var s = ""; typeof s;
"string"

As you already know, when you use the plus sign with two numbers, this is the arithmetic addition operation. However, if you use the plus sign with strings, this is a string concatenation operation, and it returns the two strings glued together:

> var s1 = "web"; 
> var s2...

Booleans

There are only two values that belong to the Boolean data type: the values true and false, used without quotes:

> var b = true; 
> typeof b;
"boolean"
> var b = false; 
> typeof b;
"boolean"

If you quote true or false, they become strings:

> var b = "true"; 
> typeof b;
"string"

Variables


Variables are used to store data; they are placeholders for concrete values. When writing programs, it's convenient to use variables instead of the actual data, as it's much easier to write pi instead of 3.141592653589793, especially when it happens several times inside your program. The data stored in a variable can be changed after it was initially assigned, hence the name "variable". You can also use variables to store data that is unknown to you while you write the code, such as the result of a later operation.

Using a variable requires two steps. You need to:

  • Declare the variable

  • Initialize it, that is, give it a value

To declare a variable, you use the var statement, like this:

var a;
var thisIsAVariable; 
var _and_this_too; 
var mix12three;

For the names of the variables, you can use any combination of letters, numbers, the underscore character, and the dollar sign. However, you can't start with a number, which means that this is invalid:

var 2three4five;

To initialize a variable...

Operators


Operators take one or two values (or variables), perform an operation, and return a value. Let's check out a simple example of using an operator, just to clarify the terminology:

> 1 + 2;
3

In this code:

  • + is the operator

  • The operation is addition

  • The input values are 1 and 2 (the input values are also called operands)

  • The result value is 3

  • The whole thing is called an expression

Instead of using the values 1 and 2 directly in the expression, you can use variables. You can also use a variable to store the result of the operation, as the following example demonstrates:

> var a = 1;
> var b = 2;
> a + 1;
2
> b + 2;
4
> a + b;
3
> var c = a + b;
> c;
3

The following table lists the basic arithmetic operators:

Operator symbol

Operation

Example

+

Addition

> 1 + 2;
3

-

Subtraction

> 99.99 – 11;
88.99

*

Multiplication

> 2 * 3;
6

/

Division

> 6 / 4;
1.5

%

Modulo, the remainder of a division

> 6 % 3;
0
&gt...

Primitive data types


Any value that you use is of a certain type. In JavaScript, there are just a few primitive data types:

  1. Number: This includes floating point numbers as well as integers. For example, these values are all numbers: 1, 100, 3.14.

  2. String: These consist of any number of characters, for example "a", "one", and "one 2 three".

  3. Boolean: This can be either true or false.

  4. Undefined: When you try to access a variable that doesn't exist, you get the special value undefined. The same happens when you declare a variable without assigning a value to it yet. JavaScript initializes the variable behind the scenes with the value undefined. The undefined data type can only have one value – the special value undefined.

  5. Null: This is another special data type that can have only one value, namely the null value. It means no value, an empty value, or nothing. The difference with undefined is that if a variable has a value null, it's still defined, it just so happens that its value is nothing. You...

Strings


A string is a sequence of characters used to represent text. In JavaScript, any value placed between single or double quotes is considered a string. This means that 1 is a number, but "1" is a string. When used with strings, typeof returns the string "string":

> var s = "some characters";
> typeof s;
"string"
> var s = 'some characters and numbers 123 5.87';
> typeof s;
"string"

Here's an example of a number used in the string context:

> var s = '1';
> typeof s;
"string"

If you put nothing in quotes, it's still a string (an empty string):

> var s = ""; typeof s;
"string"

As you already know, when you use the plus sign with two numbers, this is the arithmetic addition operation. However, if you use the plus sign with strings, this is a string concatenation operation, and it returns the two strings glued together:

> var s1 = "web"; 
> var s2 = "site"; 
> var s = s1 + s2; 
> s;
"website"
> typeof s;
"string"

The dual purpose of the + operator is a source...

Booleans


There are only two values that belong to the Boolean data type: the values true and false, used without quotes:

> var b = true; 
> typeof b;
"boolean"
> var b = false; 
> typeof b;
"boolean"

If you quote true or false, they become strings:

> var b = "true"; 
> typeof b;
"string"

Logical operators


There are three operators, called logical operators, that work with Boolean values. These are:

  • ! – logical NOT (negation)

  • && – logical AND

  • || – logical OR

You know that when something is not true, it must be false. Here's how this is expressed using JavaScript and the logical ! operator:

> var b = !true;
> b;
false

If you use the logical NOT twice, you get the original value:

> var b = !!true;
> b;
true

If you use a logical operator on a non-Boolean value, the value is converted to Boolean behind the scenes:

> var b = "one";
> !b;
false

In the preceding case, the string value "one" is converted to a Boolean, true, and then negated. The result of negating true is false. In the next example, there's a double negation, so the result is true:

> var b = "one";
> !!b;
true

You can convert any value to its Boolean equivalent using a double negation. Understanding how any value converts to a Boolean is important. Most values convert to true with the exception...

Comparison


There's another set of operators that all return a Boolean value as a result of the operation. These are the comparison operators. The following table lists them together with example uses:

Operator symbol

Description

Example

==

Equality comparison: Returns true when both operands are equal. The operands are converted to the same type before being compared. Also called loose comparison.

> 1 == 1;
true

> 1 == 2;
false

> 1 == '1';
true

===

Equality and type comparison: Returns true if both operands are equal and of the same type. It's better and safer to compare this way because there's no behind-the-scenes type conversions. It is also called strict comparison.

> 1 === '1';
false

> 1 === 1;
true

!=

Non-equality comparison: Returns true if the operands are not equal to each other (after a type conversion).

> 1 != 1;
false

> 1 != '1';
false

> 1 != '2';
true

!==

Non-equality comparison without type conversion: Returns...

Primitive data types recap


Let's quickly summarize some of the main points discussed so far:

  • There are five primitive data types in JavaScript:

    • Number

    • String

    • Boolean

    • Undefined

    • Null

  • Everything that is not a primitive data type is an object

  • The primitive number data type can store positive and negative integers or floats, hexadecimal numbers, octal numbers, exponents, and the special numbers NaN, Infinity, and –Infinity

  • The string data type contains characters in quotes

  • The only values of the Boolean data type are true and false

  • The only value of the null data type is the value null

  • The only value of the undefined data type is the value undefined

  • All values become true when converted to a Boolean, with the exception of the six falsy values:

    • ""

    • null

    • undefined

    • 0

    • NaN

    • false

Arrays


Now that you know about the basic primitive data types in JavaScript, it's time to move to a more powerful data structure—the array.

So, what is an array? It's simply a list (a sequence) of values. Instead of using one variable to store one value, you can use one array variable to store any number of values as elements of the array.

To declare a variable that contains an empty array, you use square brackets with nothing between them:

> var a = [];

To define an array that has three elements, you do this:

> var a = [1, 2, 3];

When you simply type the name of the array in the console, you get the contents of your array:

> a;
[1, 2, 3]

Now the question is how to access the values stored in these array elements. The elements contained in an array are indexed with consecutive numbers starting from zero. The first element has index (or position) 0, the second has index 1, and so on. Here's the three-element array from the previous example:

Index

Value

0

1

1

2

2

3

To...

Conditions and loops


Conditions provide a simple but powerful way to control the flow of code execution. Loops allow you to perform repetitive operations with less code. Let's take a look at:

  • if conditions

  • switch statements

  • while, do-while, for, and for-in loops

Note

The examples in the following sections require you to switch to the multiline Firebug console. Or, if you use the WebKit console, use Shift + Enter instead of Enter to add a new line.

The if condition

Here's a simple example of an if condition:

var result = '', a = 3;
if (a > 2) {
  result = 'a is greater than 2';
}

The parts of the if condition are:

  • The if statement

  • A condition in parentheses—"is a greater than 2?"

  • A block of code wrapped in {} that executes if the condition is satisfied

The condition (the part in parentheses) always returns a Boolean value, and may also contain the following:

  • A logical operation: !, &&, or ||

  • A comparison, such as ===, !=, >, and so on

  • Any value or variable that can be converted to a Boolean...

Code blocks


In the preceding examples, you saw the use of code blocks. Let's take a moment to clarify what a block of code is, because you use blocks extensively when constructing conditions and loops.

A block of code consists of zero or more expressions enclosed in curly brackets:

{
  var a = 1;
  var b = 3;
}

You can nest blocks within each other indefinitely:

{
  var a = 1;
  var b = 3;
  var c, d;
  {
    c = a + b;
    {
      d = a - b;
    }
  }
}

Tip

Best practice tips

  • Use end-of-line semicolons, as discussed previously in the chapter. Although the semicolon is optional when you have only one expression per line, it's good to develop the habit of using them. For best readability, the individual expressions inside a block should be placed one per line and separated by semicolons.

  • Indent any code placed within curly brackets. Some programmers like one tab indentation, some use four spaces, and some use two spaces. It really doesn't matter, as long as you're consistent. In the preceding example...

Left arrow icon Right arrow icon

Key benefits

  • Think in JavaScript
  • Make object-oriented programming accessible and understandable to web developers
  • Apply design patterns to solve JavaScript coding problems
  • Learn coding patterns that unleash the unique power of the language
  • Write better and more maintainable JavaScript code
  • Type in and play around with examples that can be used in your own scripts

Description

JavaScript is the behavior, the third pillar in today's paradigm that looks at web pages as something that consists of clearly distinguishable parts: content (HTML), presentation (CSS) and behavior (JavaScript). Using JavaScript, you can create not only web pages but also desktop widgets, browser and application extensions, and other pieces of software. It's a pretty good deal: you learn one language and then code all kinds of different applications. While there's one chapter specifically dedicated to the web browser environment including DOM, Events and AJAX tutorials, the rest is applicable to the other environments Many web developers have tried coding or adopting some bits of JavaScript, but it is time to "man up" and learn the language properly because it is the language of the browser and is, virtually, everywhere. This book starts from zero, not assuming any prior JavaScript programming knowledge and takes you through all the in-depth and exciting futures hidden behind the facade. Once listed in the "nice to have" sections of job postings, these days the knowledge of JavaScript is a deciding factor when it comes to hiring web developers. After reading this book you'll be prepared to ace your JavaScript job interview and even impress with some bits that the interviewer maybe didn't know. You should read this book if you want to be able to take your JavaScript skills to a new level of sophistication.

Who is this book for?

For new to intermediate JavaScript developer who wants to prepare themselves for web development problems solved by smart JavaScript!

What you will learn

  • The basics of object-oriented programming, and how to apply it in the JavaScript environment
  • How to set up and use your training environment (Firebug)
  • In depth discussion of data types, operators, and flow control statements in JavaScript
  • In depth discussion of functions, function usage patterns, and variable scope
  • Understand how prototypes work
  • Reuse code with common patterns for inheritance
  • Make your programs cleaner, faster and compatible with other programs and libraries
  • Use object-oriented JavaScript for improving script performance
  • Achieve missing object-oriented features in JavaScript

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 26, 2013
Length: 382 pages
Edition : 2nd
Language : English
ISBN-13 : 9781849693134
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jul 26, 2013
Length: 382 pages
Edition : 2nd
Language : English
ISBN-13 : 9781849693134
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 131.97
JavaScript and JSON Essentials
$32.99
Learning jQuery - Fourth Edition
$43.99
Object-Oriented JavaScript - Second Edition
$54.99
Total $ 131.97 Stars icon
Banner background image

Table of Contents

13 Chapters
1. Object-oriented JavaScript Chevron down icon Chevron up icon
2. Primitive Data Types, Arrays, Loops, and Conditions Chevron down icon Chevron up icon
3. Functions Chevron down icon Chevron up icon
4. Objects Chevron down icon Chevron up icon
5. Prototype Chevron down icon Chevron up icon
6. Inheritance Chevron down icon Chevron up icon
7. The Browser Environment Chevron down icon Chevron up icon
8. Coding and Design Patterns Chevron down icon Chevron up icon
A. Reserved Words Chevron down icon Chevron up icon
B. Built-in Functions Chevron down icon Chevron up icon
C. Built-in Objects Chevron down icon Chevron up icon
D. Regular Expressions Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.6
(11 Ratings)
5 star 63.6%
4 star 36.4%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Harpinder Sandhu May 23, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Its really good book for JavaScript
Amazon Verified review Amazon
Matt Feb 22, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
this book is gold.I'm back a year later. I still use this book. If you are a developer or aspiring to be one.. do yourself a solid, buy this book and go through all the exercises at the end of the chapters. By that point you should have a nice foundation of JavaScript.
Amazon Verified review Amazon
Amazon-Kunde Apr 14, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Der Titel beschreibt deutlich, worum es sich in diesem Werk handelt. Das Buch ist verständlich und fachlich solide. Mir hat es und wird es noch weiter helfen, das Konzept der klassenlosen Objekte mit Prototypen und seinen potentiellen Fallstricken besser zu verstehen und in Richtung Beherrschung zu marschieren. Ein gutes Buch mit klarer Kaufempfehlung.
Amazon Verified review Amazon
Alfred J Speller Jun 07, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If you want to take your Javascript skills to the next level this is a great book to start with. The explanations are to the point and short. The content is very rich and keep me wanting to dive in to learn more. For me this wasnt a book that you read just once and move on. I have referred to several chapters and/or concepts over and over to make sure I have a complete understanding. I do think the closure explanation with the image is better described in the 1st edition though.
Amazon Verified review Amazon
Prometheus Jul 02, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book on the subject.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.