Estudio de Programación - React
Estudio de Programación - React
Getting started with the Web is a concise series introducing you to practicalities of Web
development. You’ll set up the tools you need to construct a simple webpage and publish your
own simple code.
In Installing basic software, we show you what tools you need to do simple web development
and how to install them properly.
1
https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web
What tools do I actually need, right now?
That looks like a scary list, but can get started in web development without knowing anything
about most of these. In this article, we’ll just set up with a bare minimum – a text editor and
some modern web browsers.
In Installing basic software, we show you what tools you need to do simple web development
and how to install them properly2.
Before going on, you should install at least two of these browsers and have them ready for
testing.
Internet Explore is not compatible with some modern web features and it may not be able to
run your project.
Some examples will need to be run by a web server to work successfully. You can find out how
to do this in How do you set up a local testing server?
Prerequisites: None.
2
https://developer.mozilla.org/en-
US/docs/Learn/Getting_started_with_the_web/Installing_basic_software
3
https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Thinking_before_coding
Summary
When starting with a web project, many people focus on the technical side. Of course you
must be familiar with the technique of your craft, but what really matters is what you want to
accomplish. Yes, it seems obvious, but to many projects fail not from lack of technical know
how, but from lack of goals and vision.
So when you get an idea and want to turn it into a website, there are a few questions you
should answer before anything else:
All of this is called project ideation and is a necessary first step to reach your goal, whether you
are a beginner or an experienced developer.
Deeper dive
A project never starts with the technical side. Musicians will never make any music unless they
first have an idea of what they want to play-and the same is true for painters, writers, and web
developers. Technique comer second.
Technique is obviously critical. Musicians must master their instrument. But good musician can
never produce good music without an idea. Therefore, before jumping into the technical side-
for example, code and tools-you must first step back and decide in detail what you want to do.
An hour’s discussion with friends is a good start, but inadequate. You must sit down and
structure your ideas to get a clear view of what path you must take to make your ideas a
reality. To do this, you need only pen and paper and some time to answer at least the
following questions.
Note: there are countless ways to carry out projects ideation. We cannot lay them all out here
(a whole book wouldn’t be enough). What we will present here is a simple method to handle
what professionals call Project Ideation, Project Planning, and Project Management.
Once you have such list, you need to prioritize. Order the goals from most important to least
important:
Doing this simple exercise-writing goals and sorting them-will help you out when you have
decisions to make. (should I implement these features, use these services, create these
designs?).
So now that you have to prioritized list of goals, let’s move on the next question.
Let’s look back at our example. We have five goals connected to music, one goal related to
personal life (finding your significant other), and the completely unrelated car photos. Is it
reasonable to build a single website to cover all those goals? Is it even necessary? After all,
scores of existing web services might bring you to your goals without building a new website.
Finding a girl/boyfriend is a prime case where it make more sense to use existing resources
rather than build a whole new site. Why? Because we’ll spend more time building and
maintaining the website rather than actually searching for a girl/boyfriend. Since our goal is
what matters most, we should spend our energy on leveraging 4 existing tools rather than
starting from scratch. Again, there are so many web services already available for showcasing
photos that it isn’t worth the effort to build a new site just to spread the word about how cute
our cats are.
The other five goals are all connected to music. There are, of course, many web services that
could handle these goals, but it makes sense in this case to build a dedicated website of our
own. Such a website is the best way to aggregate all the stuff we want to publish in a single
place (good for goals 3, 5, and 6) and promote interaction between us and the public (good for
goals 2 and 4). In short, since these goals all revolve around the same topic, having everything
in one place will help us to meet our goals and help our followers connect with us.
How can a website help me reach my goals? By answering that, you’ll find the best way to
reach your goals and save yourself from wasted effort.
4
WR: vtr, tener influencia, hacer uso, apalancar. https://www.wordreference.com/es/translation.asp?
tranword=leveraging
What needs to be done, and in what order, to reach my goals?
Now that you know what you want to accomplish, it’s time to turn those goals into actionable
steps. As a side note, your goals are not necessarily set in stone. They evolve over time even in
the course of the project, especially if you run across unexpected obstacles or just change your
mind.
Rather than go through a long explanation, let’s go back to our example with this table:
Goals Things to do
Let people hear your music 1. Record music
2. Prepare some audio files usable online (Could
you do this with existing web services?)
3. Give people access to your music on some part of
your website
Talk about music 1. Write a few articles to start the discussion
2. Define how article should look
3. Publish those articles on the website (How to do
this?)
Meet other musicians 1. Provide ways for people to contact you (Email?
Facebook? Phone? Mail?)
2. Define how people will find those contact
channels from your website
Sell goodies 1. Create the goodies
2. Store the goodies
3. Find a way to handle shipping
4. Find a way to handle payment
5. Make a mechanism on your site for people to
place orders
Teach music through videos 1. Record videos lessons
2. Prepare video files viewable online (Again, could
you do this with existing web services?)
3. Give people access to your videos on some part
of your website
Two things to notice. First, some of these items are not web-related (e.g., record music, write
articles). Often those offline activities matter even more than the web side of the project. In
sales, for instance, it’s far more important and time-consuming to handle supply, payment,
and shipment than to build a website where people can place orders.
Second, setting out actionable steps leads to new questions you’ll need to answer. Usually
there turn out to be more questions than we originally thought. (For example, should I learn
How to do all this myself, ask someone to do it for me, or use third-party services?)
Conclusion
As you can see, the idea “I want to make a website” generates a long to-do list, which only
grows longer as you think about it. Soon it may look overwhelming, but don’t panic. You don’t
need to answer all the questions and you don’t need to do everything on your list. What
matters is to have a vision of what you want and how to get there. Once you have that clear
vision, you need to decide how and when to do it. Break down big task into small, actionable 5
steps. And those small steps will add up to great achievements.
From this article, you should now be able to make a rough plan for creating a website. A next
step might be to read how the Internet works.
Prerequisites: None, but we encourage you to read the Article on setting project goals7 first
Objective: You will learn the basics of the technical infrastructure of the Web and the
difference between Internet and the Web.
Summary
The Internet is the backbone of the Web, the technical infrastructure that makes the Web
possible. At its most basic, the Internet is a large network of computers which communicate all
together.
The history of the Internet is somewhat obscure. It began in the 1960s as a US-army-funded
research project, then evolved into a public infrastructure in the 1980s with the support of
many public universities and private companies. The various technologies that support the
Internet have evolved over time, but the way it works hasn’t changed that much: Internet is a
way to connect computers all together and ensure that, whatever happens, they find a way to
stay connected.
Deeper dive
A simple network
When two computers need to communicate, you have to link them, either physically (usually
with an Ethernet cable) or wirelessly (for example with WiFi or Bluethooth systems). All
modern computers can sustain any of those connections.
Note: for the rest of this article, we will only talk about physical cables, but tireless networks
work the same.
Such a network is not limited to two computers. You can connect as many computers as you
wish. But it gets complicated quickly. If you’re trying to connect, say, ten computers, you need
45 cables, with nine plugs per computer!
To solve this problem, each computer on a network is connected to a special tiny computer
called a router. This router has only one job: like a signaler at a railway, it makes sure that a
message sent from a given computer arrives at the right destination computer. To send a
message to computer B, computer A must send the message to the router, which in turn
forward the message to computer B and makes sure the message is not delivered to computer
C.
5
WR: adj, Procesable, justificable, susceptible de procesamiento, que se puede enjuiciar, factible.
https://www.wordreference.com/es/translation.asp?tranword=actionable
6
https://developer.mozilla.org/en-US/docs/Learn/Common_questions/How_does_the_Internet_work
7
https://developer.mozilla.org/en-US/docs/Learn/Thinking_before_coding
Once we add a router to the system, our network of 10 computers only requires 10 cables: a
single plug for each computer and a router with 10 plugs.
A network of networks
So far so good. But what a bout connecting hundreds, thousands, billion of computers? Of
course a single router can’t scale that far, but, if you read carefully, we said that a router is a
computer like any other, so what keeps us from connecting two routers together? Nothing, so
let’s do that.
By connecting computers to routers, then routers to routers, we are able to scale infinitely.
Such a network comer very close to what we call the Internet, but we’re missing something.
We built that network for our own purposes. There are another networks out there: your
friends, your neighbors, anyone can have their own network of computers. But it’s not really
possible to set cables up between your house and the rest of the world, so how can you handle
this? Well, there are already cables linked to your house, for example, electric power and
telephone. The telephone infrastructure already connects your house with anyone in the
world so it is the perfect wire we need. To connect our network to the telephone
infrastructure, we need a special piece of equipment called a modem. This modem turn the
information from our network into information manageable by the telephone infrastructure
and vice versa.
So we are connected to the telephone infrastructure. The next step is to send the messages
from our network to the network we want to reach. To do that, we will connect our network
to an Internet Service Provider (ISP). An ISP is a company that manages some special routers
that are all linked together and can also access other ISP’s routers. So the message from our
network is carried through the network os ISP networks to the destination network. The
Internet consists of this whole infrastructure of networks.
Finding computers
If you want to send a message to a computer, you have to specify which one. Thus any
computer linked to a network has a unique address that identifies it, called an “IP address”
(where IP stands for Internet Protocol). It’s an address made of a series of four numbers
separated by dots, for example: 192.168.2.10.
That’s perfectly fine for computers, but we human beings have a hard time remembering that
sort of address. To make things easier, we can alias an IP address with a human readable name
called a domain name. for example (at the time of writing; IP address can change) google.com
is the domain name used on top of the IP address 173.194.121.32. So using the domain name
is the easiest way for us to reach a computer over the Internet.
What is the difference between webpage, website, web server, and search engine? 8
In this article, we describe various web-related concepts: web pages, website, web server, and
search engines. These terms are often confused by newcomers to the web or are incorrectly
used. Let’s learn what they each other means!
Objective: be able to describe the differences between a web page, a website, a web server,
and a search engine.
Summary
As with any area of knowledge, the web comes with a lot of jargon. Don’t worry, we won’t
overwhelm you with all of it (we have a glossary of you’re curious). However, there are a few
basic terms you need to understand at the outset, since you’ll hear these expressions all the
time as you read on. It’s easy to confuse these terms sometimes since they refer to related but
different functionalities. In fact, you’ll sometimes see these terms misused in news reports and
elsewhere, so getting them mixed up is understandable!
We’ll cover these terms and technologies in more detail as we explore further, but these quick
definitions will be a great start for you:
web page
A document which can displayed in a web browser such as Firefox, Google Chrome, Opera,
Microsoft Internet Explorer or Edge, or Apple’s Safari. These are also often called just “pages.”
website
A collection of web pages which are grouped together and usually connected together in
various ways. Often called a “web site” o simply a “site.”
web server
search engine
search engine
A web service that helps you find other web pages, such as Google, Bing, Yahoo, or
DuckDuckGo. Search engines are normally accessed through a web browser (e.g. you can
perform search engine searches directly in the address bar of Firefox, Chrome, etc.) or through
a web page (e.g. bing.com or duckduckgo.com).
8
https://developer.mozilla.org/en-
US/docs/Learn/Common_questions/Pages_sites_servers_and_search_engines
Let’s look at a simple analogy – public library. this is what you would generally do when visiting
a library:
The library is like a web server. It has several sections, which is similar to a web server
hosting multiple websites.
The different sections (science, math, history, etc.) in the library are like websites. Each
section is like a unique website (two sections do not contain same books).
The books in each section are like webpages. One website may have several webpages,
e.g., the Science section (the website) will have books on heat, sound,
thermodynamics, statics, etc. (the webpages). Webpages can each be found at a
unique location (URL).
The search index is like the search engine. Each book has its own unique location in the
library (two books cannot be kept at the same place) which is specified by the catalog
number.
Deeper dive
So, let’s dig deeper into how those four terms are related and why they are sometimes
confused with each other.
Web page
A web page is a simple document displayable by a browser. Such documents are written in the
HTML language (which we look into more detail in other articles). A web page can embed a
variety of different types of resources such as:
Note: Browsers can also display other documents such as PDF files or images, but the term
web page specifically refers to HTML documents. Otherwise, we only use the term document.
All web pages available on the web are reachable through a unique address. To access a page,
just type its address in your browser address bar:
Web site
A website is a collection of linked web pages (plus their associated resources) that share a
unique domain name. each web page of a given website provides explicit links-most of the
time in the form of clickable portion of text-that allows the user to move from one page of the
website to another.
To access a website, type its domain name in your web browser address bar, and the browser
will display the website’s main web page, or homepage (casually referred as “the home”):
The ideas of a web page and a website are especially easy to confuse for a website that
contains only one web page. Such a website is a sometimes called a single-page website.
Web server
A web server is a computer hosting one or more websites. “Hosting” means that all the web
pages and their supporting files are available on that computer. The web server will send any
web page from the website it is hosting to nay user’s browser, per user request.
Don’t confuse website and web server. For example, if you hear someone say, “My website is
not responding”, it actually means that the web server is not responding and therefore the
website in not available. More importantly, since a web server can host multiple websites, the
term web server is never used to designate a website, as it could cause great confusion. In our
previous example, if we said, “My web server in not responding”, it means that multiple
websites on that web server are not available.
Search engine
Search engines are a common source of confuse on the web. A search engine is a special kind
of website that helps users find web pages from other websites.
There are plenty out there: Google, Bing, Yandex, DuckDuckGo, and many more. Some are
generic, some are specialized about certain topics. Use whichever you prefer.
Many beginners on the web confuse search engines and browsers. Let’s make it clear: A
browser is a piece of software that retrieves and displays web pages; a search engine is a
website that helps people fin pages from other websites. The confusion arises because, the
first time someone launches a browser, the browser displays as search engine’s homepage.
This makes sense, because, obviously, the first thing you want to do with a browser is to find a
web page to display. Don’t confuse the infrastructure (e.g., the browser) with the service (e.g.,
the search engine). The distinction will help you quite a bit, but even some professionals speak
loosely, so don’t feel anxious about it.
Here is an instance of Firefox showing a Google search box as its default startup page:
Prerequisites: You should already know how Internet works, and understand the difference
between a web page, a web site, a web server, and a search engine.
Objective: you will learn what server is and gain general understand of how it works.
Summary
“Web server” can refer to hardware of software, or both of them working together.
1. On the hardware side, a web server is a computer that stores web server software and
a website’s components files (e.g. HTML documents, images, CSS stylesheets, and
JavaScript files). It is connected to the Internet and supports physical data interchange
with other devices connected to the web.
2. On the software side, a web server includes several parts that control how web users
access hosted files, at minimum an HTTP server. An HTTP server is a piece of software
9
https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_web_server
that understand URLs (web address) and HTTP (the protocol your browser uses to view
webpages). It can be accessed through the domain names (like mozilla.org) of websites
it stores, and delivers their content to the end-user’s device.
At the most basic level, whenever a browser needs a file which is hosted on a web server, the
browser request the file via HTTP. When the request reaches the correct web server
(hardware), the HTTP SERVER (software) request, finds the requested document (if it doesn’t
then a 404 response is returned), and sends it back to the browser, also through HTTP.
A static web server, or a stack, consists of a computer (hardware) with an HTTP server
(software). We call it “static” because the server sends its hosted files “as-is” to your browser.
A dynamic web server consists of a static web server plus extra software, most commonly an
application server and a database. We call it “dynamic” because the application server updates
the hosted files before sending them to your browser via the HTTP server.
For example, to produce the final webpage you see in the browser, the application server
might fill an HTML template with contents from a database. Sites like MDN or Wikipedia have
many thousands of webpages, but they aren’t real HTML documents, only a few HTML
templates and a giant database. This setup makes it easies and quicker to maintain and deliver
the content.
Deeper dive
To fetch a webpage, as we already said, your browser sends a request to the webserver, which
proceeds to search for the requested file in tis own storage space. On finding the file, the
server reads it, processes it as needed, and sends it to the browser. Let’s look atthose steps in
more detail.
Hosting files
A web sever first has to store the website’s files, namely all HTML documents and their related
assets, including images, CSS stylesheets, JavaScript files, fonts, and videos.
Technically, you could host all those files on your own computer, but it’s far more convenient
to store them all on a dedicated web server that
Once you set up a web hosting solution, you just have to upload your files to our web server.
A Protocol is a set of rues for communication between two computers. HTTP is a textual,
stateless protocol.
Textual
Stateless
Neither the server not the client remember previous communications. For example, relying on
HTTP alone, a server cannot remember a password you typed or what step you’re on in a
transaction. You need an application server for tasks like that. (We’ll cover that sort of
technology in further articles.)
HTTP provides clear rules for how a client and server communicate. We’ll cover HTTP itself in a
technical article later on. For now, just be aware of these things:
Only clients can make HTTP requests, and then only servers. Servers can only respond
to a client’s HTTP request.
When requesting a file via HTTP, clients must provide the file’s URL.
The web server must answer every HTTP request, at least with an error message.
On a web server, the HTTP server is responsible for processing and answering incoming
requests.
1. On receiving a request, an HTTP server first checks whether the requested URL
matches an existing file.
2. If so, the web server sends the file content back to the browser. If not, an application
server builds the necessary file.
3. If neither process is possible, the most commonly 404 Not Found. (That error is so
common that many web designers spend quite some time designing 404 error pages.)
10
https://developer.mozilla.org/en-
US/docs/Learn/Common_questions/How_much_does_it_cost#Hosting
Static vs. dynamic content
Roughly speaking, a server can serve either static of dynamic content. “Static” means “served
as-is”. Static websites are the easiest to set up, so we suggest you make you first sire a static
site.
“Dynamic” means that the server processes the content or even generates it on the fly from a
database. This solution provides more flexibility, but the technical stack becomes more difficult
to handle, making it dramatically more complex to build the website.
Take for example the page you’re reding right now. On the web server hosting it, there is an
application server that takes article content from a database, formats it, puts it inside some
HTML templates, and sends you the results. In this case, the application server is called Kuma
and is built with Python (using the Django framework). The Mozilla team built Kuma for the
specific needs of MDN, but there are many similar applications built on many other
technologies.
There are so many application servers that it’s pretty hard to suggest a particular one. Some
application servers cater to specific website categories like blogs, wikis or e-shops; others,
called CMSs (content management systems), are mote generic. If you’re building a dynamic
website, take the time to choose a tool that fits your needs. Unless you want to learn some
web server programming (which is an exciting area in itself!), you don’t need to create your
own application server. That’s just reinventing the wheel.
Prerequisites: you need to first how the Internet works, and what a Web server is.
If the web address path starts with file:// followed by the path to the file on your local hard
drive, a local file is being used. In contract, if you view one of our examples hosted on GitHub
(or an example on some other remote server), the web address will start with http:// or
http://, to show that the file has received via HTTP.
11
https://developer.mozilla.org/en-US/docs/Learn/Common_questions/set_up_a_local_testing_server
They feature asynchronous requests. Some browser (including Chrome) will not run
async requests (see Fetching data from the server12)if you just run the example from a
local file. This is because of security restrictions (for more on web security, read
Website security).
They feature a server-side language. Server-side languages (such as PHP or Python)
require a special server to interpret the code and deliver the results.
To do this:
1. Install Python. If you are using Linux or macOS, it should be available on your system
already. If you are a Windows user, you can get an installer from the Python homepage
and follow the instructions to install it:
Go to python.org
Under the Download section, click the link for Phyton “3.xxx”
At the bottom of the page, choose the Windows x86 executable installer and
download it.
When it has downloaded, run it:
On the first installer page, make sure you check the “Add Python 3.xxx to
PATH” checkbox.
Click Install, then Click Close when the installation has finished.
2. Open your command prompt (Windows)/ terminal (macOS/Linux). To check Python is
installed, enter the following command:
1 | python -V
2 | # Or you might have the py command available,
3 | # in which case try py -V
3. This should return a version number. If this is OK, navigate to the directory that your
example is inside, using the cd command.
1 | # include the directory name to enter it, for example
2 | cd Desktop
3 | # use two dots to jump up one directory level if you need to
4 | cd..
4. Enter the command to start up the server in that directory:
# If Python version returned above is 3.X
Python3 -m http.server
# On windows try “python” instead of “python3”, or “py -3”
Python -m SimpleHTTPServer
5. By default, this will run the contents of the directory on a local web server, on port
8000. You can go to this server by going to the URL localhist:8000 in your web browser.
Here’ll see the contents of the directory listed – click the HTML file you want to run.
12
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Fetching_data
Note: if you already have something running on port 8000, you can choose another port by
running the server command followed by an alternative port number, e.g. python3 -m
http.server 7800 (Python 3.x) or python -m SimpleHTTPServer 7800 (Python 2.x). You can then
access your content at localhost:7800.
Python’s SimpleHTTPServer (python 2.0) http.server (python 3.0) module is useful, but it
doesn’t know to run code written in languages such as Python, PHP or JavaScript. To handle
that you’ll need something more – exactly what you’ll need depends on the server-side
language you are trying to run. Here are a few examples:
To run Python server-side code, you’ll need to use a Python web framework. You can
find out how to use the Django framework by reading Django Web Framework
(Python). Flask is also a good (slightly less heavyweight) alternative to Django. To run
this you’ll need to install Python/PIP, then install Flask using pip3 install flask. At this
point you should be able to run the Python Flask example python3 python-example.py,
then navigating to localhost:5000 your browser.
To run Node.js (JavaScript) server-side code, you’ll need to use raw node or a
framework built on top of it. Express is a good choice – see Express Web Framework
(Node.js/JavaScript)13.
1 | $ cd path/to/your/php/code
2 | $ php -S localhost:8000
What will your website look like? Discusses the planning and design work you have to do for
your website before writing code, including “What information does my website offer?”,
“What fonts and colors do I want?”, and “What does my site do?” 14
1. What is your website about? Do you like dogs, New York, or Pac-Man?
2. What information are you presenting on the subject? Write a title and a few
paragraphs and think of an image you’d like to show on your page.
13
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs
14
https://developer.mozilla.org/en-
US/docs/Learn/Getting_started_with_the_web/What_will_your_website_look_like
3. What does your website look like, in simple high-level terms? What’s the background
color? What kind of font is appropriate: formal, cartoony, bold and loud, subtle?
Note: Complex projects need detailed guidelines that go into all the details of colors, fonts,
spacing between items on a page, appropriate writing style, and so on. This is sometimes
called a design guide, design system, or brand book, and you can see an example at the Firefox
Photon Design System.
Note: Even on real, complex websites, the design teams usually start out with rough sketches
on paper and later on build digital mockups using a graphics editor or web technologies.
Web teams often include both a graphic designer and a user experience15 (UX) designer.
Graphic designers put together the visuals of the website. UX designers have a somewhat
more abstract role in addressing how users will experience and interact with the website.
Text
You should still have your paragraphs and title from earlier. Keep these close by.
Theme color
To choose a color, go to the Color Picker and find a color you like. When you click on a color
you’ll see a strange six-character code like #66066. That’s called a hex code (short for
hexadecimal), and represents your color. Copy the code down somewhere sage for now.
Images
To choose an image, go to Google Images17 and search for something suitable.
1. When find the image you want, click on the image to get an enlarged view of it.
2. Right-click the image (Ctrl + click on a Mac), choose Save Image As…, and choose a safe
place to save your image. Alternatively, copy the image’s web address from your
browser’s address bar for later use.
Note that most images on the web, including in Google Images, are copyrighted. To reduce
your likelihood18 of violating copyright, you can use Google’s license filter. Click on the Tools
button, the on the result Usage rights option that appears below. You should choose an option
such as Labeled for reuse.
15
https://developer.mozilla.org/en-US/docs/Glossary/UX
16
WR: n, activos, bien mueble, valor, acciones, ventaja, recurso, valor, recurso herramienta.
https://www.wordreference.com/es/translation.asp?tranword=assets
17
https://www.google.com/imghp?gws_rd=ssl
18
WB: n, Probabilidad, posibilidad.
Font
To chose a font:
1. Go to Google Fonts19
HTML basics
Hypertext Markup Language (HTML) es the code that you use to structure your web content
and give it meaning and purpose. For example, is my content a set of paragraphs or a list of
bullet points? Do I have images inserted in my page? Do I have a data table? Without
overwhelming you, HTML basics provides enough information to make you familiar with
HTML.
CSS basics
Cascading Stylesheets (CSS) is the code that you use to style your website. For example, do you
want the text to be black or red? Where should content be drawn on the screen? What
background images and colors should be used to decorate your website? CSS basics takes you
through what you need to get started.
JavaScript basics
JavaScript is the programming language that you use to add interactive features to your
website. Some examples could be games, things that happen when buttons are pressed or
data is entered in forms, dynamic styling effects, animation, and much more. JavaScript basics
gives you an idea of what is possible with this exciting language, and how to get started.
19
http://www.google.com/fonts
Tutorial: Intro to React20
This tutorial doesn’t assume any existing React knowledge.
Tip
This tutorial is designed for people who prefer to learn by doing. If you prefer learning
concepts from the ground up, check out our step-by-step guide. You might find this tutorial
and the guide complementary to each other.
Setup for the Tutorial will give you a starting point to follow the tutorial.
Overview will teach you the fundamentals of React: components, props, and state.
Completing the Game will teach you the most common techniques in React
development.
Adding Time Travel will give you a deeper insight into the unique strengths of React.
You don’t have to complete all of the sections at once to get the value out of this tutorial. Try
to get as far as you can – even if it’s one or two sections.
You can see what we’ll be building here: Final Result. If the code doesn’t make sense to you, or
of you are unfamiliar with the code’s syntax, don’t worry! The goal of this tutorial is to help
you understand React and its syntax.
We recommend that you check out the tic-tac-toe game before continuing with the tutorial.
One of the features that you’ll notice is the there is a numbered list to the right of the game’s
board. This list gives you a history of all of the moves that have occurred in the game, and it is
updated as the game progresses.
You can close the tic-tac-toe game once you’re familiar with it. We’ll be starting from a simpler
template in this tutorial. Our next step is to set you up so that you can start building the game.
Prerequisites
We’ll assume that you have some familiarity with HTML and JavaScript, but you should be able
to follow along even if you’re coming from a different programming language. We’ll also
assume that you’re familiar with programming concepts like functions, objects, arrays, and to a
lesser extent, classes.
20
https://reactjs.org/tutorial/tutorial.html
If you need view JavaScript, we recommend reading this guide. No that we’re also using some
features from ES6 – a recent version of JavaScript. In this tutorial, we’re using arrow function,
classes, let, and const statements. You can use the Babel REPL to check what ES6 code
compiles to.
It's useful to start with an overview of the language’s history. JavaScript was created in 1995 by
Brandan Eich while he was an engineer at Netscape. Java Script was first released with
Netscape 2 early in 1996. It was originally going to be called LiveScript, but it was renamed in
an ill-fated marketing decision that attempted to capitalize on the popularity of Sun
Microsystem’s Java language – despite the two having very little in common. This has been a
source of confusion ever since.
Several months later, Microsoft released Jscript with Internet Explorer 3. It was a mostly-
compatible JavaScript work-alike. Several months after that, Netscape submitted JavaScript to
Ecma International, a European standard organization, which resulted in the first edition of the
ECMAScript standard that year. The standards organization, which resulted in the first edition
of the ECMAScript edition 4 in 1999, and it has stayed pretty much stable ever since. The
fourth edition was abandoned, due to political differences concerning language complexity.
Many parts of the fourth edition formed the basis for ECMAScript edition 5, published in
December of 2009, and for the 6th major edition of the standard, published in June of 2015.
Because it is more familiar, we will refer to ECMAScript as “JavaScript” from this point on.
Unlike most programming language, the JavaScript language has no concept of input or
output. It is designed to run as a scripting language in a host environment, and it is up to the
host environment to provide mechanisms for communicating with the outside world. The most
common host environment is the browser, but JavaScript interpreters can also be found in a
huge list of other places, including Adobe Acrobat, Adobe Photoshop, SVG images, Yahoo’s
Widget engine, server-side environments such as Node.js, NoSQL databases like the open
source Apache CouchDB, embedded computers, complete desktop environments like GNOME
(one of the most popular GUIs for GNU/Linux operating systems), and others.
Overview
JavaScript is a multi-paradigm, dynamic language with types and operators, standard built-in
objects, and methods. Its syntax is based on the Java and C language – many structures from
those language apply to JavaScript as well. JavaScript supports object-oriented programming
with object prototypes, instead of classes (see more about prototypical inheritance and
ES2015 classes). JavaScript also supports functional programming – because they are objects,
functions may be stored in variables and passed around like any other object.
21
https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
Let’s start off by looking at the build blocks of any language: the types. JavaScript programs
manipulate values, and those values all belong to a type. JavaScript programs manipulate
values, and those values all belong to a type. JavaScript’s types are:
Number
String
Boolean
Function
Object
Symbol (new in ES2015)
…oh, and undefined and null, which are … slightly odd. And Array, which is a special kind of
objects. And Date and RegExp, which are objects that you get for free. And to be technically
accurate, functions are just a special type of object. So the type diagram looks like this:
Number
String
Boolean
Object
o Function
o Array
o Date
o RegExp
null
undefined
And these are some built-in Error types as well. Things are a los easier if we stick with the first
diagram, however, so we’ll discuss the types listed there for now.
Numbers
Numbers in JavaScript are “double-precision 64-bit format IEEE 754 values”, according to the
spec. this has some interesting consequences. There’s no such thing as an integer in JavaScript,
so you have to be a little careful with your arithmetic if you’re used to math in C or Java.
The standard arithmetic operators are supported, including addition, subtraction, modulus (or
remainder) arithmetic, and os forth. There’s also a built-in object that we did not mention
earlier called Math that provides advanced mathematical functions and constants:
1 | M ATH.SIN (3.5);
2 | VAR CIRCUMFERENCE = 2 * M ATH .PI * R;
You can convert a string to an integer using the built-in parseInt() function. This takes the base
for the conversion as an optional second argument, which you should always provide:
In older browsers, strings beginning with a “0” are assumed to be in octal (radix 8), but this
hasn’t been the case since 2013 or so. Unless you’re certain of your string format, you can get
surprising result on those older browsers:
1 | PARSEINT (‘10’); // 8
2 | PARSEINT (‘0 X10’); // 16
Here, we see the parseInt() function treat the first string as octal due to the leading 0, and the
second string as hexadecimal due to the leading “0x”. The hexadecimal notation is still in place;
only octal has been remover.
If you want to convert a binary number to an integer, just change the base:
Similarly, you can parse floating point umbers using the built-in parseFloat() function. Unlike its
parseInt cousin, parseFloat() always uses base 10.
You can also use the unary + operator to convert values to numbers:
1 | + ‘42’; // 42
2 | + ‘010’; // 10
3 | + ‘0X10’; // 16
A special value called NaN (short for “Not a Number”) is returned if the sting is non-numeric:
NaN is toxic: if you provide it as an operand to any mathematical operation, the result will also
be NaN:
1 | NAN + 5; // N AN
You can test for NaN using the built-in isNaN() function:
1 | ISNAN(N AN); // TRUE
1 | 1 / 0; // I NFINITY
2 | -1 / 0; // -I NFINITY
You can test for Infinity, -Infinity and NaN, values using the built-in isFinite() function:
The parseInt() and parseFloat() functions parse a string until they reach a character that isn’t
valid for the specified number format, the return the number parsed up to that point.
However the “+`” operator simply converts the string to NaN if there is an invalid character
contained within it. Just try parsing the string “10.2abc” with each method by yourself in the
console and you’ll understand the differences better.
Strings
String in JavaScript are sequences of Unicode characters. This should be welcome news to
anyone who has had to deal with internationalization. More accurately, they are sequences of
UTF-16 code units; each code unit is represented by a 16-bit number. Each Unicode character
is represented by either 1 or 2 code units.
If you want to represent a single character, you just use a string consisting of that single
character.
To find the length of a string (in code units), access its length property:
1 | ‘HELLO’.LENGTH ; // 5
There’s our first brush with JavaScript objects! Did we mention that you can use strings like
object too? They have methods as well that allow you to manipulate the string and access
information about the string:
1 | ‘HELLO’.CHARAT(0); // “H”
2 | ‘HELLO, WORLD’.REPLACE(‘WORLD’, ‘MARS’; // ”HELLO, MARS ”
3 | ‘HELLO’.TOUPPER CASE(); “HELLO”
Other types
JavaScript distinguishes between null, which is a value that indicates a deliberate non-value
(and is only accessible through the null keyword), and undefined, which is a value of type
undefined that indicates an uninitialized variable – that is, a value hasn’t even been assigned
yet. We’ll talk about variables later, but in JavaScript it is possible to declare a variable without
assigning a valuable to it. If you do this, the variable’s type is undefined. Undefined is actually a
constant.
JavaScript has a Boolean type, with possible values true and false (both of which are
keywords.) Any value can be converted to a Boolean according to the following rules:
1. false, 0, empty strings (“”), NaN, null, and undefined all become false.
2. All other values become true.
You can perform this conversion explicitly using the Boolean() function:
However, this is rarely necessary, as JavaScript will silently perform this coversion when it
expects a Boolean, such as in an if statement (see below). For this reason, we sometimes speak
simply of “true” and “false values,” meaning values that become true and false, respectively,
when converted to Booleans. Alternatively, such values can be called “truthy” and “falsy”,
respectively.
Boolean operation such as && (logical and), ||(logical or), and ! (logical not) are supported; see
below.
Variables
New variables in JavaScript are declared using one of three keywords: let, const, or var.
let allows you to declare block-level variables. The declared variables is available from the
block it is enclosed in.
1 | LET A;
2 | LET NAME = ‘S IMON ’;
const allows you to declare variables whose values are never intended to change. The variable
is available from the block it is declared in.
1 | VAR A;
2 | VAR NAME = ‘S IMON ’;
If you declare a variable without assigning any value to it, its type is undefined.
An important difference between JavaScript and other languages like Java is that in JavaScript,
blocks do not have scope; only functions have a scope. So if a variable is defined using var in a
compound statement (for example inside an if control structure), it will be visible to the entire
function. However, starting with ECMAcript 2015, let and const declarations allow you to
create block-scoped variables.
Operators
JavaScript’s numeric operator are +, -, *, / and % which is the remainder operator (which is the
same as modulo.) Values are assigned using =, and there aare also compound assignment
statements such as += and -=. These extend out to x = x operator y.
1 | X += 5;
2 | X = X + 5;
You can use ++ to increment and decrement respectively. These can be used as a prefix or
postfix operators.
If you add a string to a number (or other value) everything is converted into a string first. This
might trip you up:
If you add a string to a number (or other value) everything is converted into a string first. This
might trip you up:
1 | ‘ 3’ + 4 + 5: // “345”
2 | 3 + 4 + ?5?; // “75”
Comparinsons in JavaScript can be made using <, >, <= and >=. These work for both strings
and numbers. Equality is a little less straightforward. The double-equals operator type coercion
if you give it different types, with sometimes interesting results:
JavaScript also has bitwise operations. If you want them, they’re there.
Control structures
JavaScript has a similar set of control structures to other language in the C family. Conditional
statement are supported by if and else; you can chain them together if you like:
2 | if (name == ?puppies?) {
3 | name += ‘woof?
5 | name += ‘meow’;
6 | } else {
7 | name += ‘!’;
8|}
JavaScript has while loops and do-while loops. The first is good for basic looping; the second
for loops where you wish to ensure that the body of the loop is executed at least once:
1 | while (true) {
2 | // an infinite loop!
3|}
4|
5 | var input;
6 | do {
7 | input = get_input();
8 | } while (inputIsNotValid(input));
JavaScript’s for loop is the same as that in C and Java: it lets you provide the control
information for your loop on a single line.
3|}
JavaScript also contains two others prominent for loops: for… of
3|}
And for…in:
3|}
The &&and || operators use short-circuit logic, which means whether they will execute their
second operand is dependent on the first. This is useful for checking for null objects before
accessing their attribute:
The switch statement can be used for multiple branches based on a number or string:
2 | case ‘draw’:
3| drawIt();
4| break;
5 | case ‘eat’:
6| eatIt();
7| break;
8 | default:
9| doNothing();
10| }
The default clause is optional. You can have expressions in both the switch part and the cases if
ou like; comparisons take place between the two using the == operator:
1 | switch (1 + 3) {
2 | case 1: // fallthrough
3 | case 2:
4| eatIt();
5 | default:
6| neverhappens();
7|}
Objects
JavaScript objects can be thought of as simple collections of name-value pairs. As such, they
are similar to:
Dictionaries in Python.
Hashes in Perl and Ruby.
Hash tables in C and C++.
HashMaps in Java.
Associative arrays in PHP.
The fact that this data structure is so widely used is a testament to its versatility. Since
everything (bar core types) in JavaScript is an object, any JavaScript program naturally involves
a great deal of hash table lookups. It’s a good thing they’re so fast!
The “name” part is JavaScript string, while the value can be any JavaScript value – including
more objects. This allows you to build data structures of arbitrary complexity.
And:
These are semantically equivalent; the second is called object literal syntax and is more
convenient. This syntax is also the core of JSON format and should be preferred at all times.
1 | var obj = {
2 | name: ‘Carrot’,
4 | details: {
5| color: ‘orange’,
6| size: 12
7| }
8 | };
Attribute access can be chained together:
1 | obj.details.color; // orange
2 | obj[‘details’][‘size’]; // 12
2 | this.name = name;
3 | this.age = age;
4|}
5|
6 | // Define an object
9|
Once created, an object’s properties can again be accessed in one of two ways:
1 | // dot notation
2 | obj.name = ‘Simon’;
And…
1 | // bracket notation
2 | obj[‘name’] = ‘Simon’;
These are also semantically equivalent. The second method has the advantage that the name
of the property is provided as a string, which means it can be calculated at run-time. However,
using this method prevents some JavaScript engine and minifier optimizations being applied. It
can also be used to set and get properties with names that are reserved words:
For more on objects and prototypes see Object.prototype. For an explanation of object
prototypes and the object prototype chains see Inheritance and the prototype chain.
Starting in ECMAScript 2015, object keys can be defined by the variable using brackets
notation upon being created {[phoneType]: 12345} is possible instead of just var userPhone =
{}; userphone[phoneType]: 12345} is possible instead of just var userPhone = {};
userPhone[phoneType] = 12345.
Arrays
Arrays in JavaScript are actually a special type of object. They work vey much like regular
objects (numerical properties can naturally be accessed only using [] syntax) but hey have one
magic property called ‘length’ this is always one more than the highest index in the array.
2 | a[0] = ‘dog’;
3 | a[1] = ‘cat’;
4 | a[2] = ‘hen’;
5 | a.length; // 3
2 | a.legth; // 3
Note that array.length isn’t necessarily the number of items in the array. Consider that
following:
2 | a[100]= ‘fox’;
3 | a.length; // 101
Remember – the length of the array is one more than the highest index.
If you query a non-existent array index, you’ll get a value of undefined in return:
If you take the above [] and length into account, you can iterate over an array using the
following for loop:
ES2015 introduced the more concise for…of loop for iterable objects such as arrays:
3|}
You could also iterate over an array using a for…in loop, however this does not iterate over the
array elements, but the array indices. Furthermore, if some added new properties to
Array.prototype, they would also be iterated over by such a loop. Therefore this loop type is
not recommended for arrays.
Another way of iterating over an array that was added with ECMAScript 5 is forEach():
3 | });
1 |a.push(item);
Array come with a number of methods. See also the full documentation for array methods.
Functions
Along with objects, functions are the core component in understanding JavaScript. The most
basic function couldn’t be much simpler:
1 | function add(x, y) {
2 | var total = x + y;
3 | return total;
4|}
This demonstrates a basic function. A JavaScript function can take 0 or more named
parameters. The function body can contain as many statements as you like and can declare its
own variables which are local to that function. The return statement can be used to return a
value at any time, terminating the function. If no return statement is used (or an empty return
with no value), JavaScript returns undefined.
The named parameters turn out to be more like guidelines than anything else. You can call a
function without passing the parameters it expects, in which case they will be set to undefined.
1 | add(); // NaN
You can also pass in more arguments than the function is expecting:
1 | add(2, 3, 4); // 5
That may seem a little silly, but functions have access to an additional variable inside their
body called arguments, which is an array-like objects holding all of the values passed to the
function. Let’s re-write the add function to take as many values as we want:
1 | function add() {
2 | var su = 0;
4| sum += arguments[i];
5| }
6 | return sum;
7|}
8|
9 | add(2, 3, 4, 5); // 14
That’s really not any more useful than writing 2 + 3 + 4 +5 though. Let’s create an averaging
function:
1 | function avg() {
2 | var sum = 0;
4| sum += arguments[i];
5| }
7|}
8|
This is pretty useful, but it does seem a little verbose. To reduce this code a bit more we can
look at substituting the use of the arguments array though Rest parameter syntax. In this way,
we can pass in any number of arguments into the function while keeping our code minimal.
The rest parameter operator is used in function parameter lists with the format: …variable
and it will include within that variable the entire list of uncaptured arguments that the function
was called with. We will also replace the for loop with a for…of loop to return the values
within our variable.
1 | function avg(…args) {
2 | var sum = 0;
4| sum += value;
5| }
7|}
8|
In the above code, the variable args holds all the value that were passed into the function.
It is important to note that wherever the rest parameter operator oprator is places in a
function declaration it will store all arguments after its declaration, but not before. i.e. function
avg/firstValue, …args)will store the first value passed into the function in the firstValue
variable and the remaining arguments in args. That’s another useful language feature but it
does lead us to a new problem. The avg() function takes a comma-separated list of arguments
– but what if you want to find the average of an array? You could just rewrite the function as
follows.
1 | function avgArray(arr) {
2 | var sum = =;
4| sum += arr[i];
5| }
8|
But it would be nice to be able to reuse the function that we’ve already created. Luckily,
JavaScript lets you call a function with an arbitrary array of arguments, using the apply()
method of any function object.
The second argument to apply() is the array to use as arguments; the first will be be discussed
later on. This emphatisizes the fact that function are objects too.
You can achive the same result using the spread operator in the function call.
2 | var sum = 0;
4| sum += arguments[i];
5| }
7 | };
This is semantically equivalent to the function avg() form. It’s extremely powerful, as it lets you
put a full function definition anywhere that you would normally put variables – like block scope
in C:
1 | var a = 1;
2 | var b = 2;
3|
4 | (function() {
5 | var b = 3;
6 | a += b;
7 | })();
8|
9 | a; // 4
10 | b; // 2
JavaScript allows you to call functions recursively. This is particularly useful for dealing with
tree structures, such as those in the browser DOM.
1 | function countChars(elm) {
3| return elm.nodeValue.length;
4| }
5 | var count = 0;
7| count += countChars(child);
8| }
9 | return count;
10 | }
This highlights a potential problem with anonymous functions: how do you call them
recursively if they don’t have a name? JavaScript lets you name expressions for this. You can
use named IFFEs (immediately Invoked Function Expressions) as shown below:
2 | if (elm.NodeType == 3) { // TEXT_NODE
3| return elm.nodeValue.length;
4| }
5 | var count = 0;
7| count += counter(child);
8| }
9 | return count;
10 | })(document.body);
The name provided to a function expression as above is only available to the function’s own
scope. This allows more optimizations to be done by the engine and results in more readable
code. The name also shows up in the debugger and some stack traces, which can save you time
when debugging.
Note that JavaScript functions are themselves objects – like everything else in JavaScript – and
you can add or change properties on them just like we’ve seen earlier in the Objects section.
Custom objects
For a more detailed discussion of object-oriented programming in JavaScript, see Introduction
to Object-Oriented JavaScript.
In classic Object Oriented Programming, objects are collections of data and methods that
operate on that data. JavaScript is a prototype-base language that contains no class statement,
as you’d fin in C++ or Java (this is sometimes confusing for programmers accustomed to
language with a class statement). Instead, JavaScript uses functions as classes. Let’s consider a
person object with first and last name fields. There are two ways in which the name might be
displayed: as “first last” or as “last, first”. Using the functions and objects that we’ve discussed
previously, we could display the date like this:
2 | return {
3| first: first,
4| last: last
5 | }:
6|}
7 | function personFullName(person) {
9|}
12| }
13|
This works, but it’s pretty ugly. You end up with dozens of functions in your global namespace.
What we really need is a way to attach a function to an object. since functions are objects, this
is easy:
2 | return {
3| first: first,
4| last: last,
5| fullName: function() {
7| },
8| fulNameReversed: function() {
10| }
11| };
12| }
13|
Note on the this keyword. Used inside a function, this refers to the current object. What that
means is specified by the way in which you called that function. If you called it using dot
notation or bracket notation on an object, that object becomes this. If dot notation wasn’t
used for the call, this refers to the global object.
1 | var s = makePerson
When we call fullName() alone, without using s.fullName(), this is bound to the global object.
since there are no global variables called first or last we get undefined for each one.
We can take advantage of the this keyword to improve our makePerson function:
2 | this.first = first;
3 | this.last = last;
4 | this.fullName = function() {
6 | };
7 | this.fullNameReversed = function() {
9 | };
10| }
We have introduced another keyword: new. new is strongly related to this. It creates a brand
mew empty object, and then calls the function specified, with this set to that new object.
Notice though that the function specified with this does not return a value but merely modifies
the this object. it’s new that returns the this object to the calling site. Functions that are
designed to be called by new are called constructor functions. Common practice is to capitalize
these functions as a reminder to call them with new.
The improved function still has the same pitfall with calling fullName() alone.
Our person objects are getting better, but there are still some ugly edges to them. Every time
we create a person object we are creating two brand new function objects within it – wouldn’t
it be better if this code was shared?
1 | function personFullName() {
3|}
4 | function personFullNameReversed() {
6 | };
7 | function Person(firs,last) {
8 | this.first = first;
9 | this.last = last;
12| }
That’s better: we are creating the method functions only once, and assigning references to
them inside the constructor. Can we do any better than that? The answer is yes:
2 | this.first = first;
3 | this.last = last;
4|}
5 | Person.prototype.fullName = function() {
6 | return this.first + ‘ ‘ + this.last;
7 | };
8 | Person.prototype.fullNameReversed = function() {
10| };
Person.prototype is an object shared by all instances of Person. It forms part of a lookup chain
(that has a special name, “prototype chain”): any time you attempt to access a property of
Person that isn’t set, JavaScript will check Person.prototype to see if that property of
Person.prototype becomes available to all instances of that constructor via the this object.
This is an incredibly powerful tool. JavaScript lets you modify something’s prototype at any
time in your program, which means you can add extra methods to existing objects at runtime:
3|
4 | Person.prototype.firstNameCaps = function() {
5 | return this.first.toUpperCase();
6 | };
7 | s.firstNameCaps(); // “SIMON”
Interestingly, you can also add things to the prototype of built-in JavaScript objects. Let’s add a
method to String that returns that string in reverse:
1 | var s = ‘Simon’;
3|
4 | String.prototype.reserved = function() {
5 | var = r = ‘ ‘;
7| r += this[i];
8| }
9 | return
10| };
11|
As mentioned before, the prototype forms part of a chain. The root of that chain is
Object.prototype, whose methods include toString() – it is this method that is called when you
try to represent an object as a string. This is useful for debugging our Person objects:
3|
4 | Person.protoype.toString = function() {
6|}
7|
Remember now avg.apply() had a null first arguments? We can revisit that now. The first
argument to apply() is the object that should be treated as ‘this’. For example, here’s a trivial
implementation of new:
3 | constructor.apply(o, args);
4 | return o;
5|}
This isn’t an exact replica of new as it doesn’t set up the prototype chain (it would be difficult
to illustrate). This is not something you use very often, but it’s useful to know about. In this
snippet22, …args (including the ellipsis) is calle the “rest arguments” – as the name implies, this
contains the rest of the arguments.
Calling
22
WR: (n) [extracto of sth published] fragmento, trozo, [scrap of news, information] pedazo, recorte [de
periódico]. https://www.wordreference.com/es/translation.asp?tranword=snippet
1 | var bill = trivialNew(Person, ‘William’, ‘Orange’);
apply() has a sister function named call, which again lets you set this but takes an expanded
argument list as opposed to an array.
1 | function lastNameCaps() {
2 | return this.last.toUpperCase();
3 |}
5 | lastNameCaps.call(s)
7 | s.lastNameCaps = lastNameCaps;
8 | s.lastNameCaps(); // WILLISON
Inner functions
JavaScript function declarations are allowed inside other function. We’ve seen this once
before, with an earlier makePerson() function. An important detail of nested functions in
JavaScript is that they can access variables in their parent function’s scope:
1 | function parentFunc() {
2 | var a = 1;
3|
4 | function nestedFunct() {
6| return a + b;
7|}
8 | return nestedFunc
9|}
This provides a great deal of utility in writing more maintainable code. If a called function relies
on one or two functions that are not useful to any other part of your code, you can nest those
utility functions inside it. This keeps the number of functions that are in the global scope down,
which is always a good thing.
This is also a great counter to the lure of global variables. When writing complex code it is
often tempting to use global variables to share values between multiple functions – which
leads to code that is hard to maintain. Nested functions can share variables in theis parent, so
you can use that mechanism to couple functions together when it makes sense without
polluting your global namespace – “local globals” if you like. This technique should be used
with caution, but it’s a useful ability to have.
Closures
This leads us to one of the most powerful abstractions that JavaScript has to offer – but also
the most potentially confusing. What does this do?
1 | function makeAdder(a) {
2 | return function(b) {
3| return a + b;
4 | };
5|}
8 | add5(6); // ?
9 | add20(7); // ?
The name of the makeAdder() function should give it away: it creates new ‘adder’ functions,
each of which, when called with one argument, adds it to the argument that it was created
with.
What’s happening here is pretty much the same as was happening with the inner functions
earlier on: a function defined inside another function has access to the outer function’s
variables. The only difference here is that the outer function has returned, and hence common
sense would seem to dictate that its local variables no longer exist. But they do exist –
otherwise, the adder functions would be unable to work. What’s more, there are two different
“copies” of makeAdder()’s local variables – one in which a is 5 and the other one where a is 20.
So the result of that function calls is as follows:
1 |add(6); returns 11
2 | add(7); // returns 27
Here’s wha’s actually happening. Whenever JavaScript executes a function, a ‘scope’ object is
created to hold the local variables created within that function. It is initialized with any
variables passed in a s function parameters. This is similar to the global object that all global
variables and functions live in, but with a couple of important differences: firstly, a brand new
scope object is created every time a function stats executing, and secondly, unlike the global
object (which is accessible as this and in browsers as windows) these scope objects cannot be
directly accessed from your JavaScript code. There is no mechanism for iterating over the
properties of the current scope object, for example.
So when makeAdder() is called, a scope object is created with one property: a, which is the
argument passed to the makeAdder() function. makeAdder() then returns a newly created
function. Normally JavaScript’s garbage collector would clean up the scope object created for
makeAdder() at this point, but the returned function maintains a reference back to that scope
object. As a result, the scope object will not be garbage-collected until there are no more
references to the function object that makeAdder() returned.
Scope objects form a chain called the scope chain, similar to the prototype chain used by
JavaScript’s object system.
A closure is the combination of a function and the scope in which it was created. Closures let
you let you save state – as such, they can often be sued in place of objects. You can find
several excellent introductions to closures.
Function Guide23
Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript
procedure-a set of statements that performs a task or calculates a value. To use a function,
you must define it somewhere in the scope from which you wish to call it.
See also the exhaustive reference chapter about JavaScript functions to get to know the
details.
Defining functions
Function declaration
A function definition (also called a function declaration, or function statement) consists of the
function keyword, followed by:
For example, the following code defines a simple function named square:
1 | function square(number) {
3|}
The function square takes one parameter, called number. The function consists of one
statement that says to return the parameter of the function (that is; number) multiplied by
itself. The statement return specifies the value returned by the function:
23
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
1 | return number * number
Primitive parameters (such as a number) are passed to functions by value; the value is passed
to the function, but if the function changes the value of the parameter, this changes is not
reflected globally or in the calling function.
If you pass an object (i.e. a non-primitive value, such as Array or a user-defined object) as a
parameter and the function changes the object’s properties, that change is visible the function,
as show in the following example:
1 | function my Func(theObject) {
2 | theObject.make = ‘Toyota’;
3|}
4|
6 | var x, y,;
7|
9|
10| myFunc(mycar);
Function expressions
While the function declaration above is syntactically a statement, functions can also be created
by a function expression.
Such a function can be anonymous; it does not have to have a name. For example, the
function square could have defined as:
However, a name can be provided with a function expression. Providing a name allows the
function to refer to itself, and also makes it easier to identify the function in a debugger’s stack
traces:
Setup for the Tutorial
Overview
Now that you’re up, lets get an overview of React!
What is React?
React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It lets
you compose complex UIs from small and isolated pieces of code called “components”.
Each has a few different kinds of components, but we’ll star with React.Componet subclasses:
render() {
return (
<div className=”shopping-list”>
<ul>
<li>Instagram</li>
<li>WhatsApp</li>
<li>Oculus</li>
</ul>
</div>
);
We’ll get to the funny XML-like tags soon. We use components to tell React what we want to
see on the screen. When our data changes, React will efficiently update and re-render our
components.
Here, ShoppingLIst is a React components class, or React component type. A component takes
in parameters, called props (short for “properties”), and returns a hierarchy of views to display
via the render method.
The render method returns a description of what you want to see on the screen. React takes
the description and displays the result. In particular, render returns a React element, which is
a lightweight description of what to render. Most React developers use a special syntax called
“JSX” which makes these structures easier to write. The <div /> syntax is transformed at build
time to React.createElement(‘div’). the example above is equivalent to:
);
If you’re curious, createElement() is described in more detail in the API reference, but we
won’t be using it in this tutorial. Instead, we will keep using JSX.
JSX comer with the full power of JavaScript. You can put any JavaScript expressions within
brace inside JSX. Each React element is a JavaScript object that you can store in a variable or
pass around in your program.
The ShoppingList component above only renders built-in DOM components like <div /> and
<li />. But you can compose and render custom React components too. For example, we can
now refer to the whole shopping list by writing <ShopppinList />. Each React component is
encapsulated and can operate independently; this allows you to build complex UIs from simple
components.
This Starter Code is the base of what we’re building. We’ve provided the CSS styling so that
you only need to focus on learning React and programming the tic-tac-toe game.
By inspecting the code, you’ll notice that we have three React components:
Square
Board
Game
The Square component renders a single <button> and the Borad renders 9 squares. The game
component renders a board with placeholder values which we’ll odify late. There are currently
no interactive components.
Function24
Generally speaking, a function is a “subprogram” that ca be called by code external (or internal
in the case of recursion) to the function. Like the program itself, a function is composed of a
sequence of statements called the function body, values can be passed to a function, and the
function will return a value.
In JavaScript, function are first-class objects, because they can have properties and methods
just like any other object. What distinguishes the, from objects is that functions can be called.
In brief, they are Function objects.
For example and explanations, see also the JavaScript guide about functions.
Boolean
Symbol
24
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions