Learn to style HTML using CSS - Learn web development

Learn to style HTML using CSS
=============================

Cascading Style Sheets — or CSS — is the first technology you should start learning after HTML. While HTML is used to define the structure and semantics of your content, CSS is used to style it and lay it out. For example, you can use CSS to alter the font, color, size, and spacing of your content, split it into multiple columns, or add animations and other decorative features.

#### Looking to become a front-end web developer?

 We have put together a course that includes all the essential information you need to
 work towards your goal.

**Get started**

Prerequisites
-------------

You should learn the basics of HTML before attempting any CSS. We recommend that you work through our Introduction to HTML module first.

Once you understand the fundamentals of HTML, we recommend that you learn further HTML and CSS at the same time, moving back and forth between the two topics. This is because HTML is far more interesting and much more fun to learn when you apply CSS, and you can't learn CSS without knowing HTML.

Before starting this topic, you should also be familiar with using computers and using the web passively (i.e., just looking at it, consuming the content). You should have a basic work environment set up, as detailed in Installing basic software, and understand how to create and manage files, as detailed in Dealing with files — both of which are parts of our Getting started with the web complete beginner's module.

It is also recommended that you work through Getting started with the web before proceeding with this topic, especially if you are completely new to web development. However, much of what is covered in its CSS basics article is also covered in our CSS first steps module, albeit in a lot more detail.

Modules
-------

This topic contains the following modules, in a suggested order for working through them. You should start with the first one.

CSS first steps

CSS (Cascading Style Sheets) is used to style and layout web pages — for example, to alter the font, color, size, and spacing of your content, split it into multiple columns, or add animations and other decorative features. This module provides a gentle beginning to your path towards CSS mastery with the basics of how it works, what the syntax looks like, and how you can start using it to add styling to HTML.

CSS building blocks

This module carries on where CSS first steps left off — now you've gained familiarity with the language and its syntax, and got some basic experience with using it, it's time to dive a bit deeper. This module looks at the cascade and inheritance, all the selector types we have available, units, sizing, styling backgrounds and borders, debugging, and lots more.

The aim here is to provide you with a toolkit for writing competent CSS and help you understand all the essential theory, before moving on to more specific disciplines like text styling and CSS layout.

CSS styling text

With the basics of the CSS language covered, the next CSS topic for you to concentrate on is styling text — one of the most common things you'll do with CSS. Here we look at text styling fundamentals, including setting font, boldness, italics, line and letter spacing, drop shadows, and other text features. We round off the module by looking at applying custom fonts to your page, and styling lists and links.

CSS layout

At this point, we've already looked at CSS fundamentals, how to style text, and how to style and manipulate the boxes that your content sits inside. Now it's time to look at how to place your boxes in the right place with respect to the viewport, and one another. We have covered the necessary prerequisites so we can now dive deep into CSS layout, looking at different display settings, modern layout tools like flexbox, CSS grid, and positioning, and some of the legacy techniques you might still want to know about.

Solving common CSS problems
---------------------------

Use CSS to solve common problems provides links to sections of content explaining how to use CSS to solve very common problems when creating a web page.

From the beginning, you'll primarily apply colors to HTML elements and their backgrounds; change the size, shape, and position of elements; and add and define borders on elements. But there's not much you can't do once you have a solid understanding of even the basics of CSS. One of the best things about learning CSS is that once you know the fundamentals, usually you have a pretty good feel for what can and can't be done, even if you don't know how to do it yet!

"CSS is weird"
--------------

CSS works a bit differently from most programming languages and design tools you'll come across. Why does it work the way it does? In the following video, Miriam Suzanne provides a useful explanation of why CSS works as it does, and why it has evolved as it has:

See also
--------

CSS on MDN

The main entry point for CSS documentation on MDN, where you'll find detailed reference documentation for all features of the CSS language. Want to know all the values a property can take? This is a good place to go.


JavaScript — Dynamic client-side scripting - Learn web development

JavaScript — Dynamic client-side scripting
==========================================

JavaScript is a programming language that allows you to implement complex functionalities on web pages. Every time a web page does more than just sit there and display static information for you to look at—displaying timely content updates, interactive maps, animated 2D/3D graphics, scrolling video jukeboxes, or more—you can bet that JavaScript is probably involved.

#### Looking to become a front-end web developer?

 We have put together a course that includes all the essential information you need to
 work towards your goal.

**Get started**

Prerequisites
-------------

JavaScript is arguably more difficult to learn than related technologies such as HTML and CSS. Before attempting to learn JavaScript, you are strongly advised to get familiar with at least these two technologies first, and perhaps others as well. Start by working through the following modules:

* Getting started with the Web
* Introduction to HTML
* Introduction to CSS

Having previous experience with other programming languages might also help.

After getting familiar with the basics of JavaScript, you should be in a position to learn about more advanced topics, for example:

* JavaScript in depth, as taught in our JavaScript guide
* Web APIs
Modules
-------

**Our policy on modern JavaScript**

JavaScript is an actively evolving language and has changed greatly over the years. In particular, the 6th edition of the language (sometimes known as ECMAScript 2015 or ES6), introduced in 2015, added many new features. At the same time, to maintain backwards compatibility with older websites, old features of the language have been retained, even when they are no longer considered good practice.

We think that the features added to JavaScript in ECMAScript 2015 and subsequent versions enable developers to write more readable, reliable, and expressive code, and that it's important to learn about them.

The features we teach in this course are stable and have been supported by all major browsers for several years.

This topic contains the following modules, in a suggested order for working through them.

JavaScript first steps

In our first JavaScript module, we first answer some fundamental questions such as "what is JavaScript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing JavaScript. After that, we discuss some key JavaScript features in detail, such as variables, strings, numbers and arrays.

JavaScript building blocks

In this module, we continue our coverage of all JavaScript's key fundamental features, turning our attention to commonly-encountered types of code block such as conditional statements, loops, functions, and events. You've seen this stuff already in the course, but only in passing — here we'll discuss it all explicitly.

Introducing JavaScript objects

In JavaScript, most things are objects, from core JavaScript features like strings and arrays to the browser APIs built on top of JavaScript. You can even create your own objects to encapsulate related functions and variables into efficient packages. The object-oriented nature of JavaScript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you. Here we teach object theory and syntax in detail, look at how to create your own objects, and explain what JSON data is and how to work with it.

Asynchronous JavaScript

In this module we take a look at asynchronous JavaScript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server.

Client-side web APIs

When writing client-side JavaScript for websites or applications, you won't go very far before you start to use APIs — interfaces for manipulating different aspects of the browser and operating system the site is running on, or even data from other websites or services. In this module we will explore what APIs are, and how to use some of the most common APIs you'll come across often in your development work.

Solving common JavaScript problems
----------------------------------

Solve common problems in your JavaScript code provides a little advice on how to avoid common beginner JavaScript programming mistakes, along with many helpful links to topics that show how to solve common JavaScript programming problems.

See also
--------

JavaScript on MDN

The main entry point for core JavaScript documentation on MDN — this is where you'll find extensive reference docs on all aspects of the JavaScript language, and some advanced tutorials aimed at experienced JavaScripters.

Learn JavaScript

An excellent resource for aspiring web developers — Learn JavaScript in an interactive environment, with short lessons and interactive tests, guided by automated assessment. The first 40 lessons are free.

Coding math

An excellent series of video tutorials to teach the math you need to understand to be an effective programmer, by Keith Peters.


Front-end web developer - Learn web development

Front-end web developer
=======================

Welcome to our front-end web developer learning pathway!

Here we provide you with a structured course that will teach you all you need to know to become a front-end web developer. Work through each section, learning new skills (or improving existing ones) as you go along. Each section includes exercises and assessments to test your understanding before you move forward.

Subjects covered
----------------

The subjects covered are:

* Basic setup and learning how to learn
* Web standards and best practices (such as accessibility and cross-browser compatibility)
* HTML, the language that gives web content structure and meaning
* CSS, the language used to style web pages
* JavaScript, the scripting language used to create dynamic functionality on the web
* Tooling that is used to facilitate modern client-side web development.

You can work through sections in order, but each one is also self-contained. For example, if you already know HTML, you can skip ahead to the CSS section.

Prerequisites
-------------

You don't need any previous knowledge to start this course. All you need is a computer that can run modern web browsers, an internet connection, and a willingness to learn.

If you are not sure if front-end web development is for you, and/or you want a gentle introduction before starting a longer and more complete course, work through our Getting started with the web module first.

Getting help
------------

We have tried to make learning front-end web development as comfortable as possible, but you will probably still get stuck because you don't understand something, or some code is just not working.

Don't panic. We all get stuck, whether we are beginner or professional web developers. The Learning and getting help article provides you with a series of tips for looking up information and helping yourself. If you are still stuck, feel free to post a question on our Discourse forums.

Let's get started. Good luck!

The learning pathway
--------------------

### Getting started

Time to complete: 1.5–2 hours

#### Prerequisites

Nothing except basic computer literacy.

#### How will I know I'm ready to move on?

There are no assessments in this part of the course. But make sure you don't skip. It is important to get you set up and ready to do work for exercises later on in the course.

#### Guides

* Installing basic software — basic tool setup (15 min read)
* Background on the web and web standards (45 min read)
* Learning and getting help (45 min read)
### Semantics and structure with HTML

Time to complete: 35–50 hours

#### Prerequisites

A basic web development environment.

#### How will I know I'm ready to move on?

The assessments in each module are designed to test your knowledge of the subject matter. Completing the assessments confirms that you are ready to move on to the next module.

#### Modules

* Introduction to HTML (15–20 hour read/exercises)
* Multimedia and embedding (15–20 hour read/exercises)
* HTML tables (5–10 hour read/exercises)
### Styling and layout with CSS

Time to complete: 90–120 hours

#### Prerequisites

It is recommended that you have basic HTML knowledge before starting to learn CSS. You should at least study Introduction to HTML first.

#### How will I know I'm ready to move on?

The assessments in each module are designed to test your knowledge of the subject matter. Completing the assessments confirms that you are ready to move on to the next module.

#### Modules

* CSS first steps (10–15 hour read/exercises)
* CSS building blocks (35–45 hour read/exercises)
* CSS styling text (15–20 hour read/exercises)
* CSS layout (30–40 hour read/exercises)

#### Additional resources

* CSS layout cookbook
### Interactivity with JavaScript

Time to complete: 135–185 hours

#### Prerequisites

It is recommended that you have basic HTML knowledge before starting to learn JavaScript. You should at least study Introduction to HTML first.

#### How will I know I'm ready to move on?

The assessments in each module are designed to test your knowledge of the subject matter. Completing the assessments confirms that you are ready to move on to the next module.

#### Modules

* JavaScript first steps (30–40 hour read/exercises)
* JavaScript building blocks (25–35 hour read/exercises)
* Introducing JavaScript objects (25–35 hour read/exercises)
* Client-side web APIs (30–40 hour read/exercises)
* Asynchronous JavaScript (25–35 hour read/exercises)
### Web forms — Working with user data

Time to complete: 40–50 hours

#### Prerequisites

Forms require HTML, CSS, and JavaScript knowledge. Given the complexity of working with forms, it is a dedicated topic.

#### How will I know I'm ready to move on?

The assessments in each module are designed to test your knowledge of the subject matter. Completing the assessments confirms that you are ready to move on to the next module.

#### Modules

* Web forms (40–50 hours)
### Making the web work for everyone

Time to complete: 45–55 hours

#### Prerequisites

It is good to know HTML, CSS, and JavaScript before working through this section. Many of the techniques and best practices touch on multiple technologies.

#### How will I know I'm ready to move on?

The assessments in each module are designed to test your knowledge of the subject matter. Completing the assessments confirms that you are ready to move on to the next module.

#### Modules

* Cross-browser testing (25–30 hour read/exercises)
* Accessibility (20–25 hour read/exercises)
### Modern tooling

Time to complete: 55–90 hours

#### Prerequisites

It is good to know HTML, CSS, and JavaScript before working through this section, as the tools discussed work alongside many of these technologies.

#### How will I know I'm ready to move on?

There are no specific assessment articles in this set of modules. The case study tutorials at the end of the second and third modules prepare you for grasping the essentials of modern tooling.

#### Modules

* Git and GitHub (5 hour read)
* Understanding client-side web development tools (20–25 hour read)
* Understanding client-side JavaScript frameworks (30-60 hour read/exercises)


Web forms — Working with user data - Learn web development

Web forms — Working with user data
==================================

This module provides a series of articles that will help you master the essentials of web forms. Web forms are a very powerful tool for interacting with users — most commonly they are used for collecting data from users, or allowing them to control a user interface. However, for historical and technical reasons, it's not always obvious how to use them to their full potential. In the articles listed below, we'll cover all the essential aspects of Web forms including marking up their HTML structure, styling form controls, validating form data, and submitting data to the server.

#### Looking to become a front-end web developer?

 We have put together a course that includes all the essential information you need to
 work towards your goal.

**Get started**

Prerequisites
-------------

Before starting this module, you should at least work through our Introduction to HTML. At this point you should find the Introductory guides easy to understand, and also be able to make use of our Basic native form controls guide.

Mastering forms however requires more than just HTML knowledge — you also need to learn some specific techniques to style form controls, and some scripting knowledge is required to handle things like validation and creating custom form controls. Therefore, before you look at the other sections listed below we'd recommend that you go away and learn some CSS and JavaScript first.

The above text is a good indicator as to why we've put web forms into its own standalone module, rather than trying to mix bits of it into the HTML, CSS, and JavaScript topic areas — form elements are more complex than most other HTML elements, and they also require a close marriage of related CSS and JavaScript techniques to get the most out of them.

**Note:** If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Glitch.

Introductory guides
-------------------

Your first form

The first article in our series provides your very first experience of creating a web form, including designing a simple form, implementing it using the right HTML elements, adding some very simple styling via CSS, and how data is sent to a server.

How to structure a web form

With the basics out of the way, we now look in more detail at the elements used to provide structure and meaning to the different parts of a form.

The different form controls
---------------------------

Basic native form controls

We start off this section by looking at the functionality of the original HTML `<input>` types in detail, looking at what options are available to collect different types of data.

The HTML5 input types

Here we continue our deep dive into the `<input>` element, looking at the additional input types provided when HTML5 was released, and the various UI controls and data collection enhancements they provide. Additionally, we look at the `<output>` element.

Other form controls

Next we take a look at all the non-`<input>` form controls and associated tools, such as `<select>`, `<textarea>`, `<meter>`, and `<progress>`.

Form styling guides
-------------------

Styling web forms

This article provides an introduction to styling forms with CSS, including all the basics you might need to know for basic styling tasks.

Advanced form styling

Here we look at some more advanced form styling techniques that need to be used when trying to deal with some of the more difficult-to-style form elements.

UI pseudo-classes

An introduction to the UI pseudo-classes enabling HTML form controls to be targeted based on their current state.

Validating and submitting form data
-----------------------------------

Client-side form validation

Sending data is not enough — we also need to make sure that the data users enter into forms is in the correct format to process it successfully, and that it won't break our applications. We also want to help our users to fill out our forms correctly and not get frustrated when trying to use our apps. Form validation helps us achieve these goals — this article tells you what you need to know.

Sending form data

This article looks at what happens when a user submits a form — where does the data go, and how do we handle it when it gets there? We also look at some of the security concerns associated with sending form data.

Advanced articles
-----------------

The following articles aren't essential to the learning pathway, but they'll prove interesting and useful when you've mastered the above techniques and want to know more.

How to build custom form controls

You'll come across some cases where the native form widgets just don't provide what you need, e.g. because of styling or functionality. In such cases, you may need to build your own form widget out of raw HTML. This article explains how you'd do this and the considerations you need to be aware of when doing so, with a practical case study.

Sending forms through JavaScript

This article looks at ways to use a form to assemble an HTTP request and send it via custom JavaScript, rather than standard form submission. It also looks at why you'd want to do this, and the implications of doing so. (See also Using FormData objects.)

CSS property compatibility table for form controls

This last article provides a handy reference allowing you to look up what CSS properties are compatible with what form elements.

See also
--------

* HTML forms element reference
* HTML <input> types reference
* HTML attribute reference
* User input methods and controls


Getting started with the web - Learn web development

Getting started with the web
============================

*Getting started with the web* is a concise series introducing you to the practicalities of web development. You'll set up the tools you need to construct a simple webpage and publish your own simple code.

The story of your first website
-------------------------------

It's a lot of work to create a professional website, so if you're new to web development, we encourage you to start small. You won't build another Facebook right away, but it's not hard to make your own simple website online, so we'll start there.

Guides
------

By working through the articles listed below, you will go from nothing to getting your first webpage online. Let's begin our journey!

Installing basic software

When it comes to tools for building a website, there's a lot to pick from. If you're just starting, you might be confused by the array of code editors, frameworks, and testing tools out there. In this article, we will show you step-by-step how to install the software you need to begin some basic web development.

What will your website look like?

Before you start writing the code for your website, you should plan it first. What information are you showcasing? What fonts and colors are you using? Here we'll outline a simple method that you can follow to plan out your site's content and design.

Dealing with files

A website consists of many files: text content, code, stylesheets, media content, and so on. When you're building a website, you need to assemble these files into a sensible structure and make sure they can talk to one another. This article explains how to set up a sensible file structure for your website and what issues you should be aware of.

HTML basics

HyperText Markup Language (HTML) is 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 on my page? Do I have a data table? Without overwhelming you, this article will provide enough information to make you familiar with HTML.

CSS basics

Cascading Style Sheets (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? In this article, we'll take 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. In this article, we'll give you an idea of what is possible with this exciting language, and how to get started.

Publishing your sample code

Once you have finished writing the code and organizing the files that make up your website, you need to put it all online so people can find it. This article describes how to get your simple sample code online with minimum effort.

How the web works

When you access your favorite website, a lot of complicated things happen in the background that you may not know about. Here we will outline what happens when you view a webpage on your computer.

See also
--------

* Web Demystified: A great series of videos explaining web fundamentals, aimed at complete beginners to web development. Created by Jérémie Patonnier.
* The web and web standards: This article provides some useful background on the Web — how it came about, what web standard technologies are, how they work together, why "web developer" is a great career to choose, and what kinds of best practices you'll learn about through the course.


JavaScript First Steps - Learn web development

JavaScript First Steps
======================

In our first JavaScript module, we first answer some fundamental questions such as "what is JavaScript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing JavaScript. After that, we discuss some key building blocks in detail, such as variables, strings, numbers and arrays.

#### Looking to become a front-end web developer?

 We have put together a course that includes all the essential information you need to
 work towards your goal.

**Get started**

Prerequisites
-------------

Before starting this module, you don't need any previous JavaScript knowledge, but you should have some familiarity with HTML and CSS. You are advised to work through the following modules before starting on JavaScript:

* Getting started with the Web (which includes a really basic JavaScript introduction).
* Introduction to HTML.
* Introduction to CSS.

**Note:** If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Glitch.

Guides
------

What is JavaScript?

Welcome to the MDN beginner's JavaScript course! In this first article we will look at JavaScript from a high level, answering questions such as "what is it?", and "what is it doing?", and making sure you are comfortable with JavaScript's purpose.

A first splash into JavaScript

Now you've learned something about the theory of JavaScript, and what you can do with it, we are going to give you a crash course on the basic features of JavaScript via a completely practical tutorial. Here you'll build up a simple "Guess the number" game, step by step.

What went wrong? Troubleshooting JavaScript

When you built up the "Guess the number" game in the previous article, you may have found that it didn't work. Never fear — this article aims to save you from tearing your hair out over such problems by providing you with some simple tips on how to find and fix errors in JavaScript programs.

Storing the information you need — Variables

After reading the last couple of articles you should now know what JavaScript is, what it can do for you, how you use it alongside other web technologies, and what its main features look like from a high level. In this article, we will get down to the real basics, looking at how to work with the most basic building blocks of JavaScript — Variables.

Basic math in JavaScript — numbers and operators

At this point in the course, we discuss maths in JavaScript — how we can combine operators and other features to successfully manipulate numbers to do our bidding.

Handling text — strings in JavaScript

Next, we'll turn our attention to strings — this is what pieces of text are called in programming. In this article, we'll look at all the common things that you really ought to know about strings when learning JavaScript, such as creating strings, escaping quotes in strings, and joining them together.

Useful string methods

Now we've looked at the very basics of strings, let's move up a gear and start thinking about what useful operations we can do on strings with built-in methods, such as finding the length of a text string, joining and splitting strings, substituting one character in a string for another, and more.

Arrays

In the final article of this module, we'll look at arrays — a neat way of storing a list of data items under a single variable name. Here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.

Assessments
-----------

The following assessment will test your understanding of the JavaScript basics covered in the guides above.

Silly story generator

In this assessment, you'll be tasked with taking some of the knowledge you've picked up in this module's articles and applying it to creating a fun app that generates random silly stories. Have fun!

See also
--------

Learn JavaScript

An excellent resource for aspiring web developers — Learn JavaScript in an interactive environment, with short lessons and interactive tests, guided by automated assessment. The first 40 lessons are free, and the complete course is available for a small one-time payment.


JavaScript building blocks - Learn web development

JavaScript building blocks
==========================

In this module, we continue our coverage of all JavaScript's key fundamental features, turning our attention to commonly-encountered types of code blocks such as conditional statements, loops, functions, and events. You've seen this stuff already in the course, but only in passing — here we'll discuss it all explicitly.

#### Looking to become a front-end web developer?

 We have put together a course that includes all the essential information you need to
 work towards your goal.

**Get started**

Prerequisites
-------------

Before starting this module, you should have some familiarity with the basics of HTML and CSS, and you should have also worked through our previous module, JavaScript first steps.

**Note:** If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Glitch.

Guides
------

Making decisions in your code — conditionals

In any programming language, code needs to make decisions and carry out actions accordingly depending on different inputs. For example, in a game, if the player's number of lives is 0, then it's game over. In a weather app, if it is being looked at in the morning, show a sunrise graphic; show stars and a moon if it is night. In this article we'll explore how conditional structures work in JavaScript.

Looping code

Sometimes you need a task done more than once in a row. For example, looking through a list of names. In programming, loops perform this job very well. Here we will look at loop structures in JavaScript.

Functions — reusable blocks of code

Another essential concept in coding is **functions. Functions** allow you to store a piece of code that does a single task inside a defined block, and then call that code whenever you need it using a single short command — rather than having to type out the same code multiple times. In this article we'll explore fundamental concepts behind functions such as basic syntax, how to invoke and define functions, scope, and parameters.

Build your own function

With most of the essential theory dealt with previously, this article provides a practical experience. Here you'll get some practice with building up your own custom function. Along the way, we'll also explain some further useful details of dealing with functions.

Function return values

The last essential concept you must know about a function is return values. Some functions don't return a significant value after completion, but others do. It's important to understand what their values are, how to make use of them in your code, and how to make your own custom functions return useful values.

Introduction to events

Events are actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond to them in some way if desired. For example if the user clicks a button on a webpage, you might want to respond to that action by displaying an information box. In this final article we will discuss some important concepts surrounding events, and look at how they work in browsers.

Assessments
-----------

The following assessment will test your understanding of the JavaScript basics covered in the guides above.

Image gallery

Now that we've looked at the fundamental building blocks of JavaScript, we'll test your knowledge of loops, functions, conditionals and events by building a fairly common item you'll see on a lot of websites — a JavaScript-powered image gallery.

See also
--------

Learn JavaScript

An excellent resource for aspiring web developers — Learn JavaScript in an interactive environment, with short lessons and interactive tests, guided by automated assessment. The first 40 lessons are free, and the complete course is available for a small one-time payment.


Introducing JavaScript objects - Learn web development

Introducing JavaScript objects
==============================

In JavaScript, most things are objects, from core JavaScript features like arrays to the browser APIs built on top of JavaScript. You can even create your own objects to encapsulate related functions and variables into efficient packages and act as handy data containers. The object-based nature of JavaScript is important to understand if you want to go further with your knowledge of the language, therefore we've provided this module to help you. Here we teach object theory and syntax in detail, then look at how to create your own objects.

#### Looking to become a front-end web developer?

 We have put together a course that includes all the essential information you need to
 work towards your goal.

**Get started**

Prerequisites
-------------

Before starting this module, you should have some familiarity with HTML and CSS. You are advised to work through the Introduction to HTML and Introduction to CSS modules before starting on JavaScript.

You should also have some familiarity with JavaScript basics before looking at JavaScript objects in detail. Before attempting this module, work through JavaScript first steps and JavaScript building blocks.

**Note:** If you are working on a computer/tablet/other devices where you are not able to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Glitch.

Guides
------

Object basics

In the first article looking at JavaScript objects, we'll look at fundamental JavaScript object syntax, and revisit some JavaScript features we've already looked at earlier on in the course, reiterating the fact that many of the features you've already dealt with are in fact objects.

Object prototypes

Prototypes are the mechanism by which JavaScript objects inherit features from one another, and they work differently from inheritance mechanisms in classical object-oriented programming languages. In this article, we explore how prototype chains work.

Object-oriented programming

In this article, we'll describe some of the basic principles of "classical" object-oriented programming, and look at the ways it is different from the prototype model in JavaScript.

Classes in JavaScript

JavaScript provides some features for people wanting to implement "classical" object-oriented programs, and in this article, we'll describe these features.

Working with JSON data

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax, which is commonly used for representing and transmitting data on the web (i.e., sending some data from the server to the client, so it can be displayed on a web page). You'll come across it quite often, so in this article, we give you all you need to work with JSON using JavaScript, including parsing the JSON so you can access data items within it, and writing your own JSON.

Object building practice

In previous articles we looked at all the essential JavaScript object theory and syntax details, giving you a solid base to start from. In this article we dive into a practical exercise, giving you some more practice in building custom JavaScript objects, which produce something fun and colorful — some colored bouncing balls.

Assessments
-----------

Adding features to our bouncing balls demo

In this assessment, you are expected to use the bouncing balls demo from the previous article as a starting point, and add some new and interesting features to it.

See also
--------

Learn JavaScript

An excellent resource for aspiring web developers — Learn JavaScript in an interactive environment, with short lessons and interactive tests, guided by automated assessment. The first 40 lessons are free, and the complete course is available for a small one-time payment.


Solve common problems in your JavaScript code - Learn web development

Solve common problems in your JavaScript code
=============================================

The following links point to solutions to common problems you may encounter when writing JavaScript.

Common beginner's mistakes
--------------------------

### Correct spelling and casing

If your code doesn't work and/or the browser complains that something is undefined, check that you've spelt all your variable names, function names, etc. correctly.

Some common built-in browser functions that cause problems are:

| Correct | Wrong |
| --- | --- |
| `getElementsByTagName()` | `getElementByTagName()` |
| `getElementsByName()` | `getElementByName()` |
| `getElementsByClassName()` | `getElementByClassName()` |
| `getElementById()` | `getElementsById()` |

### Semicolon position

You need to make sure you don't place any semicolons incorrectly. For example:

| Correct | Wrong |
| --- | --- |
| `elem.style.color = 'red';` | `elem.style.color = 'red;'` |

### Functions

There are a number of things that can go wrong with functions.

One of the most common errors is to declare the function, but not call it anywhere. For example:

```js
function myFunction() {
  alert("This is my function.");
}
```

This code won't do anything unless you call it with the following statement:

```js
myFunction();
```

#### Function scope

Remember that functions have their own scope — you can't access a variable value set inside a function from outside the function, unless you declared the variable globally (i.e. not inside any functions), or return the value from the function.

#### Running code after a return statement

Remember also that when you return from a function, the JavaScript interpreter exits the function — no code after the return statement will run.

In fact, some browsers (like Firefox) will give you an error message in the developer console if you have code after a return statement. Firefox gives you "unreachable code after return statement".

### Object notation versus normal assignment

When you assign something normally in JavaScript, you use a single equals sign, e.g.:

```js
const myNumber = 0;
```

With Objects, however, you need to take care to use the correct syntax. The object must be surrounded by curly braces, member names must be separated from their values using colons, and members must be separated by commas. For example:

```js
const myObject = {
  name: "Chris",
  age: 38,
};
```

Basic definitions
-----------------

* What is JavaScript?
* What is a variable?
* What are strings?
* What is an array?
* What is a loop?
* What is a function?
* What is an event?
* What is an object?
* What is JSON?
* What is a web API?
* What is the DOM?
Basic use cases
---------------

### General

* How do you add JavaScript to your page?
* How do you add comments to JavaScript code?
### Variables

* How do you declare a variable?
* How do you initialize a variable with a value?
* How do you update a variable's value? (also see Assignment operators)
* What data types can values have in JavaScript?
* What does 'loosely typed' mean?
### Math

* What types of number do you have to deal with in web development?
* How do you do basic math in JavaScript?
* What is operator precedence, and how is it handled in JavaScript?
* How do you increment and decrement values in JavaScript?
* How do you compare values in JavaScript? (e.g. to see which one is bigger, or to see if one value is equal to another).
### Strings

* How do you create a string in JavaScript?
* Do you have to use single quotes or double quotes?
* How do you escape characters in strings?
* How do you join strings together?
* Can you join strings and numbers together?
* How do you find the length of a string?
* How do you find what character is at a certain position in a string?
* How do you find and extract a specific substring from a string?
* How do you change the case of a string?
* How do you replace one specific substring with another?
### Arrays

* How do you create an array?
* How do you access and modify the items in an array? (this includes multidimensional arrays)
* How do you find the length of an array?
* How do you add items to an array?
* How do you remove items from an array?
* How do you split a string into array items, or join array items into a string?
### Debugging JavaScript

* What are the basic types of error?
* What are browser developer tools, and how do you access them?
* How do you log a value to the JavaScript console?
* How do you use breakpoints and other JavaScript debugging features?

For more information on JavaScript debugging, see Handling common JavaScript problems. Also, see Other common errors for a description of common errors.

### Making decisions in code

* How do you execute different blocks of code, depending on a variable's value or other condition?
* How do you use if ...else statements?
* How do you nest one decision block inside another?
* How do you use AND, OR, and NOT operators in JavaScript?
* How do you conveniently handle a large number of choices for one condition?
* How do you use a ternary operator to make a quick choice between two options based on a true or false test?
### Looping/iteration

* How do you run the same bit of code over and over again?
* How do you exit a loop before the end if a certain condition is met?
* How do you skip to the next iteration of a loop if a certain condition is met?
* How do you use while and do...while loops?
Intermediate use cases
----------------------

### Functions

* How do you find functions in the browser?
* What is the difference between a function and a method?
* How do you create your own functions?
* How do you run (call, or invoke) a function?
* What is an anonymous function?
* How do you specify parameters (or arguments) when invoking a function?
* What is function scope?
* What are return values, and how do you use them?
### Objects

* How do you create an object?
* What is dot notation?
* What is bracket notation?
* How do you get and set the methods and properties of an object?
* What is `this`, in the context of an object?
* What is object-oriented programming?
* What are constructors and instances, and how do you create them?
* What different ways are there to create objects in JavaScript?
### JSON

* How do you structure JSON data, and read it from JavaScript?
* How can you load a JSON file into a page?
* How do you convert a JSON object to a text string, and back again?
### Events

* What are event handlers and how do you use them?
* What are inline event handlers?
* What does the `addEventListener()` function do, and how do you use it?
* Which mechanism should I use to add event code to my web pages?
* What are event objects, and how do you use them?
* How do you prevent default event behavior?
* How do events fire on nested elements? (event propagation, also related — event bubbling and capturing)
* What is event delegation, and how does it work?
### Object-oriented JavaScript

* What are object prototypes?
* What is the constructor property, and how can you use it?
* How do you add methods to the constructor?
* How do you create a new constructor that inherits its members from a parent constructor?
* When should you use inheritance in JavaScript?
### Web APIs

* How do you manipulate the DOM (e.g. adding or removing elements) using JavaScript?


Client-side web APIs - Learn web development

Client-side web APIs
====================

When writing client-side JavaScript for websites or applications, you will quickly encounter **Application Programming Interfaces** (**APIs**). APIs are programming features for manipulating different aspects of the browser and operating system the site is running on, or manipulating data from other websites or services. In this module, we will explore what APIs are, and how to use some of the most common APIs you'll come across often in your development work.

#### Looking to become a front-end web developer?

 We have put together a course that includes all the essential information you need to
 work towards your goal.

**Get started**

Prerequisites
-------------

To get the most out of this module, you should have worked your way through the previous JavaScript modules in the series (First steps, Building blocks, and JavaScript objects). Those modules typically involve simple API usage, as it is often difficult to write client-side JavaScript examples without them. For this tutorial, we will assume that you are knowledgeable about the core JavaScript language, and we will explore common Web APIs in a bit more detail.

Basic knowledge of HTML and CSS would also be useful.

**Note:** If you are working on a device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Glitch.

Guides
------

Introduction to web APIs

First up, we'll start by looking at APIs from a high level — what are they, how do they work, how do you use them in your code, and how are they structured? We'll also take a look at what the different main classes of APIs are, and what kind of uses they have.

Manipulating documents

When writing web pages and apps, one of the most common things you'll want to do is manipulate web documents in some way. This is usually done by using the Document Object Model (DOM), a set of APIs for controlling HTML and styling information that makes heavy use of the `Document` object. In this article, we'll look at how to use the DOM in detail, along with some other interesting APIs that can alter your environment in interesting ways.

Fetching data from the server

Another very common task in modern websites and applications is retrieving individual data items from the server to update sections of a webpage without having to load an entirely new page. This seemingly small detail has had a huge impact on the performance and behavior of sites. In this article, we'll explain the concept, and look at technologies that make it possible, such as `XMLHttpRequest` and the Fetch API.

Third party APIs

The APIs we've covered so far are built into the browser, but not all APIs are. Many large websites and services such as Google Maps, Twitter, Facebook, PayPal, etc. provide APIs allowing developers to make use of their data (e.g. displaying your twitter stream on your blog) or services (e.g. displaying custom Google Maps on your site, or using Facebook login to log in your users). This article looks at the difference between browser APIs and 3rd party APIs and shows some typical uses of the latter.

Drawing graphics

The browser contains some very powerful graphics programming tools, from the Scalable Vector Graphics (SVG) language, to APIs for drawing on HTML `<canvas>` elements, (see The Canvas API and WebGL). This article provides an introduction to the Canvas API, and further resources to allow you to learn more.

Video and audio APIs

HTML comes with elements for embedding rich media in documents — `<video>` and `<audio>` — which in turn come with their own APIs for controlling playback, seeking, etc. This article shows you how to do common tasks such as creating custom playback controls.

Client-side storage

Modern web browsers feature a number of different technologies that allow you to store data related to websites and retrieve it when necessary allowing you to persist data long term, save sites offline, and more. This article explains the very basics of how these work.


Asynchronous JavaScript - Learn web development

Asynchronous JavaScript
=======================

In this module, we take a look at asynchronous JavaScript, why it is important, and how it can be used to effectively handle potential blocking operations, such as fetching resources from a server.

#### Looking to become a front-end web developer?

 We have put together a course that includes all the essential information you need to
 work towards your goal.

**Get started**

Prerequisites
-------------

Asynchronous JavaScript is a fairly advanced topic, and you are advised to work through JavaScript first steps and JavaScript building blocks modules before attempting this.

**Note:** If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you can try out (most of) the code examples in an online coding program such as JSBin or Glitch.

Guides
------

Introducing asynchronous JavaScript

In this article, we'll learn about **synchronous** and **asynchronous** programming, why we often need to use asynchronous techniques, and the problems related to the way asynchronous functions have historically been implemented in JavaScript.

How to use promises

Here we'll introduce promises and show how to use promise-based APIs. We'll also introduce the `async` and `await` keywords.

Implementing a promise-based API

This article will outline how to implement your own promise-based API.

Introducing workers

Workers enable you to run certain tasks in a separate thread to keep your main code responsive. In this article, we'll rewrite a long-running synchronous function to use a worker.

Assessments
-----------

Sequencing animations

The assessment asks you to use promises to play a set of animations in a particular sequence.

See also
--------

* Asynchronous Programming from the fantastic Eloquent JavaScript online book by Marijn Haverbeke.


Adding features to our bouncing balls demo - Learn web development

Adding features to our bouncing balls demo
==========================================

* Previous
* Overview: Objects

In this assessment, you are expected to use the bouncing balls demo from the previous article as a starting point, and add some new and interesting features to it.

|  |  |
| --- | --- |
| Prerequisites: |
 Before attempting this assessment you should have already worked through
 all the articles in this module.
  |
| Objective: |
 To test comprehension of JavaScript objects and object-oriented
 constructs
  |

Starting point
--------------

To get this assessment started, make a local copy of index-finished.html, style.css, and main-finished.js from our last article in a new directory in your local computer.

Alternatively, you could use an online editor such as CodePen, JSFiddle, or Glitch. You could paste the HTML, CSS and JavaScript into one of these online editors. If the online editor you are using doesn't have a separate JavaScript panel, feel free to put it inline in a `<script>` element inside the HTML page.

**Note:** If you get stuck, you can reach out to us in one of our communication channels.

Hints and tips
--------------

A couple of pointers before you get started.

* This assessment is quite challenging. Read the whole assessment before you start coding, and take each step slowly and carefully.
* It might be a good idea to save a separate copy of the demo after you get each stage working, so you can refer back to it if you find yourself in trouble later on.
Project brief
-------------

Our bouncy ball demo is fun, but now we want to make it a little bit more interactive by adding a user-controlled evil circle, which will eat the balls if it catches them. We also want to test your object-building skills by creating a generic `Shape()` object that our balls and evil circle can inherit from. Finally, we want to add a score counter to track the number of balls left to capture.

The following screenshot gives you an idea of what the finished program should look like:

![Screenshot of the bouncing balls demo page. A white-outlined circle is visible in addition to the colored balls, and the text "Ball count: 23" is visible under the heading.](/en-US/docs/Learn/JavaScript/Objects/Adding_bouncing_balls_features/bouncing-evil-circle.png)

To give you more of an idea, have a look at the finished example (no peeking at the source code!)

Steps to complete
-----------------

The following sections describe what you need to do.

### Create a Shape class

First of all, create a new `Shape` class. This has only a constructor. The `Shape` constructor should define the `x`, `y`, `velX`, and `velY` properties in the same way as the `Ball()` constructor did originally, but not the `color` and `size` properties.

The `Ball` class should be made to derive from `Shape` using `extends`. The constructor for `Ball` should:

* take the same arguments as before: `x`, `y`, `velX`, `velY`, `size`, and `color`
* call the `Shape` constructor using `super()`, passing in the `x`, `y`, `velX`, and `velY` arguments
* initialize its own `color` and `size` properties from the parameters it is given.

The `Ball` constructor should define a new property called `exists`, which is used to track whether the balls exist in the program (have not been eaten by the evil circle). This should be a boolean (`true`/`false`), initialized to `true` in the constructor.

The `collisionDetect()` method of the `Ball` class needs a small update. A ball needs to be considered for collision detection only if the `exists` property is `true`. So, replace the existing `collisionDetect()` code with the following code:

```js
collisionDetect() {
  for (const ball of balls) {
    if (!(this === ball) && ball.exists) {
      const dx = this.x - ball.x;
      const dy = this.y - ball.y;
      const distance = Math.sqrt(dx \* dx + dy \* dy);

      if (distance < this.size + ball.size) {
        ball.color = this.color = randomRGB();
      }
    }
  }
}
```

As discussed above, the only addition is to check if the ball exists — by using `ball.exists` in the `if` conditional.

The ball `draw()` and `update()` method definitions should be able to stay exactly the same as they were before.

At this point, try reloading the code — it should work just the same as it did before, with our redesigned objects.

### Defining EvilCircle

Now it's time to meet the bad guy — the `EvilCircle()`! Our game is only going to involve one evil circle, but we are still going to define it using a constructor that inherits from `Shape()`, to give you some practice. You might want to add another circle to the app later on that can be controlled by another player, or have several computer-controlled evil circles. You're probably not going to take over the world with a single evil circle, but it will do for this assessment.

Create a definition for an `EvilCircle` class. It should inherit from `Shape` using `extends`.

#### EvilCircle constructor

The constructor for `EvilCircle` should:

* be passed just `x`, `y` arguments
* pass the `x`, `y` arguments up to the `Shape` superclass along with values for `velX` and `velY` hardcoded to 20. You should do this with code like `super(x, y, 20, 20);`
* set `color` to `white` and `size` to `10`.

Finally, the constructor should set up the code enabling the user to move the evil circle around the screen:

```js
window.addEventListener("keydown", (e) => {
  switch (e.key) {
    case "a":
      this.x -= this.velX;
      break;
    case "d":
      this.x += this.velX;
      break;
    case "w":
      this.y -= this.velY;
      break;
    case "s":
      this.y += this.velY;
      break;
  }
});
```

This adds a `keydown` event listener to the `window` object so that when a key is pressed, the event object's `key` property is consulted to see which key is pressed. If it is one of the four specified keys, then the evil circle will move left/right/up/down.

### Defining methods for EvilCircle

The `EvilCircle` class should have three methods, as described below.

#### draw()

This method has the same purpose as the `draw()` method for `Ball`: it draws the object instance on the canvas. The `draw()` method for `EvilCircle` will work in a very similar way, so you can start by copying the `draw()` method for `Ball`. You should then make the following changes:

* We want the evil circle to not be filled in, but rather just have an outer line (stroke). You can achieve this by updating `fillStyle` and `fill()` to `strokeStyle` and `stroke()` respectively.
* We also want to make the stroke a bit thicker, so you can see the evil circle a bit more easily. This can be achieved by setting a value for `lineWidth` somewhere after the `beginPath()` call (3 will do).

#### checkBounds()

This method will do the same thing as the first part of the `update()` method for `Ball` — look to see whether the evil circle is going to go off the edge of the screen, and stop it from doing so. Again, you can mostly just copy the `update()` method for `Ball`, but there are a few changes you should make:

* Get rid of the last two lines — we don't want to automatically update the evil circle's position on every frame, because we will be moving it in some other way, as you'll see below.
* Inside the `if ()` statements, if the tests return true we don't want to update `velX`/`velY`; we want to instead change the value of `x`/`y` so the evil circle is bounced back onto the screen slightly. Adding or subtracting (as appropriate) the evil circle's `size` property would make sense.

#### collisionDetect()

This method will act in a very similar way to the `collisionDetect()` method for `Ball` method, so you can use a copy of that as the basis of this new method. But there are a couple of differences:

* In the outer `if` statement, you no longer need to check whether the current ball in the iteration is the same as the ball that is doing the checking — because it is no longer a ball, it is the evil circle! Instead, you need to do a test to see if the ball being checked exists (with which property could you do this with?). If it doesn't exist, it has already been eaten by the evil circle, so there is no need to check it again.
* In the inner `if` statement, you no longer want to make the objects change color when a collision is detected — instead, you want to set any balls that collide with the evil circle to not exist any more (again, how do you think you'd do that?).
### Bringing the evil circle into the program

Now we've defined the evil circle, we need to actually make it appear in our scene. To do this, you need to make some changes to the `loop()` function.

* First of all, create a new evil circle object instance (specifying the necessary parameters). You only need to do this once, not on every iteration of the loop.
* At the point where you loop through every ball and call the `draw()`, `update()`, and `collisionDetect()` functions for each one, make it so that these functions are only called if the current ball exists.
* Call the evil circle instance's `draw()`, `checkBounds()`, and `collisionDetect()` methods on every iteration of the loop.
### Implementing the score counter

To implement the score counter, follow the following steps:

1. In your HTML file, add a `<p>` element just below the h1 element containing the text "Ball count: ".
2. In your CSS file, add the following rule at the bottom:

```css
p {
  position: absolute;
  margin: 0;
  top: 35px;
  right: 5px;
  color: #aaa;
}
```

3. In your JavaScript, make the following updates:
    * Create a variable that stores a reference to the paragraph.
    * Keep a count of the number of balls on screen in some way.
    * Increment the count and display the updated number of balls each time a ball is added to the scene.
    * Decrement the count and display the updated number of balls each time the evil circle eats a ball (causes it not to exist).
* Previous
* Overview: Objects


Object prototypes - Learn web development

Object prototypes
=================

* Previous
* Overview: Objects
* Next

Prototypes are the mechanism by which JavaScript objects inherit features from one another. In this article, we explain what a prototype is, how prototype chains work, and how a prototype for an object can be set.

|  |  |
| --- | --- |
| Prerequisites: |
 Understanding JavaScript functions, familiarity with JavaScript basics
 (see
 First steps and
 Building blocks), and OOJS basics (see
 Introduction to objects).
  |
| Objective: |
 To understand JavaScript object prototypes, how prototype chains work,
 and how to set the prototype of an object.
  |

The prototype chain
-------------------

In the browser's console, try creating an object literal:

```js
const myObject = {
  city: "Madrid",
  greet() {
    console.log(`Greetings from ${this.city}`);
  },
};

myObject.greet(); // Greetings from Madrid
```

This is an object with one data property, `city`, and one method, `greet()`. If you type the object's name *followed by a period* into the console, like `myObject.`, then the console will pop up a list of all the properties available to this object. You'll see that as well as `city` and `greet`, there are lots of other properties!
```

__defineGetter__
__defineSetter__
__lookupGetter__
__lookupSetter__
__proto__
city
constructor
greet
hasOwnProperty
isPrototypeOf
propertyIsEnumerable
toLocaleString
toString
valueOf
```

Try accessing one of them:

```js
myObject.toString(); // "[object Object]"
```

It works (even if it's not obvious what `toString()` does).

What are these extra properties, and where do they come from?

Every object in JavaScript has a built-in property, which is called its **prototype**. The prototype is itself an object, so the prototype will have its own prototype, making what's called a **prototype chain**. The chain ends when we reach a prototype that has `null` for its own prototype.

**Note:** The property of an object that points to its prototype is **not** called `prototype`. Its name is not standard, but in practice all browsers use `__proto__`. The standard way to access an object's prototype is the `Object.getPrototypeOf()` method.

When you try to access a property of an object: if the property can't be found in the object itself, the prototype is searched for the property. If the property still can't be found, then the prototype's prototype is searched, and so on until either the property is found, or the end of the chain is reached, in which case `undefined` is returned.

So when we call `myObject.toString()`, the browser:

* looks for `toString` in `myObject`
* can't find it there, so looks in the prototype object of `myObject` for `toString`
* finds it there, and calls it.

What is the prototype for `myObject`? To find out, we can use the function `Object.getPrototypeOf()`:

```js
Object.getPrototypeOf(myObject); // Object { }
```

This is an object called `Object.prototype`, and it is the most basic prototype, that all objects have by default. The prototype of `Object.prototype` is `null`, so it's at the end of the prototype chain:

![Prototype chain for myObject](/en-US/docs/Learn/JavaScript/Objects/Object_prototypes/myobject-prototype-chain.svg)

The prototype of an object is not always `Object.prototype`. Try this:

```js
const myDate = new Date();
let object = myDate;

do {
  object = Object.getPrototypeOf(object);
  console.log(object);
} while (object);

// Date.prototype
// Object { }
// null
```

This code creates a `Date` object, then walks up the prototype chain, logging the prototypes. It shows us that the prototype of `myDate` is a `Date.prototype` object, and the prototype of *that* is `Object.prototype`.

![Prototype chain for myDate](/en-US/docs/Learn/JavaScript/Objects/Object_prototypes/mydate-prototype-chain.svg)

 In fact, when you call familiar methods, like `myDate2.getMonth()`,
 you are calling a method that's defined on `Date.prototype`.

Shadowing properties
--------------------

What happens if you define a property in an object, when a property with the same name is defined in the object's prototype? Let's see:

```js
const myDate = new Date(1995, 11, 17);

console.log(myDate.getYear()); // 95

myDate.getYear = function () {
  console.log("something else!");
};

myDate.getYear(); // 'something else!'
```

This should be predictable, given the description of the prototype chain. When we call `getYear()` the browser first looks in `myDate` for a property with that name, and only checks the prototype if `myDate` does not define it. So when we add `getYear()` to `myDate`, then the version in `myDate` is called.

This is called "shadowing" the property.

Setting a prototype
-------------------

There are various ways of setting an object's prototype in JavaScript, and here we'll describe two: `Object.create()` and constructors.

### Using Object.create

The `Object.create()` method creates a new object and allows you to specify an object that will be used as the new object's prototype.

Here's an example:

```js
const personPrototype = {
  greet() {
    console.log("hello!");
  },
};

const carl = Object.create(personPrototype);
carl.greet(); // hello!
```

Here we create an object `personPrototype`, which has a `greet()` method. We then use `Object.create()` to create a new object with `personPrototype` as its prototype. Now we can call `greet()` on the new object, and the prototype provides its implementation.

### Using a constructor

In JavaScript, all functions have a property named `prototype`. When you call a function as a constructor, this property is set as the prototype of the newly constructed object (by convention, in the property named `__proto__`).

So if we set the `prototype` of a constructor, we can ensure that all objects created with that constructor are given that prototype:

```js
const personPrototype = {
  greet() {
    console.log(`hello, my name is ${this.name}!`);
  },
};

function Person(name) {
  this.name = name;
}

Object.assign(Person.prototype, personPrototype);
// or
// Person.prototype.greet = personPrototype.greet;
```

Here we create:

* an object `personPrototype`, which has a `greet()` method
* a `Person()` constructor function which initializes the name of the person to create.

We then put the methods defined in `personPrototype` onto the `Person` function's `prototype` property using Object.assign.

After this code, objects created using `Person()` will get `Person.prototype` as their prototype, which automatically contains the `greet` method.

```js
const reuben = new Person("Reuben");
reuben.greet(); // hello, my name is Reuben!
```

This also explains why we said earlier that the prototype of `myDate` is called `Date.prototype`: it's the `prototype` property of the `Date` constructor.

### Own properties

The objects we create using the `Person` constructor above have two properties:

* a `name` property, which is set in the constructor, so it appears directly on `Person` objects
* a `greet()` method, which is set in the prototype.

It's common to see this pattern, in which methods are defined on the prototype, but data properties are defined in the constructor. That's because methods are usually the same for every object we create, while we often want each object to have its own value for its data properties (just as here where every person has a different name).

Properties that are defined directly in the object, like `name` here, are called **own properties**, and you can check whether a property is an own property using the static `Object.hasOwn()` method:

```js
const irma = new Person("Irma");

console.log(Object.hasOwn(irma, "name")); // true
console.log(Object.hasOwn(irma, "greet")); // false
```

**Note:** You can also use the non-static `Object.hasOwnProperty()` method here, but we recommend that you use `Object.hasOwn()` if you can.

Prototypes and inheritance
--------------------------

Prototypes are a powerful and very flexible feature of JavaScript, making it possible to reuse code and combine objects.

In particular they support a version of **inheritance**. Inheritance is a feature of object-oriented programming languages that lets programmers express the idea that some objects in a system are more specialized versions of other objects.

For example, if we're modeling a school, we might have *professors* and *students*: they are both *people*, so have some features in common (for example, they both have names), but each might add extra features (for example, professors have a subject that they teach), or might implement the same feature in different ways. In an OOP system we might say that professors and students both **inherit from** people.

You can see how in JavaScript, if `Professor` and `Student` objects can have `Person` prototypes, then they can inherit the common properties, while adding and redefining those properties which need to differ.

In the next article we'll discuss inheritance along with the other main features of object-oriented programming languages, and see how JavaScript supports them.

Summary
-------

This article has covered JavaScript object prototypes, including how prototype object chains allow objects to inherit features from one another, the prototype property and how it can be used to add methods to constructors, and other related topics.

In the next article we'll look at the concepts underlying object-oriented programming.

* Previous
* Overview: Objects
* Next


Object-oriented programming - Learn web development

Object-oriented programming
===========================

* Previous
* Overview: Objects
* Next

Object-oriented programming (OOP) is a programming paradigm fundamental to many programming languages, including Java and C++. In this article, we'll provide an overview of the basic concepts of OOP. We'll describe three main concepts: **classes and instances**, **inheritance**, and **encapsulation**. For now, we'll describe these concepts without reference to JavaScript in particular, so all the examples are given in pseudocode.

**Note:** To be precise, the features described here are of a particular style of OOP called **class-based** or "classical" OOP. When people talk about OOP, this is generally the type that they mean.

After that, in JavaScript, we'll look at how constructors and the prototype chain relate to these OOP concepts, and how they differ. In the next article, we'll look at some additional features of JavaScript that make it easier to implement object-oriented programs.

|  |  |
| --- | --- |
| Prerequisites: |
 Understanding JavaScript functions, familiarity with JavaScript basics
 (see
 First steps and
 Building blocks), and OOJS basics (see
 Introduction to objects and Object prototypes).
  |
| Objective: | To understand the basic concepts of class-based object-oriented programming. |

Object-oriented programming is about modeling a system as a collection of objects, where each object represents some particular aspect of the system. Objects contain both functions (or methods) and data. An object provides a public interface to other code that wants to use it but maintains its own private, internal state; other parts of the system don't have to care about what is going on inside the object.

Classes and instances
---------------------

When we model a problem in terms of objects in OOP, we create abstract definitions representing the types of objects we want to have in our system. For example, if we were modeling a school, we might want to have objects representing professors. Every professor has some properties in common: they all have a name and a subject that they teach. Additionally, every professor can do certain things: they can all grade a paper and they can introduce themselves to their students at the start of the year, for example.

So `Professor` could be a **class** in our system. The definition of the class lists the data and methods that every professor has.

In pseudocode, a `Professor` class could be written like this:
```

class Professor
    properties
        name
        teaches
    methods
        grade(paper)
        introduceSelf()
```

This defines a `Professor` class with:

* two data properties: `name` and `teaches`
* two methods: `grade()` to grade a paper and `introduceSelf()` to introduce themselves.

On its own, a class doesn't do anything: it's a kind of template for creating concrete objects of that type. Each concrete professor we create is called an **instance** of the `Professor` class. The process of creating an instance is performed by a special function called a **constructor**. We pass values to the constructor for any internal state that we want to initialize in the new instance.

Generally, the constructor is written out as part of the class definition, and it usually has the same name as the class itself:
```

class Professor
    properties
        name
        teaches
    constructor
        Professor(name, teaches)
    methods
        grade(paper)
        introduceSelf()
```

This constructor takes two parameters, so we can initialize the `name` and `teaches` properties when we create a new concrete professor.

Now that we have a constructor, we can create some professors. Programming languages often use the keyword `new` to signal that a constructor is being called.

```js
walsh = new Professor("Walsh", "Psychology");
lillian = new Professor("Lillian", "Poetry");

walsh.teaches; // 'Psychology'
walsh.introduceSelf(); // 'My name is Professor Walsh and I will be your Psychology professor.'

lillian.teaches; // 'Poetry'
lillian.introduceSelf(); // 'My name is Professor Lillian and I will be your Poetry professor.'
```

This creates two objects, both instances of the `Professor` class.

Inheritance
-----------

Suppose in our school we also want to represent students. Unlike professors, students can't grade papers, don't teach a particular subject, and belong to a particular year.

However, students do have a name and may also want to introduce themselves, so we might write out the definition of a student class like this:
```

class Student
    properties
        name
        year
    constructor
        Student(name, year)
    methods
        introduceSelf()
```

It would be helpful if we could represent the fact that students and professors share some properties, or more accurately, the fact that on some level, they are the *same kind of thing*. **Inheritance** lets us do this.

We start by observing that students and professors are both people, and people have names and want to introduce themselves. We can model this by defining a new class `Person`, where we define all the common properties of people. Then, `Professor` and `Student` can both **derive** from `Person`, adding their extra properties:
```

class Person
    properties
        name
    constructor
        Person(name)
    methods
        introduceSelf()

class Professor : extends Person
    properties
        teaches
    constructor
        Professor(name, teaches)
    methods
        grade(paper)
        introduceSelf()

class Student : extends Person
    properties
        year
    constructor
        Student(name, year)
    methods
        introduceSelf()
```

In this case, we would say that `Person` is the **superclass** or **parent class** of both `Professor` and `Student`. Conversely, `Professor` and `Student` are **subclasses** or **child classes** of `Person`.

You might notice that `introduceSelf()` is defined in all three classes. The reason for this is that while all people want to introduce themselves, the way they do so is different:

```js
walsh = new Professor("Walsh", "Psychology");
walsh.introduceSelf(); // 'My name is Professor Walsh and I will be your Psychology professor.'

summers = new Student("Summers", 1);
summers.introduceSelf(); // 'My name is Summers and I'm in the first year.'
```

We might have a default implementation of `introduceSelf()` for people who aren't students *or* professors:

```js
pratt = new Person("Pratt");
pratt.introduceSelf(); // 'My name is Pratt.'
```

This feature - when a method has the same name but a different implementation in different classes - is called **polymorphism**. When a method in a subclass replaces the superclass's implementation, we say that the subclass **overrides** the version in the superclass.

Encapsulation
-------------

Objects provide an interface to other code that wants to use them but maintain their own internal state. The object's internal state is kept **private**, meaning that it can only be accessed by the object's own methods, not from other objects. Keeping an object's internal state private, and generally making a clear division between its public interface and its private internal state, is called **encapsulation**.

This is a useful feature because it enables the programmer to change the internal implementation of an object without having to find and update all the code that uses it: it creates a kind of firewall between this object and the rest of the system.

For example, suppose students are allowed to study archery if they are in the second year or above. We could implement this just by exposing the student's `year` property, and other code could examine that to decide whether the student can take the course:

```js
if (student.year > 1) {
  // allow the student into the class
}
```

The problem is, if we decide to change the criteria for allowing students to study archery - for example by also requiring the parent or guardian to give their permission - we'd need to update every place in our system that performs this test. It would be better to have a `canStudyArchery()` method on `Student` objects, that implements the logic in one place:
```

class Student : extends Person
    properties
       year
    constructor
       Student(name, year)
    methods
       introduceSelf()
       canStudyArchery() { return this.year > 1 }
```

```js
if (student.canStudyArchery()) {
  // allow the student into the class
}
```

That way, if we want to change the rules about studying archery, we only have to update the `Student` class, and all the code using it will still work.

In many OOP languages, we can prevent other code from accessing an object's internal state by marking some properties as `private`. This will generate an error if code outside the object tries to access them:
```

class Student : extends Person
    properties
       private year
    constructor
        Student(name, year)
    methods
       introduceSelf()
       canStudyArchery() { return this.year > 1 }

student = new Student('Weber', 1)
student.year // error: 'year' is a private property of Student
```

In languages that don't enforce access like this, programmers use naming conventions, such as starting the name with an underscore, to indicate that the property should be considered private.

OOP and JavaScript
------------------

In this article, we've described some of the basic features of class-based object-oriented programming as implemented in languages like Java and C++.

In the two previous articles, we looked at a couple of core JavaScript features: constructors and prototypes. These features certainly have some relation to some of the OOP concepts described above.

* **constructors** in JavaScript provide us with something like a class definition, enabling us to define the "shape" of an object, including any methods it contains, in a single place. But prototypes can be used here, too. For example, if a method is defined on a constructor's `prototype` property, then all objects created using that constructor get that method via their prototype, and we don't need to define it in the constructor.
* **the prototype chain** seems like a natural way to implement inheritance. For example, if we can have a `Student` object whose prototype is `Person`, then it can inherit `name` and override `introduceSelf()`.

But it's worth understanding the differences between these features and the "classical" OOP concepts described above. We'll highlight a couple of them here.

First, in class-based OOP, classes and objects are two separate constructs, and objects are always created as instances of classes. Also, there is a distinction between the feature used to define a class (the class syntax itself) and the feature used to instantiate an object (a constructor). In JavaScript, we can and often do create objects without any separate class definition, either using a function or an object literal. This can make working with objects much more lightweight than it is in classical OOP.

Second, although a prototype chain looks like an inheritance hierarchy and behaves like it in some ways, it's different in others. When a subclass is instantiated, a single object is created which combines properties defined in the subclass with properties defined further up the hierarchy. With prototyping, each level of the hierarchy is represented by a separate object, and they are linked together via the `__proto__` property. The prototype chain's behavior is less like inheritance and more like **delegation**. Delegation is a programming pattern where an object, when asked to perform a task, can perform the task itself or ask another object (its **delegate**) to perform the task on its behalf. In many ways, delegation is a more flexible way of combining objects than inheritance (for one thing, it's possible to change or completely replace the delegate at run time).

That said, constructors and prototypes can be used to implement class-based OOP patterns in JavaScript. But using them directly to implement features like inheritance is tricky, so JavaScript provides extra features, layered on top of the prototype model, that map more directly to the concepts of class-based OOP. These extra features are the subject of the next article.

Summary
-------

This article has described the basic features of class-based object oriented programming, and briefly looked at how JavaScript constructors and prototypes compare with these concepts.

In the next article, we'll look at the features JavaScript provides to support class-based object-oriented programming.

* Previous
* Overview: Objects
* Next


Test your skills: Object basics - Learn web development

Test your skills: Object basics
===============================

The aim of this skill test is to assess whether you've understood our JavaScript object basics article.

**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
 If there is an error in your code, it will be logged into the results panel on this page or in the JavaScript console.

If you get stuck, you can reach out to us in one of our communication channels.

Object basics 1
---------------

In this task you are provided with an object literal, and your tasks are to

* Store the value of the `name` property inside the `catName` variable, using bracket notation.
* Run the `greeting()` method using dot notation (it will log the greeting to the browser's console).
* Update the `color` property value to `black`.

Try updating the live code below to recreate the finished example:

Download the starting point for this task to work in your own editor or in an online editor.

Object basics 2
---------------

In our next task, we want you to have a go at creating your own object literal to represent one of your favorite bands. The required properties are:

* `name`: A string representing the band name.
* `nationality`: A string representing the country the band comes from.
* `genre`: What type of music the band plays.
* `members`: A number representing the number of members the band has.
* `formed`: A number representing the year the band formed.
* `split`: A number representing the year the band split up, or `false` if they are still together.
* `albums`: An array representing the albums released by the band. Each array item should be an object containing the following members:
    + `name`: A string representing the name of the album.
    + `released`: A number representing the year the album was released.

Include at least two albums in the `albums` array.

Once you've done this, you should then write a string to the variable `bandInfo`, which will contain a small biography detailing their name, nationality, years active, and style, and the title and release date of their first album.

Try updating the live code below to recreate the finished example:

Download the starting point for this task to work in your own editor or in an online editor.

Object basics 3
---------------

In this task, we want you to return to the `cat` object literal from Task 1. We want you to rewrite the `greeting()` method so that it logs `"Hello, said Bertie the Cymric."` to the browser's console, but in a way that will work across *any* cat object of the same structure, regardless of its name or breed.

When you are done, write your own object called `cat2`, which has the same structure, exactly the same `greeting()` method, but a different `name`, `breed`, and `color`.

Call both `greeting()` methods to check that they log appropriate greetings to the console.

Try updating the live code below to recreate the finished example:

Download the starting point for this task to work in your own editor or in an online editor.

Object basics 4
---------------

In the code you wrote for Task 3, the `greeting()` method is defined twice, once for each cat. This isn't ideal (specifically, it violates a principle in programming sometimes called DRY or "Don't Repeat Yourself").

In this task we want you to improve the code so `greeting()` is only defined once, and every `cat` instance gets its own `greeting()` method. Hint: you should use a JavaScript constructor to create `cat` instances.

Try updating the live code below to recreate the finished example:

Download the starting point for this task to work in your own editor or in an online editor.