Learning JavaScript programming. Learn JavaScript Programming (Eric Freeman, Elizabeth Robson) Learn JavaScript Programming download pdf

15
aug
2016

Learn JavaScript Programming (Eric Freeman, Elizabeth Robson)

ISBN: 978-5-496-01257-7, Head First O "Reilly
Format: PDF, OCR with errors
Eric Freeman, Elizabeth Robson
Year of issue: 2015
Genre: Programming languages
Publisher: Peter
Russian language
Number of pages: 640
Description: Are you ready to take your web programming a step further and move from HTML and CSS layout to full-fledged dynamic pages? Then it's time to get acquainted with the "hottest" programming language - JavaScript!
With this book, you will learn everything about JavaScript, from variables to loops. You will understand why different browsers react differently to code and how to write universal code that is supported by all browsers. It will become clear to you why you never have to worry about page congestion and data transfer errors with JavaScript code. Don't be alarmed, even if you haven't written a single line of code before - thanks to the unique presentation format, this book will easily guide you along the entire learning path: from writing a simple script to creating complex web projects that will work in all modern browsers.
A special feature of this edition is the unique way of presenting the material, which sets O "Reilly's" Head First "series apart from the many boring books devoted to programming.


26
jul
2017

Learning JavaScript. A Guide to Building Modern Websites (Ethan Brown)

ISBN: 978-5-9908463-9-5, 978-1-491-91491-5

By Ethan Brown
Year of issue: 2017
Genre: Programming
Publisher: Williams
Russian language
Number of pages: 363
Summary: Now is the time to learn JavaScript. With the release of the latest JavaScript specification, ECMAScript 6.0 (ES6), learning how to create high-quality applications in this language is easier than ever. This book introduces programmers (hobbyists and professionals) to the ES6 specification, along with some of the associated tools and techniques for purely p ...


23
june
2007

Genre: Programming
Author: Khomonenko A.D.
Country Russia
Number of pages: 252
Description: Contains a systematic presentation of the basic techniques of programming in the language
С ++: description of data types, declaration of variables, organization of branches and loops, description and use of arrays, pointers, functions. The concepts and techniques of object-oriented programming are considered. The technology of developing programs in the Borland C ++ Builder environment is described.
Format: PDF


08
aug
2012

PHP, JavaScript, JQuery, CSS, HTML, MySQL, OOP. A short collection of possible interview questions and answers. (Andrey Shevchenko)

Format: PDF, eBook (originally computer)
Author: Andrey Shevchenko
Year of issue: 2012
Genre: Reference books, textbooks
Publisher: NeisstonPub
Russian language
Number of pages: 57
Description: The idea of \u200b\u200bwriting this book came to me after I, preparing for my first interview for the position of PHP-developer, could not find a sensible "tutorial" that would collect the most common questions and tasks that are asked for such interviews. But do you need to prepare somehow? It is necessary. Otherwise, they will ask what is the difference between MyISAM and InnoDB, or what a jQuery filter $ (“a ...


18
oct
2010

Ruby Programming (Hal Fulton)


Publisher: M., DMK Press ISBN: 5-94074-357-9
Year of issue: 2007
Genre: Programming
Russian language
Number of pages: 688
Description: Ruby is a relatively new object-oriented language, developed by Yukihiro Matsumoto in 1995 and borrowing some features from LISP, Smalltalk, Perl, CLU and others. The language is actively developing and used in a variety of areas: from system administration to the development of complex dynamic sites. The book is a complete guide to Ruby - it can be used both as a tutorial and as a reference ...


11
oct
2012

C ++ Programming (4th Edition) (Walter Savich)


By Walter Savich
Year of issue: 2004
Genre: Programming
Publisher: Addison-Wesley
Russian language
Number of pages: 784
Description: The book contains comprehensive information about the C ++ programming language. In addition to "standard" topics such as variable declarations, selection operators, loops, arrays, functions, etc., it also covers working with vectors, dynamic multidimensional arrays, exception handling, pointers, and operator overloading in detail. The self-study examples and assignments contained in each chapter will help the reader to consolidate and ...


26
aug
2010

Programming in C # (Book # 2) (various)

ISBN: 5-94074-409-5
Format: PDF, OCR without errors
Year of issue: 2008
Author: Gornakov S.G.
Genre: Mobile phone programming
Publisher: DMK Press
Number of pages: 512
Description: This is the second edition of the popular book. The new version of the edition contains nine additional chapters. Now the reader, in addition to programming applications for the Java 2 ME platform, will study the complete process of creating a mobile game. While working with the book, the approach to the formation of a full-fledged mobile game engine will be mastered, work with graphics, animation will be studied, examples of multilayer and animated game cards are given. Consider ...


22
apr
2018

Programming network applications in C ++. Volume 1 (Douglas S. Schmidt, Stephen D. Houston)

ISBN: 978-5-9518-0362-7
Format: JPG, Scanned pages
By Douglas S. Schmidt, Stephen D. Houston
Year of issue: 2009
Genre: Programming
Publisher: Binom
Russian language
Number of pages: 304
Description: The book outlines one of the most promising approaches to professional programming of network applications in C ++. The main reasons for the complexity of developing network applications are considered, as well as design patterns and an open source ACE IIO middleware layer, which can be freely downloaded from a website to the Internet and which is one of the most portable and ...


05
dec
2009

Jasmine Blanchett, Mark Summerfield. GUI Programming in C ++

ISBN: 978-5-91136-059-7
Format: DjVu, OCR without errors
Year of issue: 2008
By Jasmine Blanchett, Mark Summerfield
Genre: Programming
Publisher: Kudits-Press
Number of pages: 736
Description: The book is an updated and revised edition of the book "Qt4: GUI Programming in C ++", which is in demand on the Russian market, published in 2007. In the new edition, changes were made related to the use of the features that appeared in Qt versions 4.2 and 4.3, new chapters were added on setting up a dialogue with the user and creating application scripts, the basic principles were considered ...


24
but I
2008

Gornakov S.G. - Programming mobile phones on J2ME

Format: DjVu, Scanned pages
Year of issue: 2005
Author: Gornakov S.G
Genre: J2ME tutorial
Publisher: dmk
Number of pages: 331
Description: a pretty good and understandable book on programming for mobile phones in Java


03
jul
2016

C Programming for Beginners. 4th edition (Mike McGrath)

ISBN: 978-5-699-79117-0
Format: PDF, eBook (originally computer)
By Mike McGrath
Translator: M. Reitman
Year of issue: 2016
Genre: Computer literature, programming
Publisher: Eksmo
Series: Programming for Beginners
Russian language
Number of pages: 192
Description: In this book, with the help of sample programs and illustrations showing the results of the work of the code, all the key aspects of the C language are analyzed.This book even describes how to install a free compiler for the C language and work in it, you simply will not have a chance to make a mistake ! The book is ideal for programmers who ...


25
but I
2010

Publisher: Peter
Interface language: Russian only
Medicine: Not required
Description: This book is intended for self-development of programming in the JavaScript language. In addition to a general guide, it contains many examples and texts of ready-to-use programs. Covers the creation of scripts for websites, as well as scripts executed by Windows Scripting Host. Appendices provide reference Information in JavaScript and HTML. The book is addressed to both beginners and those who already have some experience in web design and programming. In the second and ...

11
aug
2012

JavaScript. User Bible (5th Edition) (Danny Goodman, Michael Morrison)

ISBN: 5-8459-1027-7
Format: PDF, Scanned pages
By Danny Goodman, Michael Morrison
Year of issue: 2006
Genre: Programming
Publisher: Dialectics
Russian language
Number of pages: 1179
Description: This book is addressed to a wide range of readers of Web designers who have decided to study the JavaScript language in detail. It has all the potential to win the title of complete reference guide to JavaScript, not only in the eyes of its developers, but also in the hearts of users. This edition details almost all JavaScript scripting tools used in modern and legacy b ...


17
aug
2012

Learning Ruby (Michael Fitzgerald)

ISBN: 978-5-9775-0225-2, 978-0-596-52986-4;
Format: DjVu, Scanned pages
By Michael Fitzgerald
Year of issue: 2008
Genre: Programming
Publisher: BHV-Petersburg
Russian language
Number of pages: 336
Description: The book is a guide to creating web applications in Ruby. The study is based on practical examples, which are listed on almost every page. The basics of Ruby are given, conditional operators, strings and regular expressions, operators, functions, arrays, hashes, working with files, classes are considered. Describes XML processing, reflection, metaprogramming, ...




Are you ready to take your web programming a step further and move from HTML and CSS layout to full-fledged dynamic pages? Then it's time to get acquainted with the “hottest” programming language - JavaScript!
With this book, you will learn everything about JavaScript, from variables to loops. You will understand why different browsers react differently to code and how to write universal code that is supported by all browsers. It will become clear to you why you never have to worry about page congestion and data transfer errors with JavaScript code. Don't be alarmed, even if you haven't written a single line of code before - thanks to the unique presentation format, this book will easily guide you along the entire learning path: from writing a simple script to creating complex web projects that will work in all modern browsers.
A special feature of this edition is the unique way of presenting the material, which sets O'Reilly's “Head First” series apart from many boring books devoted to programming.

In unfamiliar waters

first acquaintance with javascript

JavaScript offers fantastic opportunities. JavaScript, the main programming language of the World Wide Web, allows you to define extended behavior in web pages. Forget dry, boring, static pages that just take up screen space - with JavaScript you will
interact with users, react to events, receive and use data from the Internet, display graphics ... and much, much more. With a good knowledge of JavaScript, you can even program completely new behaviors in your pages.

And do not hesitate - your knowledge will be in demand. JavaScript is now not only one of the most popular programming languages, but is also supported by all modern (and many non-modern) browsers; moreover, there are built-in JavaScript implementations that exist separately from browsers. Enough talk, though. It's time to get down to business!

How JavaScript Works 38
How JavaScript is written 39
How to include JavaScript code on page 40
JavaScript, you've come a long way, baby ... 42
How teams are created 46
Variables and Values \u200b\u200b47
Caution, keywords! 48
Be careful with expressions! 51
Repeated operations 53
How while 54 works
Making Decisions in JavaScript 58
And if you have to make a LOT of decisions ... 59
Engage the user on page 61
A close look at console.log 63
How to open console 64
Writing a Serious JavaScript Application 65
How do I add code to a page? (counting ways) 68
Markup and Code: Paths diverge 69

The next step

real code

You already know what variables, types, expressions ... and so on. You already know a thing or two about JavaScript. Moreover, knowledge is enough to start writing real programs that do something interesting, which someone will use. True, you do not have enough hands-on experience in coding, and we will start solving this problem right now. How? Let's just start writing a simple game, fully implemented in JavaScript. The task is large-scale, but we will move towards the goal gradually, step by step. So, let's get down to business, and if you suddenly want to use our development in your projects - we do not mind, dispose of the code as you see fit.

Functions for everyone

familiarity with functions

In this chapter, you will master your first super ability. You already know a thing or two about programming; it's time to take the next step and master the functions. Functions allow you to write code that can be reused in different situations; code that is much easier to maintain; code that you can abstract and give it a simple name so that you can forget about routine details and do the really important things. You will see that functions not only open the door to programming prowess, but also play a key role in JavaScript programming style. In this chapter, we'll start with the basics, the mechanics and all the intricacies of how functions work, and then throughout the rest of the book, we'll improve your function skills. So let's start with the basics ... right now.

tidying up data

JavaScript can work with more than just numbers, strings, and booleans. Until now, we have worked exclusively with primitives - simple strings, numbers and booleans (for example, "Fido", 23 and true). There is a lot you can do with primitive types, but at some point you will need extended data to represent all items in a shopping cart, all songs in a playlist, a group of stars and their magnitudes, or an entire catalog of products. Such tasks require more serious funds. A typical tool for representing such homogeneous data is a JavaScript array. In this chapter, you will learn how to put data into an array, transfer it and work with it. In subsequent chapters, we will look at other ways to structure data, but we'll start with arrays.

Trip to Objectville

meet: objects

Until now, we have used primitives and arrays. And it applied a procedural programming methodology with simple commands, conditions, for / while loops and functions. This approach was far from the principles of object-oriented programming. Actually, it had nothing to do with object-oriented programming at all. We've used objects from time to time (and you didn't even know about it), but we haven't written any of our own objects yet. It's time to leave the boring procedural city and start creating your own objects.
In this chapter, you will learn why objects greatly improve our lives - at least in the field of programming. Just know this: once you get used to objects, you don't want to go back. Yes, and don't forget to send a postcard when you settle down.

DOM model

interacting with a web page

You are well on your way to learning JavaScript. In fact, you from a beginner in the field of script programming have become ... a programmer. Something is missing though: to fully utilize your JavaScript skills, you need to be able to interact with the web page in which
your code is located. Only then will you be able to write dynamic pages that respond to user actions and update after loading. How to interact with the page? Through the Document Object Model (DOM). In this chapter, we will look at the DOM and general principles of working with this model from JavaScript to extend the capabilities of the page.

Serious types

types, equality, conversions and all that

Now is the time to seriously talk about types. One of the great things about JavaScript is that a beginner can get far enough without going into the details of the language. But to really master the language, get a promotion, and do what is really worth doing, you need to be good at types. Remember what we said about JavaScript — that it didn't have the luxury of a peer-reviewed academic definition? Yes, that's true, but the lack of an academic foundation did not stop Steve Jobs and Bill Gates; it didn't interfere with JavaScript either. This means that JavaScript's type system is ... well, let's just say it's not the most sophisticated, and there are a lot of oddities in it. But don’t worry, in this chapter we’ll break it down, and soon you will learn safely
get around all these annoying things with types.

Building the application

together

Get your tools ready for use. Yes, your toolbox is your new programming skills, your knowledge of the DOM, and even some knowledge of HTML and CSS. In this chapter, we'll put it all together to create our first fully fledged web application. Quite primitive games with one ship placed on one line. In this chapter, we will build the full version: a large playing field, several ships, user input directly on the web page. We will create the structure of the game page in HTML markup, apply visual styling with CSS, and write JavaScript code that defines the game's behavior. Prepare yourself: in this chapter we will get into full-fledged, serious programming and write some serious code.

Event handling

asynchronous programming

In this chapter, you have to rise to a whole new level. So far, we've written code that typically runs from top to bottom. Of course, it used functions, objects, and methods, but execution followed a pre-planned track. It's a shame that we have to report such news in the second half of the book, but this code structure is not typical for JavaScript. Most JavaScript code is written to handle events. What events? Yes, any. A user clicks on a page, data comes from the web, a timer goes off in the browser, changes take place in the DOM ... This is not a complete list. Moreover, events are constantly occurring in the browser, which mostly go unnoticed. In this chapter, we will revisit our approach to programming and find out why you need to write code that responds to events.

Unlimited functions

first-class features

Explore the features and shine. In every craft, art, and discipline, there is a key principle that differentiates mid-level players from the true pro — and when it comes to JavaScript, a good grasp of function is a hallmark of professionalism. Functions play a fundamental role in JavaScript, and many of the techniques used in designing and organizing code are based on a good knowledge of functions and the ability to use them. Way of learning functions on this
the level is fun and challenging, so get ready ... This chapter is a bit like a tour of Willy Wonka's chocolate factory - as you explore JavaScript functions, you'll see a lot of weird, crazy, and wonderful things.

Serious functions

anonymous functions, scope and closures

We've learned a lot about functions, but that's not all. In this chapter, we will go further and understand the topics that professionals usually deal with. You will learn to work really effectively with functions. The chapter won't be too long, but it will be pretty intense, so by the end of the chapter, the expressiveness of your JavaScript code will surpass all expectations. You will also be ready to take on a colleague's code review or study javaScript libraries open source, because we'll explore some of the common idioms and conventions associated with the use of functions along the way. And if you've never heard of anonymous functions and closures, this is the perfect place to meet!

Object creation

non-trivial object creation

Until now, we have created objects manually. For each object, an object literal was used, which set all properties without exception. For small programs this is acceptable, but for
serious code will need something better, namely object constructors. Constructors make it easy to create objects, and you can create objects from a single pattern — in other words, constructors allow you to create a series of objects that have the same properties and contain the same methods. Code written using constructors is much more compact and reduces the risk of errors when creating a large number of objects. We assure you that after studying this chapter, you will use constructors as if you have been doing this all your conscious life.

Strong objects

using prototypes

Learning to create objects is just the beginning. It's time to pump up the muscle - explore advanced means of defining relationships between objects and organize code sharing. In addition, we need mechanisms for expanding existing objects. In other words, we need
expand your toolkit for working with objects. In this chapter, you will see that JavaScript implements a fairly powerful object model, but it differs slightly from the model of traditional object-oriented languages. Instead of typical class-based object-oriented systems, JavaScript uses the prototype model - objects that can inherit and extend the behavior of other objects. What is the benefit to you? You will soon find out. So, let's get started ...

Download from free file storage

Resolve the captcha to access the links!

You always want to get comprehensive knowledge in the field with which you work. JavaScript is one of the languages \u200b\u200babout which it is almost impossible to get comprehensive knowledge. It is constantly evolving, just like the web in general, so any web developer should strive to keep up with this development, and even more so he must know by heart the basics of the technology that he uses.

JavaScript now dominates the IT world. With it, you can either create a small web application or program a robot. Fortunately, the language has been around for a long time, and the developers who mastered it in superiority described their programming experience in it in books.

This book tells you how to get computers to do what you want them to do. Computers are as ubiquitous as screwdrivers today - but they have much more hidden complexity and are therefore harder to understand and harder to work with. For many, they remain alien, slightly threatening things. The book is also available in Russian.

This book provides a thorough overview of the world of JavaScript through parsing the built-in objects and nuances of the language. This book is definitely not intended for people just starting out with programming in general and JavaScript in particular.

This book explores both classic and modern JavaScript programming patterns. In general, it is aimed at novice programmers.

HTML5 is great. Just like jQuery. Like Node.JS. Add a little more pure JavaScript to them and you can easily conquer the web.

This book is intended for those planning to create web applications using JS. It describes the features of the language, useful tools, templates, and the list is not limited to this.

This book will give you a versatile knowledge of JavaScript, an understanding of both its general logic and details. The author assumes that the reader is already familiar with the principles of object-oriented programming and some language like PHP, Ruby, Python, C ++ or Java.

Are you ready to take your web programming practice a step further and move from HTML and CSS layout to full-fledged dynamic pages? Then it's time to get to know the "hottest" programming language - JavaScript!

After reading this book, you will learn everything about JavaScript, from variables to loops. You will understand why different browsers react differently to code and how to write universal code that is supported by all browsers. You will understand why JS is the future and become a true front-end developer.

This book shows you how to write front-end applications in JS without using any third-party frameworks or libraries.

In addition to a general knowledge of JavaScript principles, this book will also give you knowledge from related fields, such as JSON or NoSQL, as well as an understanding of how web applications are generally written.

As the title suggests, this book is about developing single page applications. It does not describe specific technologies and frameworks, but it does a good job of describing general patterns and practices.

The book is devoted to working with the DOM (Document Object Model) - perhaps the most important in JavaScript for all web developers.

This book, written by Douglas Crockford, the creator of JSON and JSLint, is a classic in the JavaScript world and should be read by everyone. It covers the basics of an object-oriented approach and provides many examples, both good and bad. Of course, the author tells how to fix such "harmful" examples and how to avoid such mistakes.

This series, written by renowned teacher Kyle Simpson, consists of 6 books, each covering a different section of the language. The main advantage of these books is that they are short enough so that you will not have time to distract yourself. You can purchase the book "ES6 and Beyond" from this series in paper version in Russian.

JavaScript is the main tool for web developers to make web pages interactive, dynamic and achieve the best performance. This is a well-structured JavaScript tutorial that will allow you to quickly learn this not the easiest to learn, but very popular language. Much attention in the book is paid to jQuery library... There are also many examples and detailed assignments.

By reading The Comprehensive Guide, you can:

  • Make your site pages interactive.
  • Master latest version jQuery plugin UI.
  • Create user-friendly forms with automatic data validation and correction.
  • Apply AJAX technology.
  • Deepen your knowledge in the field and become a professional.

After learning the basics of layout, you will certainly want more interactivity and beauty, as well as more convenient ways of interaction of the site with the backend. Then JavaScript enters the arena along with the insanely popular jQuery framework. To start working with the book, you do not need any deep knowledge - you will get all of it from it. It demonstrates only the latest practices in the field of cross-browser compatibility and page optimization, and the presentation is in clear language with illustrative examples and illustrations.

A book that has already become a classic. Its latest edition covers HTML5 and ECMAScript 6, both of today's hottest technologies. It also adds new chapters on jQuery and server-side JavaScript. This guide is useful for both beginners and those who want to hone their JavaScript knowledge to perfection.

About the other books in the Head First series “The right tone for the inner liberated expert programmer hiding in each of us. An excellent guide to practical development strategies - my brain works without being distracted by annoying, outdated academic jargon. - Travis Kalanick, CEO of Uber "Remarkable clarity, humor and a fair amount of intelligence will make even a non-programmer take a positive look at problem solving." - Corey Doctorow, second editor, Boing Boing, science fiction writer "I feel like I read half a ton of books at once." - Ward Cunningham, inventor of the Wiki "This is one of the few books on programming that I consider irreplaceable (and I count ten books in this category, no more)." - David Gelernter, Professor of Computer Science, Yale University "I laughed, I cried, this book moved me." - Daniel Steinberg, Senior Editor at java.net "I can't think of better guides than Eric and Elizabeth." - Miko Matsumura, VP of Marketing at Hazelcast, Former Java Lead, Sun Microsystems “I am literally in love with this book. I even kissed her in front of my wife. " - Satish Kumar “Visual approach and sequencing is the best way to learn this stuff ...” - Danny Goodman, author of Dynamic HTML: The Definitive Guide help newbies create their first jQuery pages in a simple and accessible way. " - Lindsay Skouras, Lawyer and Self-Taught Programmer About the Other Head First Books “Obviously Eric and Elizabeth know their stuff. Internet technologies are becoming more sophisticated and creative web page creation is becoming more and more important. Elegant architecture is central to every chapter, each concept communicated with an equal dose of pragmatism and wit. " - Ken Goldstein, former director of Shop.com and author of This is Rage: A Novel of Silicon Valley and Other Madness “Learn HTML, XHTML, and CSS is a carefully crafted, modern guide to forward-thinking web page layout and presentation practices. Authors anticipate which points may cause confusion in the reader and explain them in a timely manner. The approach used, which is based on an abundance of illustrative examples and a sequence of presentation, is optimal for the reader: he will make small changes and observe the final effect in the browser, which will help to understand the purpose of each new element. " - Danny Goodman, author of Dynamic HTML: The Definitive Guide “Learning HTML, XHTML, and CSS from the start gives the reader the feeling that the entire learning process will be simple and fun. Mastering HTML with the right explanation is no more difficult than learning the basics of your native language, and the authors have done an excellent job of providing illustrative examples for each concept. " - Mike Davidson, President and CEO of Newsvine, Inc. “Instead of writing in the traditional textbook style, Programming for iPhone and iPad offers the reader a lively, engaging, and even enjoyable learning curve for iOS programming. The material is skillfully and efficiently selected: the book covers many key technologies, including Core Data, and even such important aspects as interface design. And where else can you read how UIWebView and UITextField converse by the fireplace? " - Sean Murphy, iOS Application Designer and Developer “The Programming for iPhone and iPad book explains the principles of iOS application development from the beginning. The major changes since the first edition relate to iOS 4, Xcode 4, and writing iPad apps. With step-by-step descriptions with a visual style of presentation, this book becomes a great tool for learning programming for the iPhone and iPad in all aspects, from the simplest to the non-trivial. " - Rich Rosen, programmer and co-author of the book Mac OS X for Unix Geeks LBC 32.988-02-018.1 UDC 004.43 F88 F88 E. Freeman, E. Robson. Learning JavaScript programming. - SPb .: Peter, 2015 .-- 640 p.: Ill. - (Series "Head First O'Reilly"). ISBN 978-5-496-01257-7 Are you ready to take a step forward in web programming and move from HTML and CSS layout to creating full-fledged dynamic pages? Then it's time to get to know the "hottest" programming language - JavaScript! With this book, you will learn everything about JavaScript, from variables to loops. You will understand why different browsers react differently to code and how to write universal code that is supported by all browsers. It will become clear to you why you never have to worry about page congestion and data transfer errors with JavaScript code. Don't be alarmed, even if you haven't written a single line of code before - thanks to the unique presentation format, this book will easily guide you along the entire learning path: from writing a simple script to creating complex web projects that will work in all modern browsers. A special feature of this publication is the unique way of presenting material, which sets the O'Reilly Head First series apart from the many boring books devoted to programming. 12+ (In accordance with Federal Law No. 436-FZ of December 29, 2010.) ББК 32.988-02-018.1 UDC 004.43 The rights to the publication were obtained by agreement with O'Reilly. All rights reserved. No part of this book may be reproduced in any form whatsoever without the written permission of the copyright holders. ISBN 978-1449340131 English. ISBN 978-5-496-01257-7 © Authorized Russian translation of the English edition of Head First JavaScript Programming, 1st Edition (ISBN 9781449340131) © 2014 Eric Freeman, Elisabeth Robson. This translation is published and sold by permission of O'Reilly Media, Inc., which owns or controls all rights to publish and sell the same © Translated into Russian by Piter Publishing House LLC, 2015 © Russian edition, designed by Publishing House LLC Peter, 2015 Dedicated to JavaScript - you weren't born into a happy family, but you have surpassed all languages \u200b\u200bthat have tried to compete with you in browsers. by Elizabeth Robson Authors of the book Erik Freem Eric, in the words of one of the creators of the Head First series, is “one of the rare individuals who are well versed in the language, practice and culture of various fields - techno hipster, vice president, engineer, analyst. Eric spent almost ten years in a senior position as CTO of Disney Online & Disney.com at The Walt Disney Company. Eric is now giving his time to WickedlySmart, a young company he co-founded with Elizabeth. Eric is a computer scientist who did research with David Gelernter at Yale University. His dissertation was a fundamental work in the field of interfaces that implement the desktop metaphor, as well as the first implementation of activity flows, a concept he developed with Gelernter. In his spare time, Eric is seriously involved in music; Eric's latest project, Immersion Station, co-created with Steve Roach, can be found on the iPhone App Store. Eric lives with his wife and daughter on Bainbridge Island. His daughter often drops into Eric's music studio to play with synthesizers and audio effects generators. Email Eric at [email protected] or visit his website at http://ericfreeman.com. 8 Elizabeth is a programmer, writer and teacher. She has been in love with her job since her time at Yale University, where she earned her master's degree in computer technology. Elizabeth has long been involved with the Internet; she helped create the popular Ada Project, one of the first sites to help women find information about computer work and education. She co-founded WickedlySmart, a web-based Internet education firm. Here she creates books, articles, video courses, and more. As Director of Special Projects at O'Reilly, Elizabeth has developed workshops and distance learning courses. This is how her passion for creating educational courses that help people understand new technologies was demonstrated. Prior to joining O'Reilly, Elizabeth worked at The Walt Disney Company, where she led R&D for digital media technology. When Elizabeth is away from her computer, she goes hiking, cycling and rowing, or prepares vegetarian meals. You can write to Elizabeth at [email protected] wickedlysmart.com or visit her blog at http://elisabethrobson.com. table of contents Contents (summary) 1 2 3 4 5 6 7 8 9 10 11 12 13 Introduction First acquaintance with JavaScript. In unfamiliar waters Real code. Next step Familiarity with functions. Functions for all Organizing data. Arrays Meet Objects. Trip to Objectville Interacting with the web page. DOM Types, equality, conversions and all that. Serious types All together. Building an application Asynchronous programming. Event Handling First-class features. Unlimited Functions Anonymous Functions, Scope, and Closures. Serious functions Non-trivial object creation. Creating objects Using prototypes. Strong Objects 25 37 79 113 157 203 257 291 341 403 449 495 539 579 Contents (present) Introduction Your brain and JavaScript. You study - prepare for the exam. Or trying to master a difficult technical topic. Your brain is trying to do you a favor. He tries to make sure that this apparently irrelevant information does not waste precious resources. Better to spend them on something important. So how do you get him to learn JavaScript? Who This Book Is Written For We Know What You Are Thinking This Book Is For Those Who Want To Learn Metacognition: The Science Of Thinking 24 25 26 27 Here's What WE Did: What YOU Can Do To Make Your Brain Obey Note Science Editors Acknowledgments 28 29 30 33 34 9 table of contents 1 JavaScript offers fantastic opportunities in unfamiliar waters. JavaScript, the main programming language of the World Wide Web, allows you to define extended behavior in web pages. Forget about dry, boring, static pages that just take up screen space - with JavaScript you will interact with users, react to events, receive and use data from the Internet, display graphics ... and much, much more. With a good knowledge of JavaScript, you can even program completely new behaviors in your pages. And do not hesitate - your knowledge will be in demand. JavaScript is now not only one of the most popular programming languages, but is also supported by all modern (and many non-modern) browsers; moreover, there are built-in JavaScript implementations that exist separately from browsers. Enough talk, though. It's time to get down to business! CSS HTML The JS Browser 10 Getting Started with Javascript How JavaScript Works 38 How JavaScript Code is Written 39 How to Include JavaScript in a Page 40 JavaScript, you've come a long way, baby. .. 42 How Commands Are Created 46 Variables and Values \u200b\u200b47 Caution Keywords! 48 Be careful with expressions! 51 Executing Operations Over and Over 53 How a while Loop Works 54 Making Decisions in JavaScript 58 And When There Are LOTS of Decisions to Make ... 59 Engage the user in interacting with the page 61 Getting familiar with console.log 63 How to open the console 64 Writing a serious JavaScript application 65 How add code to page? (counting ways) 68 Markup and code: paths diverge 69 table of contents 2 real code Next step You already know what variables, types, expressions ... and so on. You already know a thing or two about JavaScript. Moreover, knowledge is enough to start writing real programs that do something interesting, which someone will use. True, you do not have enough hands-on experience in coding, and we will start solving this problem right now. How? Let's just start writing a simple game, fully implemented in JavaScript. The task is large-scale, but we will move towards the goal gradually, step by step. So, let's get down to business, and if you suddenly want to use our development in your projects, we do not mind, dispose of the code as you see fit. Preparation Receiving data from the user miss Checking the result hit the ship is sunk Mark: the ship is sunk Displaying the score / score Game over Mark: hit Let's implement the game "Sea battle" 80 First run ... 80 Let's start with the design 81 Parse the pseudocode 83 Stop! Remember HTML before you go any further! 85 Writing the code for a simplified version of "Sea Battle" 86 Moving on to the implementation of logic 87 How the prompt function works 89 Checking for a hit 90 Adding a hit check code 93 Outputting data after the game 94 Implementation of the logic is ready! 96 A little about quality control 97 Couldn't it be shorter ... 101 Simplified Battleship is almost ready 102 How to get a random position 103 The world famous recipe for generating random numbers 103 Back to quality control 105 Congratulations, you have created your first JavaScript program! Now a few words about code reuse 107 11 table of contents 3 12 introduction to functions Functions for everyone In this chapter, you will master your first superpower. You already know a thing or two about programming; it's time to take the next B step and master the functions. Functions allow you to write code that can be reused in different situations; code that is much easier to maintain; code that you can abstract and give it a simple name so that you can forget about routine details and do the really important things. You will see that functions not only open the door to programming prowess, but also play a key role in JavaScript programming style. In this chapter, we'll start with the basics, the mechanics and all the intricacies of how functions work, and then throughout the remainder of this book we'll improve your function skills. So let's start with the basics ... right now. So what's wrong with this code? 115 By the way, have you ever heard of FUNCTIONS? 117 Okay, but how does it all work? 118 What can be transferred to a function? 123 JavaScript uses pass-by-value 126 Experimenting with functions 128 Functions can also return values \u200b\u200b129 Stepping through a function with return 130 Global and local variables 133 Scope of local and global variables 135 The short life of variables 136 Don't forget to declare local variables! 137 table of contents 4 putting things in order Arrays 0 60 50 1 2 50 52 3 60 54 4 5 58 6 7 54 8 54 9 58 JavaScript can work with more than just numbers, strings, and booleans. Until now, we have worked exclusively with primitives - simple strings, numbers and booleans (for example, "Fido", 23 and true). There is a lot you can do with primitive types, but at some point you will need extended data to represent all items in a shopping cart, all songs in a playlist, a group of stars and their magnitudes, or an entire catalog of products. Such tasks require more serious funds. A typical tool for representing such homogeneous data is a JavaScript array. In this chapter, you will learn how to put data into an array, transfer it and work with it. In subsequent chapters, we will look at other ways to structure data, but we'll start with arrays. Can you help us? 158 How to represent a set of values \u200b\u200bin JavaScript 159 How arrays work 160 How many elements are there in an array? 162 Generator of Beautiful Phrases 164 Meanwhile, at Bubbles-R-Us ... 167 How to iterate over the elements of an array 170 But wait, there are more convenient way busting! 172 What, again? .. Couldn't it be shorter? 178 Refining the for loop with the postfix increment operator 179 Creating an empty array (and adding elements) 183 Here are our winners ... 187 Code Brief ... 189 Working on the printAndGetHighScore function 190 Refactoring the code with the printAndGetHighScore 191 Putting it all together ... 193 13 table of contents 5 14 Meet Objects A trip to Objectville So far, we have used primitives and arrays. And the methodology of procedural programming was applied with simple commands, conditions, for / while loops and functions. This approach was far from the principles of object-oriented programming. Actually, it had nothing to do with object-oriented programming at all. We've used objects from time to time (and you didn't even know about it), but we haven't written any of our own objects yet. It's time to leave the boring procedural city and start creating your own objects. In this chapter, you will learn why objects greatly improve our lives - at least in the field of programming. Just know this: once you get used to objects, you don't want to go back. Yes, and don't forget to send a postcard when you settle down. Someone said "objects" ?! 204 More about properties ... 205 How to create an object 207 What is "object-oriented approach"? 210 How properties work 211 How is an object stored in a variable? Curious minds are interested in ... 216 Comparing primitives with objects 217 Objects can do more ... 218 Preliminary check 219 Checking step by step 220 Let's talk a little more about passing objects to functions 222 Behave! And teach your objects ... 228 Improving the drive method 229 Why doesn't the drive method know about the started property? 232 How this works 234 How behavior affects state 240 State affects behavior 241 Congratulations on the first objects! 243 Imagine you are surrounded by solid objects! (and they make your job easier) 244 table of contents 6 interacting with a web page The DOM You are well on your way to learning JavaScript. In fact, you went from being a novice in script programming to ... a programmer. Something is missing though: To fully utilize your JavaScript skills, you need to be able to interact with the web page that contains your code. Only then will you be able to write dynamic pages that respond to user actions and update after loading. How to interact with the page? Through the Document Object Model (DOM). In this chapter, we will look at the DOM and the general principles of working with this model from JavaScript to extend the capabilities of the page. Hi, I'm a browser. I am reading a page and building a view of it in the DOM. In the previous chapter, we presented you with a "breaking the code" puzzle. 258 What does this code do? 259 How JavaScript actually interacts with the page 261 How to prepare the DOM 262 The DOM: First Impressions 263 Getting an Element with getElementById 268 What exactly do we get from the DOM? 269 \u200b\u200bIn Search of Internal HTML 270 What Happens When Changes Are Made to the DOM 272 And don’t try to execute my code before the page is loaded! 277 "Event Handler" or "Callback Function" 278 Setting an Attribute Using the setAttribute Method 283 Attribute Fun Continues! (attribute values \u200b\u200bcan be READ) 284 And don't forget that getElementById can return null too! 284 Every time you ask for a value, make sure you get what you asked for ... 284 What else can you do with the DOM? 286 document html head body p id \u003d ”greenplanet” p id \u003d ”redplanet” p id \u003d ”blueplanet” All is well Nothing to report All systems A-OK 15 table of contents 7 16 types, equality, conversions and all that Serious types It's time get serious about types. One of the great things about JavaScript is that a beginner can get far enough without going into the details of the language. But to really master the language, get a promotion, and do what is really worth doing, you need to be good at types. Remember what we said about JavaScript — that it didn't have the luxury of a peer-reviewed academic definition? Yes, that's true, but the lack of an academic foundation did not stop Steve Jobs and Bill Gates; it didn't interfere with JavaScript either. This means that JavaScript's type system is ... well, let's just say it's not the most sophisticated, and it has a lot of oddities. But don’t worry, we’ll break it down in this chapter, and soon you’ll learn how to safely bypass all these unpleasant moments with types. The truth is somewhere near ... 292 Be careful: undefined sometimes appears out of the blue ... 294 How to use null 297 Working with NaN 299 And then it's even more surprising 299 We must confess to you ... 301 The equality operator (also known as \u003d \u003d) 302 How operands are converted (everything is not as scary as it might seem) 303 How to check strict equality 306 Even more type conversions. .. 312 How to check two objects for equality 315 Pseudo-truth is somewhere nearby ... 317 What JavaScript considers "pseudo-truth" 318 The secret life of strings 320 A string can look like a primitive or an object 321 An overview of methods (and properties) of strings 323 Battle for the Chair 327 Table of Contents 8 Putting It All Together Building the Application Prepare your toolbox for work. Yes, your toolbox is your new programming skills, your knowledge of the DOM, and even some knowledge of HTML and CSS. In this chapter, we'll put it all together to create our first fully fledged web application. Quite primitive games with one ship placed on one line. In this chapter, we will build the full version: a large playing field, several ships, user input directly on the web page. We'll create the structure of the game page in HTML markup, apply visual styling with CSS, and write JavaScript to define the game's behavior. Prepare yourself: in this chapter we will get into full-fledged, serious programming and write some serious code. This time we will build a REAL Sea Battle game 342 Back to HTML and CSS 343 Creation hTML pages : The Big Picture 344 Styling 348 Using the Hit and Miss Classes 351 How to Design the Game 353 Implementing a View 355 How the displayMessage Method Works 355 How the DisplayHit and DisplayMiss Methods Work 357 Model 360 How We Will Represent the Ship Data 362 Implementing the Model Object 365 Preparing the Fire Method 366 Controller implementation 373 E Shot processing 374 F Code planning ... 375 BCD Ship 1 A Ship 2 Ship 3 G 0 1 2 3 4 HIT 5 6 Implementation of the parseGuess method 376 Counting and processing shots 379 How to link an event handler to the Fire button 383 Data transfer Controller 384 How to Place Ships 388 The generateShip Method 389 Generating the Starting Position of a New Ship 390 Completing the generateShip Method 391 17 Table of Contents 9 18 Asynchronous Programming Event Handling In this chapter, you take you to a whole new level. So far, we've written code that typically runs from top to bottom. Of course, it used functions, objects, and methods, but execution followed a pre-planned track. It is a pity that we have to report such news in the second half of the book, but this code structure is not typical for JavaScript. Most JavaScript code is written to handle events. What events? Yes, any. The user clicks on the page, the data comes from the network, the timer goes off in the browser, the DOM changes ... This is not a complete list. Moreover, events are constantly occurring in the browser, which mostly go unnoticed. In this chapter, we will revisit our approach to programming and find out why you need to write code that responds to events. What is an "event"? 405 What is an "event handler"? 406 How to Create the First Event Handler 407 Test Drive 408 How to Understand Events? Write a game, of course! 410 Implementing the Game 411 Test Drive 412 Adding Several Images 416 Now you need to assign one handler to all the onclick properties of all images 417 How to use one handler for all images 418 How the event object works 421 Working with the event object 423 Test drive: event object and source 424 Queues and Events 426 More Events 429 How setTimeout Works 430 Game Code Completion 434 Timer Test Drives 435 Table of Contents 10 First-class Features Unlimited Features Explore features and shine. In every craft, art, and discipline, there is a key principle that differentiates mid-level players from the true pro — and when it comes to JavaScript, a good grasp of function is a hallmark of professionalism. Functions play a fundamental role in JavaScript, and many of the techniques used in designing and organizing code are based on a good knowledge of functions and the ability to use them. The way to learn functions at this level is fun and challenging, so get ready ... This chapter is a bit like taking a tour of Willy Wonka's chocolate factory - as you learn JavaScript functions, you'll see a lot of weird, crazy, and wonderful things. The Double Life of the Function Keyword 450 Function Declarations and Function Expressions 451 Parsing a Function Declaration 452 What's Next? The browser executes the code 453 Moving forward ... Checking the condition 454 And finally ... 455 Functions as values \u200b\u200b459 Functions as full citizens JavaScript 462 First class flights 463 Writing code for processing and checking passengers 464 Enumerating passengers 466 Transferring a function to another function 467 Test- drive ... or rather, flight 467 Returning functions from functions 470 Drinks order code 471 Drinks order code: different approach 472 Wait, one drink is not enough! 473 Ordering drinks using a premium feature 474 Flight Test Drive 475 Web Cola 477 How the sort Array Method Works 479 Putting It All Together 480 Meanwhile in Web Cola 481 Sorting Test Drive 482 19 Table of Contents 11 Fuck! Judy is right again. 20 Anonymous Functions, Scope, and Closures Serious Functions We've learned a lot about functions, but that's not all. In this chapter, we'll go further and explore the topics that professionals usually do. You will learn to work really effectively with functions. The chapter won't be too long, but it will be pretty intense, so by the end of the chapter, the expressiveness of your JavaScript code will surpass all expectations. You will also be ready to take on a colleague's code or study the open source JavaScript library, because we will also explore some of the common idioms and conventions associated with using functions. And if you've never heard of anonymous functions and closures, this is the perfect place to meet! Wait a second ... Did Judy mention closures? They seem to have something to do with what we do. Let's study this topic and get even with it. Let's look at functions from the other side ... 496 How to use an anonymous function? 497 When is a function defined? There are options here ... 503 What happened? Why is the fly function not defined? 504 How nested functions are created 505 How nesting affects scope 506 Lexical scope in a nutshell 508 What is interesting about lexical scope 509 Functions again 511 Function calls (again) 512 What is "closure"? 515 How to close a function 516 Using closures to implement a counter 518 Test drive a magic counter 519 A look behind the scenes 519 Creating a closure with a function expression as an argument 521 A closure contains the immediate environment, not a copy of it 522 Creating a closure in an event handler 523 Program without a closure 524 A program with a closure 524 Test drive a hit counter 525 How closure works 526 table of contents 12 Non-trivial object creation Creating objects Until now, we created objects manually. For each object, we used an object literal that set all properties without exception. For small programs this is okay, but for serious code you need something better, namely object constructors. Constructors make it easy to create objects, and you can create objects from a single pattern — in other words, constructors allow you to create a series of objects that have the same properties and contain the same methods. Code written using constructors is much more compact and reduces the risk of errors when creating a large number of objects. We assure you that after studying this chapter, you will use constructors as if you have been doing this your entire adult life. Creating Objects Using Object Literals 540 About Similarities and Differences Between Objects 541 Constructors 543 How to Create a Constructor 544 How to Use a Constructor 545 How Constructors Work 546 You Can Also Add Methods to Constructors 548 Hazardous Area 551 Safety 551 Give Mass Production! 554 Test Drive on New Cars 556 Take Your Time with Object Literals 557 Argument Conversion to Object Literal 558 Car Constructor Conversion 559 Instances 561 Even Constructed Objects Can Have Independent Properties 564 Real World Constructors 566 Array Object 567 Other Built-in Objects 569 21 Table of Contents 13 Using Prototypes Powerful Objects Learning how to create objects is just the beginning. It's time to pump up your muscles - explore advanced tools for defining relationships between objects and organizing code sharing. In addition, we need mechanisms for expanding existing objects. In other words, we need to expand our toolkit for working with objects. In this chapter, you will see that JavaScript implements a fairly powerful object model, but it differs slightly from the model of traditional object-oriented languages. Instead of typical class-based object-oriented systems, JavaScript uses the prototype model - objects that can inherit and extend the behavior of other objects. What is the benefit to you? You will soon find out. So let's get started ... Object toString () hasOwnProperty () // and more 581 but how efficient is it? 582 Does duplicate methods really create problems? 584 What is a "prototype"? 585 Inheritance via prototype 586 How inheritance works 587 species: "Canine" Overriding the prototype 589 bark () run () wag () How to get a prototype 591 How to create a prototype 592 Dog Prototype Overriding an inherited method 594 About dynamic prototypes 598 More interesting implementation of the sit method 600 ShowDog Prototype Once again: how the sitting property works 601 league: “Webville” Where to start designing objects 605 Creating a prototype chain 607 How inheritance in a prototype chain works 608 stack () bait () gait () groom () ShowDog name: “Scotty” breed: “Scottish Terrier” weight: 15 handler: “Cookie” 22 Representing Objects in Diagrams Again about Constructors: Code Reused, Analyzing Results 617 Clean Up 618 A Little More Effort 619 Calling Dog.call Step by Step 620 Using Inheritance Usefully. .. extending the built-in object 626 Grand Unification Theory Total JavaScript 628 Objects for a Better Life 628 Putting It All Together 629 How to Use with this book Introduction I can't believe they included this in a book on JavaScript programming! ny to the urgent answer OE e K A el ed chili T Will they include cript in this r? " h S about a p v So on Ja and n va the question: “about the program in the book and how to work with this book For whom this book was written? If you answer yes to all of the following questions: 1 Do you have access to a computer with a modern browser and text editor? 2 Do you want to learn, remember, understand and learn how to program in JavaScript using development best practices and the latest standards? 3 Do you prefer lively conversation to dry, boring academic lectures? ... then this book is for you. By "modern browser" we mean an updated version of Safari, Chrome, Firefox or IE version 9 and above. [Note from Sales: This is actually a book for anyone with money.] Who isn't this book for? If you answer “yes” to any of the following questions: 1 Are you absolutely new to web programming? New to HTML and CSS? If so, your best bet is to start with Learn HTML, XHTML, and CSS, which teaches you how to create web pages before you tackle JavaScript. 2 Are you already an experienced web developer looking for a reference? 3 Are you afraid to try something new? Would you rather go to the dentist than wear a striped and checked one? Do you think that a book that depicts JavaScript objects in the form of men cannot be serious? ... this book is not for you. 24 introduction introduction We know what you're thinking "Are serious programming books like that?" "And why are there so many drawings here?" "Can you learn something like that?" Your mind thinks this is important. WE KNOW WHAT YOUR BRAIN Thinks The brain craves new experiences. He is constantly looking for, analyzing, expecting something unusual. It works like that, and it helps us survive. How does our brain deal with all the ordinary, everyday things? He tries with all his might to protect himself from them, so that they do not interfere with his real work - the preservation of what is really important. The brain does not consider it necessary to store boring information. It does not pass the "obviously irrelevant" filter. But how does the brain know what is important? Imagine that you are out for a walk and suddenly a tiger appears right in front of you. What's going on in your head and body? Neurons are activated. Emotions flare up. Chemical reactions take place. And then your brain understands ... Great. Another 613 dry, boring pages. Your brain doesn’t know that Eo doesn’t remember. Of course, this is important! Do not forget! click to wash. Now imagine that you are at home or in the library - in a warm, cozy place where tigers are not found. You study - prepare for the exam. Or you're trying to master a difficult technical topic that you've been allotted for a week ... ten days maximum. And then the problem arises: your brain is trying to do you a favor. He tries to make sure that this apparently irrelevant information does not waste precious resources. Better to spend them on something important. For tigers, for example. Or that it is better not to touch the fire. Or that you shouldn't ski in a T-shirt and shorts. There is no easy way to tell your brain: "Look, brain, I certainly am grateful to you, but no matter how boring this book is and even though my emotion sensor is now at zero, I want to remember what is written here." next� 25 how to work with this book teaches you This book is for those who want not to forget. to understand, but why is this about zhn well, and alem? First research how we learn something internally. According to the new article, there is no one who has more Fa, for assimilation Push psychology into the head is trained and we don’t know how tivistics, by the way on the page. We are for those in the field of cognition that we really need something more material is required Unlike other languages, work. JavaScript code is passed to force your brain st: py series Head Fir Basic Principles directly to the browser. text st, better than usual ka is remembered lou arm fo in Visibility. Graphi tia ia b raises efficiency and significantly increases, so the Crom web server (“Code found, get” research). , tion (up to 89% is shown in the figures still size. The tempers are getting more hungry, but from him to whom they thought that they had not studied) the presentation. Recently about formal lectures (in the heat of the material izl alesk R s t%. Ohm 40 t in the warm up is reached on the final test. You should be able to test the axis to improve the lecture. Not rel. I think that in order to read it eats at you, on the seventh of the year, please note: borrow JavaScript code What will attract yours too seriously. Should you place me? In the element ... at a table or a lecture, you will not get strained now that you are a reader. While you are, be beckoning. Active participation of tat nya Chi met on deoise and goals, nothing is more careful with your gyrus, in yours it should be. those; We should be interested in mastering the conclusions and ul rm fo, and to solve the exercises and for this, new knowledge is needed. involvement, in the solution of which and tricky questions. I'm a brain and different dudes are both hemispheres My playlist

Kick'n Tunes

BT - Satellite: nice downbeat tune.

Oh me. sit down! This reader's attention is fast-Attracting (and saving) oh, oh, I want to study this. I don’t need to change it for everyone: “I know by sight, the cirrtua in Syiot is paying attention to it! oh page ". The brain of deystzki countries but fall asleep on the first, unexpected. Oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooor boring. The interior does not have to be fast. The study is quicker. it is much quicker to recognize the ability to memorize how to do something. oh yyam. Known and Cared About Emotional Reminiscence. We have nothing to do with it: we are talking about it and it depends on the emotion we are doing here. No, sentim chu-what is so cool! " When deciding who is, We remember the teres and the feeling “D in, but I'm afraid, you’re surprised that you understand about such emotions as or when you understand, but expect to find the daunting tasks that surround of the Chechnical Department. Bob's knowledge of technology is everything, the topic is the best 26 introduction introduction Metacognition: the science of thinking If you really want to learn new knowledge faster and deeper - think about how you think. Learn to learn. Few of us study the theory of metacognition while studying. We are supposed to learn, but we are rarely taught this. How can I get my brain to remember all this now .... But since you're reading this book, you probably want to learn how to write JavaScript programs, and as quickly as possible. You want to remember what you read, and for that it is absolutely necessary to first understand what you read. To get the most out of your learning process, you need to get your brain to perceive the new material as Something Important. Critical to your existence. As important as the tiger. Otherwise, you will have an endless struggle with your brain, which by all means avoids memorizing new information. So how can you CONVINCE your brain that JavaScript programming is as important as the tiger? There is a slow and boring way, and there is a fast and efficient one. The first is based on blunt repetition. Everyone knows that even the most boring information can be remembered if you repeat it over and over again. With a sufficient number of repetitions, your brain estimates: "It seems to be unimportant, but once the same thing is repeated so many times ... Okay, I persuaded." The fast way is based on increasing brain activity and especially a combination of its different types. All of the factors listed on the previous page have been proven to help your brain work for you. For example, research has shown that placing words inside pictures (and not in captions, body text, etc.) forces the brain to analyze the connections between text and graphics, which leads to more neurons firing. More neurons - the higher the likelihood that the information will be considered important and worth remembering. Conversation style is also important: usually people show more attention when they participate in a conversation, as they have to follow the conversation and give their opinions. Moreover, the brain is not at all interested in what you are "talking" to the book! On the other hand, if the text is dry and formal, then the brain feels the same as you feel in a boring lecture as a passive participant. He is drowsy. But drawings and conversational style are just the beginning. next� 27 how to work with this book Here's what WE did: We used pictures because the brain perceives graphics better than text. From the point of view of the brain, a picture is worth 1,024 words. And when text is combined with graphics, we embed the text directly into the drawings, so the brain works more efficiently. We use redundancy: repeating the same thing several times, using different media, addressing different feelings - all to increase the likelihood that material will be encoded in several areas of your brain. Dog Prototype species: "Canine" bark () run () wag () ShowDog Prototype league: “Webville” stack () bait () gait () groom () ShowDog name: “Scotty” breed: “Scottish Terrier” weight: 15 handler: “Cookie” We use concepts and pictures in a somewhat unexpected way because the brain is better at picking up new information. In addition, drawings and ideas usually have emotional content because the brain pays attention to the biochemistry of emotions. What makes us feel is better remembered - be it a joke, surprise, or interest. We use a conversational style because the brain picks up information better when you participate in a conversation, rather than passively listening to a lecture. This also happens when reading. Numerous exercises are included in the book because the brain remembers better when you are doing something. We tried to make them challenging, but interesting - something that most readers prefer. We have combined several learning styles, because some readers prefer step-by-step descriptions, others tend to first present the "big picture", and the third is enough with a piece of code. Regardless of your personal preference, it is helpful to see multiple presentation options for the same story. We have tried to engage both hemispheres of your brain; this increases the likelihood of learning the material. While one side of the brain is working, the other is often able to rest; this increases the effectiveness of training over time. It also includes stories and exercises that reflect other points of view. The brain assimilates information more deeply when it has to evaluate and make judgments. There are often questions in the book that cannot always be answered easily, because the brain learns faster and remembers when it has to do something. You can't build muscle by watching others do. However, we will make sure that the readers' efforts are put in the right direction. You don’t have to puzzle over unintelligible examples or navigate false, oversaturated technical jargon, or overly concise text. There are people in stories, examples, pictures - because you are also human. And your brain pays more attention to people than to inanimate objects. We use the 80/20 principle. If you're going to be a cool JavaScript developer, this is the only book you will need. In it, we are not trying to talk about everything - only about what is really necessary. 28 introduction BECOME a browser KEY POINTS Puzzles introduction What YOU can do to make your brain obey We're done. The rest is up to you. These tips will be the starting point; listen to your brain and determine what works for you and what doesn't. Try new things. Cut and attach to the fridge. 1 Take your time. The more you understand, the less you have to memorize. 6 Just reading is not enough. When a book asks you a question, don't jump to the answer. Imagine someone is actually asking you a question. The deeper your brain thinks, the sooner you will understand and remember the material. 7 2 Exercise, take notes. We have included the exercises in the book, but we are not going to do them for you. And don't look at the exercises. Take a pencil and write. Physical activity during exercise increases its effectiveness. 3 Read the sidebars. 4 Do not read other books, put this one off before bed. 5 Drink water. And more. The brain works best in high humidity environments. Dehydration (which may occur before you even feel thirsty) decreases cognitive function. Speech activates other parts of the brain. If you're trying to understand or remember something better, say it out loud. Better yet, try explaining to someone else. You will learn the material faster and, possibly, discover something new for yourself. Listen to your brain. Watch for when your brain starts to fatigue. If you start to perceive material superficially or forget what you just read, it's time to take a break. 8 Feel! 9 Be creative! This means: read everything. Sidebars are part of the main material! Don't miss them. Some of the learning (especially the transfer of information into long-term memory) happens after you close the book. Your brain doesn't immediately process information. If new information arrives during processing, some of what you learned earlier may be lost. Speak out loud. Your brain needs to know that the material in the book really matters. Experience the heroes of our stories. Create your own photo captions. Grimacing at a bad joke is still better than feeling nothing. Try to apply new knowledge in your daily work. Just do something to gain practical experience outside of the exercises. All it takes is a pencil and a suitable task ... A task where JavaScript can be beneficial. 10 Sleep. To learn to program, you have to create many new connections in your brain. Sleep more often is helpful. next� 29 how to work with this book Please note This is a tutorial, not a reference. We have deliberately removed from the book anything that could interfere with the study of the material you are working on. And when you first read a book, you should start from the very beginning, because the book assumes that the reader has certain knowledge and experience. We describe the GOOD sides of JavaScript and warn about the BAD sides. The JavaScript programming language was not born in academia and did not go through the stage of enlightened peer review. He came to this world out of necessity and grew up in the harsh environment of early browsers. A word of warning: JavaScript has many advantages, but there are other, not so great, aspects. But overall JavaScript is a great language for those who know how to use it intelligently. In this book, we will teach you how to use the good sides effectively, as well as point out possible pitfalls and advice on how best to work around them. We are not trying to describe in every detail all aspects of the language. JavaScript is a pretty broad topic. This book should not be viewed as a reference; this is a tutorial that doesn't cover everything there is to learn about JavaScript. We want to teach you the basics of JavaScript so that you can take any old reference and do whatever you want in JavaScript. This book teaches the use of JavaScript in browsers. The browser is not only the most common environment for executing JavaScript code, but also the most convenient (everyone has a computer with a text editor and a browser, and you don't need anything else to get started with JavaScript). Running JavaScript in the browser also means instant response; to see how the code you've written works, just reload the web page. The book encourages writing well-structured, readable code. The code should be written in a way that is easy to read and understandable for other people, and also work in browsers that will be released next year. It should be as simple and straightforward as possible so that you can cope with your task and can move on to other matters. In this book, we'll teach you how to write simple, well-structured code that can adapt to future changes — code you can be proud of, framed and hung on the wall. We recommend using different browsers. We teach you to write standards-based JavaScript, and yet you are likely to run into subtle differences in how JavaScript is interpreted by different browsers. While we have made sure that the provided code works in all modern browsers, and even show a couple of tricks to ensure that the code is supported by these browsers, we recommend that you choose a couple of browsers and test your JavaScript code in them. This will teach you how to see the differences between browsers and how to write JavaScript code that works well across browsers with consistent results. 30 introduction introduction Programming is serious business. You will have to work, sometimes very hard. If you already have practical programming experience, then you know what we are talking about. If you took up this book after Learning HTML, XHTML, and CSS, please note that the code you will need to write here looks ... a little different. Programming requires a special mindset. It is logical, sometimes extremely abstract and algorithmic. Don't worry, we'll try to make the learning process as enjoyable as possible for your brain. Move gradually, eat well, and get more sleep, and the new concepts will fit in your head. Exercises are MANDATORY. The exercises are part of the main body of the book. Some exercises help to memorize the material, others help to better understand it, and still others are focused on its practical application. Don't skip exercise. Repetition is intentional. The books in this series have one fundamental feature: we want you to really understand the material well. And so that you remember everything that you have learned. Most reference books do not aim at successful memorization, but this is not a reference book, but a textbook, so some concepts are presented in the book several times. The examples have been kept as compact as possible. Our readers don't like to go through 200 lines of code in the examples to find two really important lines. Most of the examples in the book are given in the least possible context so that the part you are studying is simple and clear. Don't expect all the examples to be well-debugged or written to the end - they are made for educational purposes and do not always have full functionality. All sample files are available on the Internet. You can find them at http://wickedlysmart.com/hfjs. Mind Games have no answers. In some of them there is no correct answer at all, in others you must decide for yourself how correct your answers are (this is part of the learning process). Some of the Mind Games exercises provide tips to help you find the right direction. next� 31 how to work with this book We often only include code without markup. After the first couple of chapters, we often present only JavaScript code, assuming it is packaged in HTML markup. Below is a simple HTML page that can be used with most of the book's code. If different HTML markup needs to be used somewhere, we will tell you about it: Your HTML Page All content on the web page is hosted here. Do not worry; we will explain everything at the beginning of the book. Code Samples, Support, and Discussions All necessary supporting materials are available at http://wickedlysmart.com/hfjs. Here are some code examples and additional material, including videos. 32 introduction introduction These guys are great; they stayed with us throughout the review process and shared invaluable details about everything! Academic Editors Ro f St Jeff Ismael Martin Bing Demiddel Frank D. Moore Alfred J. Speller Bruce Forkush Jav e Ruedas Thank you to all of our amazing peer review team! This book has gone through more thorough peer review than any of our previous books. More than 270 people who have joined our WickedlySmart Insiders program participated in proofreading and quick critical review of the book as it was written. The system worked better than we expected and influenced almost every aspect of the book. We express our sincere gratitude to all participants; thanks to you the book is much better than it could have been. The scientific editors pictured above provided particularly valuable insights and significant contributions to the work of the book. In addition to them, we were assisted by: Galina Orlova, J. Patrick Kelly, Klaus-Peter Kahl, Rob Cleary, Rebecca Dunn-Crane, Olaf Schenrich, Jim Kopeck, Matthew M. Hanrahan, Russell Allin-Willems, Christine J. Wilson, Louis-Philippe Breton, Timo Glazer, Sharmen Gray, Lee Beckham, Michael Murphy, Dave Young, Don Smallwich, Alan Rusyak, Eric R. Lisinski, Brent Fazekas, Sue Starr, Eric (Orange Pants) Johnson, Jess Palmer, Manabu Kawakami, Alan MacIvor, Alex Kelly, Yvonne Bixel Truon, Austin Trape, Tim Williams, J. Albert Bowden II, Rod Shelton, Nancy DeHaven Hall, Sue McGee, Francisco Debs, Miriam Berkland, Christine Grecco, Elhaji Barry, Athanasios Valsamakis, and Peter Caseyolsey Robb Kerry. next� 33 peer review group Acknowledgments * Dear David Powers We are also extremely grateful to our distinguished Science Editor, David Powers. In truth, we don't write without David's input at all - he too often saved us from possible trouble. David helps us (or rather, forces us) to make the book more meaningful and technically accurate, and his second profession as an amateur comedian turns out to be useful when we write frivolous parts of the book. Thanks again, David - you are a true professional, and we sleep more peacefully at night, knowing that the book has passed your technical control. To O'Reilly: A huge, huge thank you to our editor Megan Blanchett, who cleared the way for this book. Don't let this smile fool you, mislead you, this man is an obstacle, a patient professional. She waited and sacrificed family leisure for the sake of its completion. It also helps us stay sane in our relationship with O'Reilly (and O'Reilly in their relationship with us). We adore you and will not wait for the next joint project! Megan Blanchett Another warm greetings to our editor-in-chief Mike Hendrickson, who has been actively promoting this book from the beginning. Thanks Mike; none of our books would have been published without your participation. You have been our leader for over ten years, and we love you! * A large number of thanks can be easily explained: we are testing the theory that everyone mentioned in the thanks section will buy at least one copy of the book (and maybe more) for relatives and friends. If you want us to thank you in our next book, and you have a big family, write. 34 introduction Mike Hendrickson introduction To the O'Reilly members: We sincerely thank the entire O'Reilly group: Melanie Yarbrough, Bob Pfaler and Dan Foxmith, who have shaped this book; To Ed Stevenson, Hughett Barrier and Leslie Crandell, who led marketing, we appreciated their unconventional approach to business. Thanks to Ellie Volkhakusen, Randy Kamera and Karen Montgomery for the stylish cover design that continues to serve us. As usual, thanks to Rachel Monahan for her uncompromising editing (and how she encouraged us) and Bert Bates for extremely helpful feedback. next� 35 1 first acquaintance with javascript In unfamiliar waters Get in, the water is great! We'll take a quick tour of JavaScript, write the first code, run it, and see how it runs in the browser! JavaScript offers fantastic opportunities. JavaScript, the main programming language of the World Wide Web, allows you to define extended behavior in web pages. Forget about dry, boring, static pages that just take up screen space - with JavaScript you will interact with users, react to events, receive and use data from the Internet, display graphics ... and much, much more. With a good knowledge of JavaScript, you can even program completely new behaviors in your pages. And do not hesitate - your knowledge will be in demand. JavaScript is now not only one of the most popular programming languages, but is also supported by all modern (and many non-modern) browsers; moreover, there are built-in JavaScript implementations that exist separately from browsers. Enough talk, though. It's time to get down to business! how javascript works How JavaScript works You have mastered the creation of structure, content, layout and style of web pages. Isn't it time to add behavior to them? Nowadays, a page that can only be viewed is not interesting to anyone. Good pages need to be dynamic and interactive, and they need to interact with users in new ways. This is what JavaScript is for. First, let's take a look at how JavaScript fits into the ecosystem of web pages: HTML You already know that HTML (Hypertext Markup Language) is used to define the content of pages, as well as their structure: paragraphs, headings, and sections. JS 38 Chapter 1 The CSS Browser You know that Cascading Style Sheets (Cascading Style Sheets) technology is used to display HTML markup — colors, fonts, borders, page layout ... CSS defines a layout style separate from the page structure. So, meet: JavaScript, a cousin of HTML and CSS. JavaScript can define the behavior of web pages. Need to react when the user clicks the "Sale ends in 30 seconds!" Button? Quickly check the contents of a textbox with important data? Download messages from Twitter and display them on the page? Or maybe you want to play? JavaScript comes to the rescue. You can add program code to the page that will perform calculations, respond to events, draw, transmit data, signal, update information, change ... In a word, any dynamic operations - all this JavaScript can do. first acquaintance with javascript How JavaScript is written JavaScript has a special place in the programming world. How does a typical classic program come about? You write code, compile it, link it, and install it on your computer. JavaScript is much more flexible and dynamic. The programmer includes JavaScript code directly into the page, and then loads it into the browser. Next, the browser itself will do everything necessary to execute the written code. Let's take a closer look at how this scheme works: CSS Icecream

Icecream flavors

49 flavors

All your favorite flavors!

Writing the Code 1 The page is created as usual with HTML content and CSS styling. JavaScript code is added to the page. As you will see shortly, by analogy with HTML and CSS, all components can be placed in one file, or the JavaScript code can be separated into a separate file that is included in the page. We will soon figure out which method is better ... Browser Browser Loading Execution 2 Open the page in the browser. Having found JavaScript code in the page, the browser immediately begins to parse it and prepare it for execution. As with HTML and CSS, if the browser detects errors in JavaScript, it tries to continue reading JavaScript, HTML and CSS. The browser tries to avoid a situation in which the user cannot see the requested page. For the future: the browser builds an "object model" of an HTML page that can be used by JavaScript code. Just remember this fact, we will not come back to it ... 3 The browser starts executing the code as soon as it encounters it, and continues to execute it throughout the page's life cycle. Unlike earlier versions, modern JavaScript is highly efficient, and thanks to sophisticated compilation techniques, the code is almost as fast as traditional programming languages. html head title body script h1 h2 p em on 4 39 embedding javascript in a page How to embed JavaScript in a page Let's start at the beginning: to get advanced with JavaScript, you need to know how to embed code in a page. How is this done? Of course, using the element It writes a piece of JavaScript code.

Just a generic heading

Once again, it doesn't matter for us now how this code works. And yet ... Look at it and guess what happens on each of the lines.

Not a lot to read about here. I "m just an obligatory paragraph living in an example in a JavaScript book. I" m looking for something to make my life more exciting.

Test Drive Enter the page code and save it in a file named “behavior.html”. Now load the page in the browser (drag the file into the browser window or use the File\u003e Open command). What does our code do? Hint: you need to wait five seconds to figure this out. 40 chapter 1 getting started with javascript RELAX Are we building code that can be used elsewhere and name it "wakeUpUser"? SLE Just don't worry. No one expects you to immediately begin to understand JavaScript as if you knew it from childhood. For now, it's enough to imagine what JavaScript is like. Relaxing is also not worth it: you need your brain to work in full force. Remember the code from the previous page? Let's try to guess what is happening on each line: -What way of counting setTimeout (wakeUpUser, 5000); How long is it in here? Hint: heel ounda. function wakeUpUser () (1000 milliseconds \u003d 1 sec) alert ("Are you going to stare at this boring page forever?"); Everything is clear here: a message is displayed for the user. Frequently Q: Asking Questions Q: A: I've heard that JavaScript is called a "toy language." It's true? A friend of mine works with JavaScript in Photoshop ... or so he says. Is it possible? At first, JavaScript was not very powerful, but then its importance increased, and significant resources (including the minds of the best specialists) were devoted to expanding the capabilities of JavaScript. But you know what? Even before JavaScript was so fast, it was great. And as you will soon see, you can do a lot with it. Yes, JavaScript is a universal scripting language and has infiltrated many applications, from graphics editors to music programs , and even into the field of server programming. A: Q: A: Is JavaScript somehow related to Java? Name only. JavaScript was created at the height of Java's popularity, and JavaScript developers have taken advantage of this fact. Both languages \u200b\u200bborrow some syntax from the C languages, but otherwise have little in common. Q: So JavaScript is the best way to create dynamic pages? What about Flash based solutions? A: There was a time when Flash was considered the preferred technology for creating interactive and more dynamic web pages, but since then the industry has clearly begun to move to HTML5 with JavaScript. And in HTML5, JavaScript is now the standard scripting language for web programming. Significant efforts and funds are now being spent on improving the speed and efficiency of JavaScript, as well as on creating JavaScript APIs that extend the functionality of the browser. Q: You say that many other languages \u200b\u200bare compiled. What is it and why isn't it in JavaScript? A: In traditional programming languages \u200b\u200b- C, C ++, or Java - the code is compiled before being executed. During compilation, the code is converted to a machine-readable representation (and usually optimized for execution speed). Scripting languages \u200b\u200bare interpreted, meaning the browser executes each line of JavaScript as soon as it encounters it. For scripting languages, runtime performance is not that important; they are more focused on prototyping, interactive programming with maximum flexibility. This was the case with early versions of JavaScript, for this reason, for many years, the code execution speed was rather mediocre. However, there was an intermediate option: an interpreted language that was compiled on the fly. It was he who was chosen by the browser developers for modern JavaScript implementations. Basically, in JavaScript, you take advantage of all the conveniences of a scripting language combined with the speed of a compiled language. Incidentally, the words interpret, calculate, and execute are common throughout this book. They may differ in meaning in different contexts, but for our purposes, they are actually equivalent. next 4 41 history of javascript JavaScript, you've come a long way, baby ... JavaScript 1.0 You may not remember Netscape, but it was the first real browser developer. In the mid-1990s, there was a fierce battle in the market (especially from Microsoft), and adding exciting new features to the browser was extremely important. To do this, Netscape created a scripting language that allowed anyone to include scripting code on a page. This is how LiveScript was born. Chances are, you've never heard of LiveScript because at the same time Sun Microsystems introduced the Java language, and its stock has skyrocketed. Why not take advantage of someone else's success? This is how LiveScript became JavaScript. Do these languages \u200b\u200bhave nothing in common? So what ... What about Microsoft? Soon after Netscape, she created her own scripting language called ... JScript. It was somehow suspiciously similar to JavaScript. This is how the browser wars began. 1995 42 Chapter 1 JavaScript 1.3 Between 1996 and 2000, JavaScript continued to evolve. Netscape contributed JavaScript for standardization; this is how ECMAScript was born. Haven't heard of ECMAScript? Just know that it is the default language definition for all JavaScript implementations (in and out of browsers). During this time, developers continued to struggle with JavaScript (browser wars were in full swing), although the use of JavaScript was becoming more common. While the subtle differences between JavaScript and JScript continued to plague the lives of developers, the two languages \u200b\u200bbecame more and more similar over time. JavaScript still enjoyed a reputation as a "language for amateurs", but soon everything changed ... 2000 JavaScript 1.8.5 Finally, JavaScript has matured and earned the recognition of professional developers! While some might argue that it's all about the emergence of a reliable standard (such as ECMAScript 5), which is now implemented in all modern browsers, in fact, Google contributed significantly to the entry of JavaScript into the professional arena. In 2005, Google Maps showed the world what JavaScript is capable of creating dynamic web pages. The best minds in the field of programming have worked to improve JavaScript interpreters and increase the speed of code execution. The syntax has changed little over the course of JavaScript's evolution in general. For all the fuss that went with its birth, JavaScript has proven to be a powerful and expressive language. 2012 first exposure to javascript Take a pencil in hand See how easy it is to write JavaScript var price \u003d 28.99; var discount \u003d 10; You don't know JavaScript yet, but you can probably at least roughly imagine how its code works. Take a look at each line and try to guess what it does. Write down your answers. We've provided one answer to help you get started. And if the task turns out to be overwhelming, the answers are given on the next page. Create a variable price and assign the value 28.99 to it. var total \u003d price - (price * (discount / 100)); if (total\u003e 25) (freeShipping ();) var count \u003d 10; while (count\u003e 0) (juggle (); count \u003d count - 1;) var dog \u003d (name: "Rover", weight: 35); if (dog.weight\u003e 30) (alert ("WOOF WOOF");) else (alert ("woof woof");) var circleRadius \u003d 20; var circleArea \u003d Math.PI * (circleRadius * circleRadius); Next 4 43 Solution to Exercise See how easy it is to write JavaScript var price \u003d 28.99; var discount \u003d 10; var total \u003d price - (price * (discount / 100)); if (total\u003e 25) (freeShipping ();) var count \u003d 10; while (count\u003e 0) (juggle (); count \u003d count - 1;) Pick up a pencil Solution You don't know JavaScript yet, but you can probably at least roughly guess how its code works. Take a look at each line and try to guess what it does. Write down your answers. We've provided one answer to help you get started. So the answers. Create a variable price and assign the value 28.99 to it. Create a variable discount and set it to 10. Calculate the discount price and set it to total. Compare the variable total and 25. If the variable is greater ... ... execute the freeShipping code snippet. End of if command Create variable count and assign value 10. While count remains greater than 0 ... ... do something, and then ... ... decrease count by 1. End of loop while Create variable dog with attributes name and weight. var dog \u003d (name: "Rover", weight: 35); if (dog.weight\u003e 30) (alert ("WOOF WOOF");) else (alert ("woof woof");) var circleRadius \u003d 20; var circleArea \u003d Math.PI * (circleRadius * circleRadius); 44 chapter 1 If the weight attribute is greater than 30 ... ... display the message “WOOF WOOF” on the web page, Otherwise ... ... display the message “woof woof” on the web page. End of the if / else command Create variable circleRadius and set it to 20. Create a variable named circleArea ... ... and assign the result of the expression (1256.6370614359173) a first glimpse of javascript If you don't want to limit yourself to regular static web pages, you can't do without JavaScript. And it is true. Pages built with HTML and CSS can look good. But once you learn JavaScript, you can build completely new flavors of pages. Moreover, it would be more correct to consider them not as ordinary pages, but as an application at the same time! and podzara What do you say? "Of course, I know this very well, otherwise why would I read this book?" We actually wanted to take this opportunity and talk a little about learning JavaScript. If you already have experience in any programming language or scripting language, then you have a rough idea of \u200b\u200bwhat awaits you. If until now you have limited yourself to HTML and CSS, know that something fundamentally new awaits you when learning a programming language. bot! In HTML and CSS, declarative operations are mainly performed. Let's say you declare that some paragraph text or all elements of the "sale" class should be colored red. JavaScript adds new behavior to the page, and for this you need to describe the calculations. You will need tools to describe the various operations: “calculate the player's score by adding the number of points”, or “repeat the next action ten times”, or “when the user clicks this button, play such and such a beep”, or even “go to Twitter, get the latest message and post it on this page. " The language required for such tasks is very different from HTML and CSS. Let's see what exactly ... next 4 45 javascript commands How commands are created When you create HTML content, you usually mark up the text by defining its structure; for this, elements, attributes and values \u200b\u200bare added to the text:

Mocha caffe latte

Espresso, steamed milk and chocolate syrup, just the way you like it.

When working with HTML, we mark up the text to define the structure: here we have an example, "Ok, here's a big heading, followed by a paragraph of regular text." CSS is a little different. The developer writes a set of rules; each rule selects page elements and then sets a set of styles for those elements: h1.drink () p () color: brown; with selectors For CSS, we write dividing rules, def p), and k drin (for example, h1. L apply HTM to which parts of the markup this section is applicable to. Let's say all drink headings are displayed in brown ... ... And paragraphs are displayed in font without serif font-family: sans-serif; JavaScript code consists of commands. Each command describes a small part of the operation to be performed, and the entire set of commands determines the behavior of the page: Command set.var age \u003d 25; var name \u003d "Owen"; if (age \u003e 14) (Each team does a small part of the work, such as declaring variables that will hold the values \u200b\u200bused. We create a variable to store the age (25). We also need a variable for the name “Owen.” The value of the variable can be used to make decisions . User's age is more than 14? Alert ("Sorry this page is for kids only!");) Else () alert ("Welcome" + name + "!"); 46 chapter 1 And if not, we greet the user by name (however , in our example, Owen is 25 years old, so the message is not displayed). If more - we inform that the user is too old for this page. Getting Started with javascript Variables and Values \u200b\u200bYou've probably noticed that variables are commonly used in JavaScript programs. Variables are meant to store values. Which ones? Let's look at a few examples: var name \u003d "Duke"; uk e ”isEligible is set to false. Variables if var isEligible \u003d false; Any two values, true and false (true / false), are called boolean (or boolean). “D winners A sequence of characters is assigned to a variable (this sequence is called a string). fal se var winners \u003d 2; The 2nd Team announces a move with and with the name winners. 2. No known catch name isEligible After mathematician George Boole. In addition to numbers, strings, and boolean values, variables can store other data. We'll get to them soon, but regardless of the type of data, all variables are created according to the same rules. Let's take a closer look at the variable declaration: A variable declaration always begins with the var keyword. Note: Boolean values \u200b\u200bare not quoted. NO EXCEPTIONS! Even if JavaScript doesn't complain that you missed var. You will soon see why ... Next comes the name of the variable. var winners \u003d 2; An assignment command always ends with a semicolon. Finally, if desired, you can specify the initial value of the variable; to do this, put an equal sign followed by a value. We say “if you want” because, strictly speaking, you can create a variable without an initial value and assign it later. To do this, just remove the assignment from the command: var losers; If a variable is declared without an equal sign and a value, then you are just going to use it somehow in the future. Doesn't matter? And how to live now ?! This is just humiliating. losers on 4 47 keywords javascript Beware, keywords! A variable has a name and a variable has a value. You also know that variables can store numbers, strings, and boolean values \u200b\u200b(and more). But how do you choose a variable name? Any name will do? No, but finding a valid name is easy. It is enough to make sure that the variable name does not violate two simple rules: 1 Variable names must begin with a letter, underscore, or dollar sign. 2 Letters, numbers, underscores, and dollar signs may follow - in any number. Oh, and one more thing: do not confuse JavaScript and use built-in keywords such as var, function, or false as variable names. These names also drop out of the list. In this book, we will also look at some keywords and figure out what they mean, but for now we will restrict ourselves to a short list: break delete for let super void case do function new switch while catch else if package this with class enum implements private throw yield const export import protected true continue extends in public try debugger false instanceof return typeof default finally interface static var often Q: A: What is a "keyword"? Keyword is one of the reserved words in the JavaScript language. JavaScript uses words like this for its own purposes. If you start using them as your variable names, you will only confuse your browser. 48 Chapter 1 Q: Questions to Ask What if a keyword is part of a variable name? For example, can I create a variable named ifOnly (that is, a variable that has the if keyword in its name)? Q: Of course you can. Only exact matches are prohibited. It is desirable that your code is simple and straightforward, therefore, using names like elze is also undesirable - they can be easily confused with else. Q: Is JavaScript case sensitive? In other words, are myvariable and MyVariable the same thing? A: If you've worked with HTML markup, you are most likely used to not being case sensitive; after all, for the browser the tag is no different from ... But JavaScript is case-sensitive in variable names, keywords, function names ... In short, almost everywhere. So be careful with upper and lower case! first acquaintance with javascript WEBVILLE T I M E S How to avoid annoying mistakes with names The choice of names is wide, therefore there are extremely two-headed names in the recommendation, we will give several How? Directly unsuccessful other law. whether JavaScript edema. from many adversaries start with capital letters: every word is used and although some of the names are: otw oH ea de dD ny, start Choose meaningful names. baty r reg str »rag on With Fi re. “We pride ourselves on _, we don’t reckon to the bulletins. Maybe the names _m have the advantage you don’t have to fall for it, if only they are very important for you, but, $ , r and foo mean something with nominative flexibility for rank (when and when they come, then they themselves will not be misunderstood by anyone. di my gle something that cu rrentPressure and passedExam do not blow and other shrink. Essentially - Be careful. We write it down with the time, but just do not forget it but “g, be careful about the registrar”, we are much more flexible and will make your distribution code the changed variables. Please feel free to choose them. (including back in the day, we did some JavaScript) Still Use “Hey, not just a little choice of names, but a little extra in the names from not scramble r r e r »Use names beginning with words only. just remember: knocking out with _ and $, only in Access, in special cases. Use clear names, but then you need to choose them farther from the key in Name words and the name of the variable is always referenced to the variable, for with $, usually cut, starting Name the other variables var when declaring them. b About syntax ƒƒ Each command ends with a “;” character. x \u003d x + 1; ƒƒ A single line comment begins with two forward slashes (//). Comments only contain information about the code for you and other developers. They are not executed in the program. // This is a comment ƒƒ Extra spaces are allowed (almost everywhere). x \u003d 2233; ƒƒ Strings must be enclosed in double quotes (or single quotes, but choose one - be consecutive). "You rule!" "And so do you!" ƒƒ Boolean values \u200b\u200btrue and false are written without quotes. rockin \u003d true; ƒƒ Variables do not need to be assigned a value when declared: var width; ƒƒ JavaScript, unlike HTML markup, is case sensitive. In other words, Counter and counter are different variables. next 4 49 syntax exercises BECOME a browser Below is the JavaScript code that contains errors. Imagine yourself in the shoes of a browser and try to find errors in your code. And when you're done, look at the answers at the end of the chapter and see if you're missing out on anything. A // Test for jokes var joke \u003d "JavaScript walked into a bar ...."; Don't worry about what this JavaScript snippet does for now; just try to find errors in variables and syntax. var toldJoke \u003d "false"; var $ punchline \u003d "Better watch out for those semi-colons." var% entage \u003d 20; var result if (toldJoke \u003d \u003d true) (Alert ($ punchline);) else) alert (joke); B \\\\ Movie Night var zip code \u003d 98104; var joe "sFavoriteMovie \u003d Forbidden Planet; var movieTicket $ \u003d 9; if (movieTicket $\u003e \u003d 9) (alert (" Too much! ");) else () 50 chapter 1 alert (" We "re going to see" + joe "sFavoriteMovie); Getting Started with JavaScript Be careful with expressions! To express intent in JavaScript, you need expressions. Each expression evaluates and the result is a value. We've seen expressions in the code examples. Let's look at the expression in the following command: Command JavaScript assigns the calculated result to the variable total.migSign * is used for doing things for cutting, and / - var total \u003d price - (price * (discount / 100)); Our variable is total.Assignment. And this is an expression. If you at least once you attended math lessons, summed up a balance or paid taxes, you will probably find the numerical expressions familiar to you.I As a result, we calculate the price (pr unt), for the discount (disco from x that prices to the given price price . If the variable is 10 or less. It contains discount - 20, result 8. Evaluate tat bud There are also string expressions: i "in a new line" Dear These strings are "concatenated by concatenation). Name Reader "(such an operation is" Dear "+" Reader "+", "The result is the same, but in the expression. When calculating, the rock sting containing g is the string" supercalifra "super" + "cali" + youKnowTheRest of the result gets ilisticexpialidocious. "* phoneNumber.substring (0,3) Another example of an expression that returns a string, I'll explain how it works later, but for now suffice it to say that the expression returns the area code from a phone number. The result of the calculation can also be true or false (true or false); these expressions are called boolean (or logical) expressions. Determine which result (true or false) will be obtained when evaluating each of the following expressions: age< 14 Если возраст (age) меньше 14, то результат равен true; в противном случае он равен false. Команда проверяет возраст пользователя. cost > \u003d 3.99 animal \u003d \u003d "bear" If the price of the item is greater than or equal to 3.99, the expression is true. Otherwise, it is false. Don't miss the sale! True if the word "bear" is present in the name of the animal. The result of an expression can be a value of another type; we will come back to this topic. In the meantime, it is important to know that when evaluating any expression, a certain result will be obtained - a number, a string or a logical expression. What does this give us? * YouKnowTheRest is assumed to contain the string “fragilisticexpialidocious”. more 4 51 expression exercises Take a pencil in your hand Take a pencil. For each of the above expressions, calculate its value and write it down in the highlighted place. Exactly WRITE DOWN ... forget your mother's words about not writing in books, and write the answer on the page! You can check the answers at the end of the chapter. Calculator for converting temperatures from Celsius to Fahrenheit? (9/5) * temp + 32 Boolean expression. The \u003d\u003d operator tests if two values \u200b\u200bare equal. color \u003d\u003d "orange" name + "," + "you" ve won! "yourLevel\u003e 5 Check:" Is the first value greater than the second? " You can use the\u003e \u003d operator for the condition "is the first value greater than or equal to the second?" (level * points) + bonus color! \u003d "orange" What happens if the temp variable is 10? __________ Is this expression true or false if the color variable contains the value “pink”? __________ And if the value is “orange”? __________ What value what happens if name contains the string "Martha"? __________________________________ What happens if yourLevel \u003d 2? ________ What happens if yourLevel \u003d 5? ________ What happens if yourLevel \u003d 7? ________ Level \u003d 5, points \u003d 30000 , and bonus \u003d 3300. What is the result of the calculation? ________ If the variable color contains the string “pink”, will this expression be true or false? __________ The! \u003d operator checks that two values \u200b\u200bare NOT equal. Increased score question! 1000 + "108" 52 Chapter 1 There are several answers, only one of them is correct. Which one will you choose? ______________________ For the curious, have you noticed that the \u003d operator is used in the assignment, and \u003d\u003d is used when checking? and you assign a value to a variable, put one equal sign \u003d, and when you check if two values \u200b\u200bare the same, put two \u003d\u003d signs. Novice programmers often confuse these operators. first acquaintance with javascript while (juggling) () keepBallsInAir (); Repeated execution of operations We often have to repeat the same operations: Rinse, spit, repeat. Eat another spoonful. And then another. Take candies from the box until they run out. Of course, in programs, operations also have to be repeated. JavaScript provides several syntactic constructs for re-executing code: while, for, for in, and forEach. We'll look at all of these kinds of loops over time, but for now we'll focus on while. We recently looked at expressions that evaluate to a Boolean result (for example, scoops\u003e 0). Such expressions play a key role in while statements: The while loop begins with the while keyword. The while loop contains a boolean expression called a continuation condition (or just a condition). If the loop condition is true, then the entire program block is executed. while (scoops\u003e ");) scoops \u003d scoops - 1; If the condition is true, then after the execution of the program block, it returns to the beginning of the loop, and everything is repeated again. If the condition is false, the loop ends. What is a" program block "? that is enclosed in curly braces (). And so on until the bitter end! next 4 53 javascript loops How the while loop works Since this is your first while loop, let's take a closer look at its execution and thoroughly understand how it works. added the declaration of the variable scoops and initialized it to 5. The code execution starts. First, the variable scoops (ice cream balls) is set to 5. var scoops \u003d 5; while (scoops\u003e 0) (document.write ("Another scoop!
"); scoops \u003d scoops - 1;) document.write (" Life without ice cream isn "t the same"); The program then jumps to the while command. When the while command is executed for the first time, the program first checks its condition - is it true or false? Scoops value var scoops \u003d 5; Above zero? Undoubtedly! while (scoops\u003e 0) (document.write ("Another scoop!
"); scoops \u003d scoops - 1;) document.write (" Life without ice cream isn "t the same"); Since the condition is true, execution of the program block begins. The first command in the body of the loop displays the string “Another scoop!
”. var scoops \u003d 5; while (scoops\u003e 0) (document.write ("Another scoop!
"); scoops \u003d scoops - 1;) document.write (" Life without ice cream isn "t the same"); 54 chapter 1 first acquaintance with javascript The following command decreases the current value of scoops by 1 and assigns the result (4) to the same variable scoops. 1 ball ate, 4 left! var scoops \u003d 5; while (scoops\u003e 0) (document.write ("Another scoop!
"); scoops \u003d scoops - 1;) document.write (" Life without ice cream isn "t the same"); This is the last command in the block. The cycle goes back to the beginning, and everything is repeated again. var scoops \u003d 5; while (scoops\u003e 0) (document.write ("Another scoop!
"); scoops \u003d scoops - 1;) document.write (" Life without ice cream isn "t the same"); The condition is checked again; this time scoops is 4. But although scoops has decreased, it is still greater than zero. Many more var scoops \u003d 5; left! while (scoops\u003e 0) (document.write ("Another scoop!
"); scoops \u003d scoops - 1;) document.write (" Life without ice cream isn "t the same"); And again the line “Another scoop!
”. var scoops \u003d 5; while (scoops\u003e 0) (document.write ("Another scoop!
"); scoops \u003d scoops - 1;) document.write (" Life without ice cream isn "t the same"); further 4 55 while loop in javascript The following command decreases the current value of scoops by 1 and assigns the result (3) to the same variable scoops. var scoops \u003d 5; while (scoops\u003e 0) (document.write ("Another scoop!
"); scoops \u003d scoops - 1;) document.write (" Life without ice cream isn "t the same"); This is the last command in the block; the program returns to the condition, and everything is repeated again. var scoops \u003d 5; while (scoops\u003e 0) (document.write ("Another scoop!
"); scoops \u003d scoops - 1;) document.write (" Life without ice cream isn "t the same"); The condition is checked again, scoops is 3. It is still greater than zero. The balls are still var scoops \u003d 5; remained! while (scoops\u003e 0) (document.write ("Another scoop!
"); scoops \u003d scoops - 1;) document.write (" Life without ice cream isn "t the same"); The string “Another scoop!
”. var scoops \u003d 5; while (scoops\u003e 0) (document.write ("Another scoop!
"); scoops \u003d scoops - 1;) document.write (" Life without ice cream isn "t the same"); 56 chapter 1 2 balls are gone, 3 are left! first acquaintance with javascript Everything continues over and over again: with each execution of the loop, scoops decreases by 1, the next line is displayed in the browser, and the program enters the next circle. 3 balls ate, 2 left! var scoops \u003d 5; while (scoops\u003e 0) (document.write ("Another scoop!
"); scoops \u003d scoops - 1;) document.write (" Life without ice cream isn "t the same"); And it continues ... 4 balls are eaten, 1 is left! var scoops \u003d 5; while (scoops\u003e 0) (document.write ("Another scoop!
"); scoops \u003d scoops - 1;) document.write (" Life without ice cream isn "t the same"); Until the last time ... but now something has changed. Scoops is zero and the condition is false. This is where it all ends; the cycle should no longer run. This time, the program bypasses the block and executes the command following it. 5 balls ate, there are 0 left! var scoops \u003d 5; while (scoops\u003e 0) (document.write ("Another scoop!
"); scoops \u003d scoops - 1;) document.write (" Life without ice cream isn "t the same"); The next command executes document.write and displays the line “Life without ice cream isn’t the same”. Done! var scoops \u003d 5; while (scoops\u003e 0) (document.write ("Another scoop!
"); scoops \u003d scoops - 1;) document.write (" Life without ice cream isn "t the same"); more 4 57 conditional javascript commands if (cashInWallet\u003e 5) (order \u003d “Carry on like this: cheeseburger, potatoes and cola”;) else (order \u003d “And I'll take a glass of water”;) Decision making in JavaScript You've already seen how a conditional expression is used to decide whether or not the while loop should continue. Boolean expressions can also be used to make decisions in JavaScript commands using if. The if statement executes its program block only if the condition being tested is true. Example: the second is the ovo if, followed by the next. any ok C ogram bl condition, etc. This condition checks if there are less than three ice cream balls left. if (scoops< 3) { } alert("Ice cream is running low!"); И если осталось меньше трех, выполняется программный блок команды if. Функция alert получает строку и выводит ее во всплывающем окне браузера. Попробуйте! Команда if позволяет последовательно выполнить несколько проверок; для этого добавляется одна или несколько секций else if: одно условие, если оно Сначала проверяется оверяется другое, не выполняется, то пр if (scoops >\u003d 5) (specified in if / else: alert ("Eat faster, the ice cream is going to melt!");) Else if (scoops< 3) { } alert("Ice cream is running low!"); 58  глава 1 Добавьте столько дополнит ельных проверок “else if”, сколько вам нужно; с каждым условием связывается свой програ ммный блок, выполняющийся в случае его истинности. первое знакомство с javascript А если нужно принять МНОГО решений... Вы можете объединить сколько угодно команд if/else. Также можно добавить завершающую секцию else; если ни одно условие не выполняется, вы сможете обработать и эту ситуацию, как в следующем примере: if (scoops > \u003d 5) (First, we check to see if there are five or more balls of ice cream left ... alert ("Eat faster, the ice cream is going to melt!"); ... Or if there are exactly three balls left ... alert (" Ice cream is running low! ");) Else if (scoops \u003d \u003d 3) () else if (scoops \u003d \u003d 2) (alert (" Going once! "); ... Or if there are 2, 1 or 0 balls left ... In each case, a corresponding signal is output.) Else if (scoops \u003d \u003d 1) (alert ("Going twice!");) Else if (scoops \u003d \u003d 0) (If none of the preceding conditions are true then this code will be executed alert ("Gone!");) else () Q: A: alert ("Still lots of ice cream left, come and get it."); Frequently Asked Questions What is a "programming block"? At the syntax level, a program block (usually referred to simply as a block) is a set of commands, one or more, enclosed in curly braces. All block commands form a group that is executed as a whole. For example, if the while condition is true, then all commands in the block will be executed. This also applies to if or else if blocks. Q: I saw a code in which a condition consists of one variable, and this variable contains not even a boolean value, but a string. How does he work? A: This topic will be covered a little later, but in a nutshell - JavaScript is flexible enough about what it considers true or false values. For example, any variable that contains a (non-empty) string is considered true, and a variable that has not yet been assigned a value is considered false. Wait, we will cover this issue in detail soon. Q: You said that the result of an expression can be not only numbers, strings or booleans, but something else. What exactly? A: For now we will restrict ourselves to primitive types: numbers, strings and booleans. But over time, we will get into more complex types: arrays (sets of values), objects and functions. Q: Where did the name "boolean values" (another name for booleans) come from? A: It comes from the name of George Boole, an English mathematician, the creator of Boolean logic. more 4 59 Fun with magnets Fun with magnets Magnets with JavaScript fragments are messed up. Can you arrange them in order to get a workable JavaScritp program that produces the output below? Check the answers at the end of the chapter before reading on. Arrange the magnets in place to create a workable JavaScript program. document.write ("Happy Birthday dear" + name + ",
"); document.write (" Happy Birthday to you.
"); var i \u003d 0; i \u003d i + 1; var name \u003d" Joe ";) document.write (" Happy Birthday to you.
"); while (i< 2) { Расставьте магниты в этой области. 60  глава 1 Восстановленная программа должна выдавать этот результат. первое знакомство с javascript Привлекайте пользователя к взаимодействию со страницей Мы говорили о том, как важно повысить уровень интерактивности страниц и что для этого необходимо взаимодействие с пользователем. Это взаимодействие можно организовать несколькими способами; некоторые из них уже встречались вам. Ниже приведена краткая сводка таких взаимодействий, а потом мы рассмотрим их более подробно. Создание сигнала Браузер поддерживает простейший механизм оповещения пользователей при помощи функции alert. Вызовите alert со строкой, содержащей сообщение, и браузер выведет ее в симпатичном диалоговом окне. Честно говоря, мы немного злоупотребляли этой функцией, она очень проста и удобна; но ее следует применять только тогда, когда вы действительно хотите, чтобы пользователь отложил все дела и немедленно ознакомился с вашим сообщением. Прямая запись в документ Эти три способа встречаются в данной главе. Веб-страницу можно рассматривать как документ (именно так ее называет браузер). Функция document.write позволяет вывести произвольную разметку HTML и контент в произвольной точке страницы. Так поступать не рекомендуется, хотя время от времени этот способ все же применяется. Мы воспользовались, потому что он достаточно прост для изучения JavaScript. Вывод на консоль В каждой среде JavaScript существует консоль, на которую можно выводить сообщения из программного кода. Чтобы вывести сообщение на консоль, вызовите функцию console.log и передайте ей строку (вскоре мы рассмотрим работу с консолью более подробно). Функция console.log - отличный инструмент диагностики и отладки. Впрочем, в нормальной программе вывод на консоль спрятан от пользователя, так что this mechanism can hardly be called effective. The console is a handy tool for finding errors in your code! If you enter a mistake (for example, you missed a quote), JavaScript usually prints a description of the error to the console, which will make it easier to find. Modifying a Document Directly The main way to interact with a page and users is JavaScript tools that allow you to access the markup of a web page, read and modify its content, even change the structure and style! All these operations are performed through the Document Object Model (see below). As you will soon see, this is the best user experience. However, to work with the document object model, you need to know the structure of the page and the programming interface used to read and write the page. We'll get to this topic shortly, but first, you need to master some more JavaScript. A cherished goal that we strive for. Once you reach it, you will be able to read the page, modify it and perform any manipulation of its content. next 4 61 javascript output comparison Who does what? ae ae All means of interaction came to the masquerade. Will you be able to recognize them under masks? Join the descriptions on the right with the names in the left column. We have drawn one line for you. document.write I immediately stop what the user is doing and issue a short message. To move on, the user must click "OK". console.log I can insert small snippets of HTML and text markup into a document. I may not be the most elegant way to convey information to the user, but I work in all browsers. alert With my help, you can fully control the web page: receive user input, change HTML markup and styles, and update the page content. document object model 62 chapter 1 I exist solely for simple debugging tasks, and I allow information to be output to a special console intended for developers. first acquaintance with javascript A close acquaintance with console.log Let's understand how the console.log function works. We'll use it in this chapter to see the results of executing the code, and in other chapters of the book to analyze and debug the output. Keep in mind, however, that the console remains hidden from most ordinary web users, so it's not advisable to use it in the final web page. Console output is typically used for diagnostics during page development. It also helps you see what's going on in your code as you learn basic JavaScript constructs. Here's how it works: Take any string ... var message \u003d "Howdy" + "" + "partner"; console.log (message); ... and pass it to console.log. The string is output to the browser console. The console contains all the data that is output by calls to console.log in your application. frequently Q: Questions asked I understand that console.log can be used to output strings, but what is it anyway? Why are “console” and “log” separated by a dot? A: Good question. We're getting a little ahead of ourselves, but think of the console as an object that performs various operations (console). One of these tasks is to output data to the console. To tell the console to do this operation, we use the syntax “console.log” and pass the output value in parentheses. Remember this; objects will be discussed in much more detail in this book. For now, just be able to use console.log is enough. Q: Does the console do anything besides normal output? A: Yes, but more often it is used for normal output. There are several other ways to use output (and console), but these are browser-specific. The console is supported by all modern browsers, but not defined in any formal specification. Q: A: All this, of course, is good, but

Are you ready to take your web programming a step further and move from HTML and CSS layout to full-fledged dynamic pages? Then it's time to get to know the "hottest" programming language - JavaScript! With this book, you will learn everything about JavaScript, from variables to loops. You will understand why different browsers react differently to code and how to write universal code that is supported by all browsers. It will become clear to you why you never have to worry about page congestion and data transfer errors with JavaScript code. Don't be alarmed, even if you haven't written a single line of code before - thanks to the unique presentation format, this book will easily guide you along the entire learning path: from writing a simple script to creating complex web projects that will work in all modern browsers. A special feature of this publication is the unique way of presenting material, which sets the O'Reilly Head First series apart from the many boring books devoted to programming.

On our site you can download the book "Learning JavaScript Programming" by Freeman Elizabeth for free and without registration in fb2, rtf, epub, pdf, txt format, read the book online or buy a book in the online store.