Introduction to client-side development
The client-server model consists of three parts:
- the client
- the server
- the network
Client Side Scripting / Coding - Client Side Scripting is the type of code that is executed or interpreted by browsers.
Client Side Scripting is generally viewable by any visitor to a site (from the view menu click on "View Source" to view the source code).
Below are some common Client Side Scripting technologies:- HTML (HyperText Markup Language)
- CSS (Cascading Style Sheets)
- JavaScript
- Ajax (Asynchronous JavaScript and XML)
- jQuery (JavaScript Framework Library - commonly used in Ajax development)
- MooTools (JavaScript Framework Library - commonly used in Ajax development)
- Dojo Toolkit (JavaScript Framework Library - commonly used in Ajax development
- Applet
- A Java program that is part of a Hypertext Markup Language (HTML) page. (HTML is the standard method for presenting web data to users.) Applets work with Java-enabled browsers, such as Microsoft Internet Explorer; they are loaded when the HTML page is processed.
Web application servers manage the business logic. The business logic, typically written in Java, supports multitiered applications. The web application server can manage requests from a variety of remote clients. The web application layer might include JavaServer Pages (JSP) files, Java servlets, Enterprise JavaBeans (EJB) components, or web services.
- JSP
- A technology that provides a consistent way to extend web server functionality and create dynamic web content. The web applications that you develop with JSP technology are server and platform independent.
- Servlet
- A Java program that responds to client requests and generates responses dynamically.
- EJB
- A component architecture for building distributed applications with the Java programming model. Server transactional components are reusable and provide portability across application servers.
- Web services
- Self-contained, modular applications that provide an interface between the provider and the consumer of application resources. You can read more about web services later in this information.
- The client-server model is a distributed communication framework of network processes among service requestors, clients and service providers. The client-server connection is established through a network or the Internet.
The client-server model is a core network computing concept also building functionality for email exchange and Web/database access. Web technologies and protocols built around the client-server model are:- Hypertext Transfer Protocol (HTTP)
- Domain Name System (DNS)
- Simple Mail Transfer Protocol (SMTP)
- Telnet
Clients include Web browsers, chat applications, and email software, among others. Servers include Web, database, application, chat and email, etc Different categories of elements in HTML
Always declare the document type as the first line in your document:<!DOCTYPE html>If you want consistency with lower case tags, you can use:<!doctype html>
Use Lower Case Element Names
HTML5 allows mixing uppercase and lowercase letters in element names.We recommend using lowercase element names because:- Mixing uppercase and lowercase names is bad
- Developers normally use lowercase names (as in XHTML)
- Lowercase look cleaner
- Lowercase are easier to write
Bad:
<SECTION>
<p>This is a paragraph.</p>
</SECTION>Very Bad:
<Section>
<p>This is a paragraph.</p>
</SECTION>Good:
<section>
<p>This is a paragraph.</p>
</section>
Close All HTML Elements
In HTML5, you don't have to close all elements (for example the<p>
element).We recommend closing all HTML elements.Bad:
<section>
<p>This is a paragraph.
<p>This is a paragraph.
</section>Good:
<section>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
</section>
Close Empty HTML Elements
In HTML5, it is optional to close empty elements.Allowed:
<meta charset="utf-8">Also Allowed:
<meta charset="utf-8" />However, the closing slash (/) is REQUIRED in XHTML and XML.If you expect XML software to access your page, it is a good idea to keep the closing slash!
Use Lower Case Attribute Names
HTML5 allows mixing uppercase and lowercase letters in attribute names.We recommend using lowercase attribute names because:- Mixing uppercase and lowercase names is bad
- Developers normally use lowercase names (as in XHTML)
- Lowercase look cleaner
- Lowercase are easier to write
Bad:
<div CLASS="menu">Good:
<div class="menu">
Quote Attribute Values
HTML5 allows attribute values without quotes.We recommend quoting attribute values because:- Developers normally quote attribute values (as in XHTML)
- Quoted values are easier to read
- You MUST use quotes if the value contains spaces
Very bad:
This will not work, because the value contains spaces:<table class=table striped>Bad:
<table class=striped>Good:
<table class="striped">
Image Attributes
Always add thealt
attribute to images. This attribute is important when the image for some reason cannot be displayed. Also, always define image width and height. It reduces flickering because the browser can reserve space for the image before loading.Bad:
<img src="html5.gif">Good:
<img src="html5.gif" alt="HTML5" style="width:128px;height:128px">
Spaces and Equal Signs
HTML5 allows spaces around equal signs. But space-less is easier to read and groups entities better together.Bad:
<link rel = "stylesheet" href = "styles.css">Good:
<link rel="stylesheet" href="styles.css">
Avoid Long Code Lines
When using an HTML editor, it is inconvenient to scroll right and left to read the HTML code.Try to avoid code lines longer than 80 characters.
Blank Lines and Indentation
Do not add blank lines without a reason.For readability, add blank lines to separate large or logical code blocks.For readability, add two spaces of indentation. Do not use the tab key.Do not use unnecessary blank lines and indentation. It is not necessary to indent every element:Unnecessary:
<body>
<h1>Famous Cities</h1>
<h2>Tokyo</h2>
<p>
Tokyo is the capital of Japan, the center of the Greater Tokyo Area,
and the most populous metropolitan area in the world.
It is the seat of the Japanese government and the Imperial Palace,
and the home of the Japanese Imperial Family.
</p>
</body>Better:
<body>
<h1>Famous Cities</h1>
<h2>Tokyo</h2>
<p>Tokyo is the capital of Japan, the center of the Greater Tokyo Area,
and the most populous metropolitan area in the world.
It is the seat of the Japanese government and the Imperial Palace,
and the home of the Japanese Imperial Family.</p>
</body>Table Example:
<table>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr>
<td>A</td>
<td>Description of A</td>
</tr>
<tr>
<td>B</td>
<td>Description of B</td>
</tr>
</table>List Example:
<ul>
<li>London</li>
<li>Paris</li>
<li>Tokyo</li>
</ul>
Omitting <html> and <body>?
In HTML5, the<html>
tag and the<body>
tag can be omitted.The following code will validate as HTML5:Example
<!DOCTYPE html>
<head>
<title>Page Title</title>
</head>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>However, we do not recommend omitting the<html>
and the<body>
tag.The<html>
element is the document root. It is the recommended place for specifying the page language:<!DOCTYPE html>
<html lang="en-US">Declaring a language is important for accessibility applications (screen readers) and search engines.Omitting<html>
or<body>
can crash DOM and XML software.Omitting<body>
can produce errors in older browsers (IE9).
Omitting <head>?
In HTML5, the <head> tag can also be omitted.By default, browsers will add all elements before<body>
to a default<head>
element.You can reduce the complexity of HTML by omitting the<head>
tag:Example
<!DOCTYPE html>
<html>
<title>Page Title</title>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>However, we do not recommend omitting the<head>
tag.Omitting tags is unfamiliar to web developers. It needs time to be established as a guideline.
Meta Data
The<title>
element is required in HTML5. Make the title as meaningful as possible:<title>HTML5 Syntax and Coding Style</title>To ensure proper interpretation and correct search engine indexing, both the language and the character encoding should be defined as early as possible in a document:<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>HTML5 Syntax and Coding Style</title>
</head>
Setting The Viewport
HTML5 introduced a method to let web designers take control over the viewport, through the<meta>
tag.The viewport is the user's visible area of a web page. It varies with the device, and will be smaller on a mobile phone than on a computer screen.You should include the following<meta>
viewport element in all your web pages:<meta name="viewport" content="width=device-width, initial-scale=1.0">A<meta>
viewport element gives the browser instructions on how to control the page's dimensions and scaling.The width=device-width part sets the width of the page to follow the screen-width of the device (which will vary depending on the device).The initial-scale=1.0 part sets the initial zoom level when the page is first loaded by the browser.Here is an example of a web page without the viewport meta tag, and the same web page with the viewport meta tag.Improves Website Presentation
The standout advantage of CSS is the added design flexibility and interactivity it brings to web development. Developers have greater control over the layout allowing them to make precise section-wise changes.As customization through CSS is much easier than plain HTML, web developers are able to create different looks for each page. Complex websites with uniquely presented pages are feasible thanks to CSS.Makes Updates Easier and Smoother
CSS works by creating rules. These rules are simultaneously applied to multiple elements within the site. Eliminating the repetitive coding style of HTML makes development work faster and less monotonous. Errors are also reduced considerably.Since the content is completely separated from the design, changes across the website can be implemented all at once. This reduces delivery times and costs of future edits.Helps Web Pages Load Faster
Improved website loading is an underrated yet important benefit of CSS. Browsers download the CSS rules once and cache them for loading all the pages of a website. It makes browsing the website faster and enhances the overall user experience.This feature comes in handy in making websites work smoothly at lower internet speeds. Accessibility on low end devices also improves with better loading speeds.New Features of CSS3
#1. CSS3 SelectorsSelectors are at the heart of CSS. Originally, CSS allowed the matching of elements by type, class, and/or ID. CSS2.1 added pseudo-elements, pseudo-classes, and combinators. With CSS3, we can target almost any element on the page with a wide range of selectors.CSS2 introduced several attribute selectors. These allow for matching elements based on their attributes. CSS3 expands upon those attribute selectors.Three more attribute selectors were added in CSS3; they allow for substring selection.1.Matches any element E whose attribute attr starts with the value val. In other words, the val matches the beginning of the attribute value.E[attr^=val] eg. a[href^='http://sales.']{color: teal;}
2.Matches any element E whose attribute attr ends in val. In other words, the val matches the end of the attribute value.E[attr$=val] eg. a[href$='.jsp']{color: purple;}
3.Matches any element E whose attribute attr matches val anywhere within the attribute. It is similar to E[attr~=val], except the val can be part of a word.E[attr*=val] eg. img[src*='artwork']{ border-color: #C3B087 #FFF #FFF #C3B087; }
Pseudo-classesIt’s likely that you’re already familiar with some of the user interaction pseudo-classes,namely :link, :visited, :hover, :active, and :focus.A few more pseudo-class selectors were added in CSS3. One is the :root selector, which allows designers to point to the root element of a document. In HTML, it would be <html>. Since :root is generic, it allows a designer to select the root element of an XML document without necessarily knowing it’s name. To permit scrollbars when needed in a document, this rule would work.:root{overflow:auto;}
As a complement to the :first-child selector, the :last-child was added. With it one can select the last element named of a parent element. For a site with articles contained in <div class=’article’></div> tags, where each has a last paragraph with some information that needs to be uniformly stylized, this rule would change the font for last paragraph of each article.div.article > p:last-child{font-style: italic;}
A new user interaction pseudo-class selector was added, the :target selector. To draw the user’s attention to a span of text when the user clicks on a same-page link, a rule like the first line below would work nicely; the link would look like the second line, the highlighted span like the third.span.notice:target{font-size: 2em; font-style: bold;}
<a href='#section2'>Section 2</a>
<p id='section2'>...</p>
A functional notation for selecting specified elements that fail a test has been created. The negation pseudo-class selector, :not can be coupled with almost any other selector that has been implemented. For example to put a border around images that don’t have a border specified, use a rule like this.img:not([border]){border: 1;}
#2. CSS3 ColorsCSS3 brings with it support for some new ways of describing colours . Prior to CSS3, we almost always declared colours using the hexadecimal format (#FFF, or #FFFFFF for white). It was also possible to declare colours using the rgb() notation, providing either integers (0–255) or percentages.The color keyword list has been extended in the CSS3 color module to include 147 additional keyword colors (that are generally well supported), CSS3 also provides us with a number of other options: HSL, HSLA, and RGBA. The most notable change with these new color types is the ability to declare semitransparent colors.- RGBA :
RGBA works just like RGB, except that it adds a fourth value: alpha, the opacity level or alpha transparency level. The first three values still represent red, green, and blue. For the alpha value, 1 means fully opaque, 0 is fully transparent, and 0.5 is 50% opaque. You can use any number between 0 and 1 inclusively.2. HSL and HSLAHSL stands for hue, saturation, and lightness. Unlike RGB, where you need to manipulate the saturation or brightness of a color by changing all three color values in concert, with HSL you can tweak either just the saturation or the lightness while keeping the same base hue. The syntax for HSL comprises an integer value for hue, and percentage values for saturation and lightness.The hsl( ) declaration accepts three values:— The hue in degrees from 0 to 359. Some examples are: 0 = red, 60 = yellow, 120= green, 180 = cyan, 240 = blue, and 300 = magenta.— The saturation as a percentage with 100% being the norm. Saturation of 100% will be the full hue, and saturation of 0 will give you a shade of gray — essentially causing the hue value to be ignored.— A percentage for lightness with 50% being the norm. A lightness of 100% will be white, 50% will be the actual hue, and 0% will be black.The a in hsla( ) here also functions the same way as in rgba( )3.OpacityIn addition to specifying transparency with HSLA and RGBA colors (and soon, eight-digit hexadecimal values), CSS3 provides us with the opacity property. opacity sets the opaqueness of the element on which it’s declared, similar to alpha.Let’s look at an example:div.halfopaque {
background-color: rgb(0, 0, 0);
opacity: 0.5;
color: #000000;
}
div.halfalpha {
background-color: rgba(0, 0, 0, 0.5);
color: #000000;
}
Though the usage of both alpha and opacity notations seem similar, when you look at it, there is a key difference in their function.While opacity sets the opacity value for an element and all of its children, a semitransparent RGBA or HSLA color has no impact on the element’s other CSS properties or descendants.#3. Rounded Corners: border-radiusThe border-radius property lets you create rounded corners without the need for images or additional markup. To add rounded corners to our box, we simply addborder-radius: 25px;
The border-radius property is actually a shorthand. For our “a” element, the corners are all the same size and symmetrical. If we had wanted different-sized corners, we could declare up to four unique valuesborder-radius: 5px 10px 15px 20px;
#4. Drop ShadowsCSS3 provides the ability to add drop shadows to elements using the box-shadow property. This property lets you specify the color, height, width, blur, and offset of one or multiple inner and/or outer drop shadows on your elements.box-shadow: 2px 5px 0 0 rgba(72,72,72,1);
#5. Text Shadowtext-shadow adds shadows to individual characters in text nodes. Prior to CSS 3, this would be done by either using an image or duplicating a text element and then positioning it.text-shadow: topOffset leftOffset blurRadius color;
CSS Selectors- CSS selectors are used to "find" (or select) HTML elements based on their element name, id, class, attribute, and more.
The element Selector
The element selector selects elements based on the element name.You can select all <p> elements on a page like this (in this case, all <p> elements will be center-aligned, with a red text color):Example
p {
text-align: center;
color: red;}
The id Selector
The id selector uses the id attribute of an HTML element to select a specific element.The id of an element should be unique within a page, so the id selector is used to select one unique element!To select an element with a specific id, write a hash (#) character, followed by the id of the element.The style rule below will be applied to the HTML element with id="para1":Example
#para1 {
text-align: center;
color: red;}
The class Selector
The class selector selects elements with a specific class attribute.To select elements with a specific class, write a period (.) character, followed by the name of the class.In the example below, all HTML elements with class="center" will be red and center-aligned:Example
.center {
text-align: center;
color: red;}You can also specify that only specific HTML elements should be affected by a class.In the example below, only <p> elements with class="center" will be center-aligned:Example
p.center {
text-align: center;
color: red;}HTML elements can also refer to more than one class.In the example below, the <p> element will be styled according to class="center" and to class="large":Example
<p class="center large">This paragraph refers to two classes.</p> Advanced Selectors in CSS
- Selectors are used for selecting the HTML elements in the attributes. Some different types of selectors are given below:
- Adjacent Sibling Selector: It selects all the elements that are adjacent siblings of specified elements. It selects the second element if it immediately follows the first element.
Syntax: It select ul tags which immediately follows the h4 tag.Example:Output: - Attribute Selector: It selects a particular type of inputs.
Syntax:Example:Output: - nth-of-type Selector: It selects an element from its position and types.
Syntax: Select a particular number tag to make changes.If we want to make canges in all even li.Example:Output:
- Adjacent Sibling Selector: It selects all the elements that are adjacent siblings of specified elements. It selects the second element if it immediately follows the first element.
Use for CSS media queries in responsive web development
- By targeting the browser width, we can style content to look appropriate for a wide desktop browser, a medium-sized tablet browser, or a small phone browser. Adjusting the layout of a web page based on the width of the browser is called "responsive design." Responsive design is made possible by CSS media queries.In this how to, you'll learn how to use media queries in responsive design.
Pros and Cons of 3 ways of using CSS (inline, internal, external)
. Inline CSS
Advantages:Inline CSS can be used for many purposes, some of which include:- Testing:
Many
web designers use Inline CSS when they begin working on new projects, this
is because its easier to scroll up in the source, rather than change the
source file. Some also using it to debug their pages, if they
encounter a problem which is not so easily fixed. This can be done in
combination with the Important rule of CSS.
- Quick-fixes:There are times
where you would just apply a direct fix in your HTML source, using the
style attribute, but you would usually move the fix to the relevant files
when you are either able, or got the time.
- Smaller
Websites: The
website such as Blogs where there are only limited number of pages, using
of Inline CSS helps users and service provider.
- Lower
the HTTP Requests: The major benefit of using
Inline CSS is lower HTTP Requests which means the website loads faster
than External CSS.
DisadvantagesInline CSS some of the disadvantages of which includes:- Overriding: Because
they are the most specific in the cascade, they can over-ride things you
didn’t intend them to.
- Every
Element:
Inline styles must be applied to every element you want them on. So if you
want all your paragraphs to have the font family “Arial” you have to add
an inline style to each <p> tag in your document. This adds
both maintenance work for the designer and download time for the reader.
- Pseudo-elements: It’s
impossible to style pseudo-elements and classes with inline styles. For
example, with external and internal style sheets, you can style the
visited, hover, active, and link color of an anchor tag. But with an inline
style all you can style is the link itself, because that’s what the style
attribute is attached to.
Internal CSSAdvantagesSince the Internal CSS have more preference over Inline CSS. There are numerous advantages of which some of important are an under:- Cache
Problem:
Internal styles will be read by all browsers unless they are hacked to
hide from certain ones. This removes the ability to use media=all or
@import to hide styles from old, crotchety browsers like IE4 and NN4.
- Pseudo-elements: It’s impossible
to style pseudo-elements and classes with inline styles. With Internal
style sheets, you can style the visited, hover, active, and link color of
an anchor tag.
- One
style of same element: Internal styles need not be
applied to every element. So if you want all your paragraphs to have the
font family “Arial” you have to add an Inline style <p> tag in
Internal Style document.
- No
additional downloads: No additional downloads
necessary to receive style information or we have less HTTP Request
Disadvantages- Multiple
Documents:
This method can’t be used, if you want to use it on multiple web pages.
- Slow
Page Loading:
As there are less HTTP Request but by using the Internal CSS the page load
slow as compared to Inline and External CSS.
- Large
File Size: While
using the Internal CSS the page size increases but it helps only to
Designers while working offline but when the website goes online it
consumers much time as compared to offline.
External CSSAdvantagesThere are many advantages for using external CSS and some of are:- Full
Control of page structure: CSS allows you to display your
web page according to W3C HTML standards without making any compromise
with the actual look of the page. Google is the leading search Engine and
major source of traffic. Google gives very little value to the web pages
that are well-organized, since the value is little thus many Designers
ignore it. But by taking small value may drive much traffic to the
website.
- Reduced
file-size:
By including the styling of the text in a separate file, you can
dramatically decrease the file-size of your pages. Also, the
content-to-code ratio is far greater than with simple HTML pages, thus
making the page structure easier to read for both the programmer and the
spiders. With CSS you can define the visual effect that you want to apply
to images, instead of using images per say. The space you gain this way
can be used for text that is relevant for spiders (i.e. keywords), and
you will also lower the file-size of the page.
- Less
load time:
Today, when Google has included the Loading time in his algorithm, its
become more important to look into the page loading time and another
benefit of having low file-size pages translates into reduced bandwidth
costs. CSS can help you save some money by offering you. I done a small
experiment to check the page load time. I am using the Mobile Internet
Connection for testing and for that first I cleared the web cache of the
website and visited http://lawmirror.comfor first time
after clearing cache. The total time taken to load the website is 16
seconds. Now I hit the F5 button and the time taken to load the website
is 8 seconds. Using external CSS has reduced the page load timing. It me
explain it how it reduces the time, when you first visited the website,
it has downloaded all the contents + external CSS and while downloading
external CSS, it has marked the CSS with the time stamp with the time
stamp of the web server. Now when you hit F5, it again starts working but
this time the browser compare the time stamps of downloaded CSS with Web
Server CSS and due to same time stamp, it doesn’t downloaded the CSS
external file from server and using the already downloaded time, which
make the Web Page Loading time faster as com paired to first time. If you
check under Firebug or Chrome tools it will tell 304 Not Modified,
meaning the file is not modified since last downloaded file, and thus
ignoring to download the external CSS file.
- Higher page ranking : In the SEO, it is very important to use external CSS. How it gives, let me explain, In SEO, the content is the King and not the amount of code on a page. Search engines spider will be able to index your pages much faster, as the important information can be placed higher in the HTML document. Also, the amount of relevant content will be greater than the amount of code on a page. The search engine will not have to look too far in your code to find the real content. You will be actually serving it to the spiders “on a platter”. CSS will help you create highly readable pages, rich in content, which will prove extremely helpful in your SEO campaign. As you very well know, better site ranking means better visibility on the web, and this can translate into more visitors and, ultimately, into increased sales or number of contracts. For more details lets use some code to understand:
Frameworks/libraries/plugins/tools to develop the Views/web pages
- Testing:
Many
web designers use Inline CSS when they begin working on new projects, this
is because its easier to scroll up in the source, rather than change the
source file. Some also using it to debug their pages, if they
encounter a problem which is not so easily fixed. This can be done in
combination with the Important rule of CSS.
Libraries
A library is an organized collection of useful functionality. A typical library could include functions to handle strings, dates, HTML DOM elements, events, cookies, animations, network requests, and more. Each function returns values to the calling application which can be implemented however you choose. Think of it like a selection of car components: you’re free to use any to help construct a working vehicle but you must build the engine yourself.Libraries normally provide a higher level of abstraction which smooths over implementation details and inconsistencies. For example, Ajax can be implemented using the XMLHttpRequest API but this requires several lines of code and there are subtle differences across browsers. A library may provide a simplerajax()
function so you’re free to concentrate on higher-level business logic.A library could cut development time by 20% because you don’t have to worry about the finer details. The downsides:- a bug within a
library can be difficult to locate and fix
- there’s no
guarantee the development team will release a patch quickly
- a patch could
change the API and incur significant changes to your code.
Frameworks
A framework is an application skeleton. It requires you to approach software design in a specific way and insert your own logic at certain points. Functionality such as events, storage, and data binding are normally provided for you. Using the car analogy, a framework provides a working chassis, body, and engine. You can add, remove or tinker with some components presuming the vehicle remains operational.A framework normally provides a higher level of abstraction than a library and can help you rapidly build the first 80% of your project. The downsides:- the last 20% can
be tough going if your application moves beyond the confines of the
framework
- framework updates
or migrations can be difficult – if not impossible
- core framework
code and concepts rarely age well. Developers will always discover a better way
to do the same thing.
Tools
A tool aids development but is not an integral part of your project. Tools include build systems, compilers, transpilers, code minifiers, image compressors, deployment mechanisms and more.Tools should provide an easier development process. For example, many coders prefer Sass to CSS because it provides code separation, nesting, render-time variables, loops, and functions. Browsers do not understand Sass/SCSS syntax so the code must be compiled to CSS using an appropriate tool before testing and deployment- a bug within a
library can be difficult to locate and fix
- A browser-based (or web-based) tool, application, program, or app is software that runs on your web browser. Browser-based applications only require an internet connection and an installed web browser on your computer to function. Most web-based applications are installed and run on a remote server that you access with your web browser.Web browsers are installed on your computer and allow you to access websites. Types of web browsers include Google Chrome, Firefox, Microsoft Edge (also known as Internet Explorer), Opera, and others.
Examples of Web-Based Apps
There is a wide range of web-based applications available, and their numbers continue to grow. Well-known types of software you can find in web-based versions are email applications, word processors, spreadsheet apps, and a host of other office productivity tools.For example, Google offers a suite of office productivity applications in a style most people are already familiar with. Google Docs is a word processor, and Google Sheets is a spreadsheet application.Microsoft's ubiquitous office suite has a web-based platform known as Office Onlineand Office 365. Office 365 is a subscription service.Web-based tools can also make meetings and collaborations vastly easier. Applications such as WebEx and GoToMeeting make setting up and running an online meeting easy.Here’s the list of the best ES6 features
1. Default Parameters in ES6
Remember we had to do these statements to define default parameters:var link = function (height, color, url) { var height = height || 50 var color = color || 'red' var url = url || 'http://azat.co' ... }
They were okay until the value was 0 and because 0 is falsy in JavaScript it would default to the hard-coded value instead of becoming the value itself. Of course, who needs 0 as a value (#sarcasmfont), so we just ignored this flaw and used the logic OR anyway… No more! In ES6, we can put the default values right in the signature of the functions:var link = function(height = 50, color = 'red', url = 'http://azat.co') { ... }
By the way, this syntax is similar to Ruby!2. Template Literals in ES6
Template literals or interpolation in other languages is a way to output variables in the string. So in ES5 we had to break the string like this:var name = 'Your name is ' + first + ' ' + last + '.' var url = 'http://localhost:3000/api/messages/' + id
Luckily, in ES6 we can use a new syntax${NAME}
inside of the back-ticked string:var name = `Your name is ${first} ${last}.` var url = `http://localhost:3000/api/messages/${id}`
3. Multi-line Strings in ES6
Another yummy syntactic sugar is multi-line string. In ES5, we had to use one of these approaches:var roadPoem = 'Then took the other, as just as fair,\n\t' + 'And having perhaps the better claim\n\t' + 'Because it was grassy and wanted wear,\n\t' + 'Though as for that the passing there\n\t' + 'Had worn them really about the same,\n\t' var fourAgreements = 'You have the right to be you.\n\ You can only be you when you do your best.'
While in ES6, simply utilize the backticks:var roadPoem = `Then took the other, as just as fair, And having perhaps the better claim Because it was grassy and wanted wear, Though as for that the passing there Had worn them really about the same,` var fourAgreements = `You have the right to be you. You can only be you when you do your best.`
4. Destructuring Assignment in ES6
Destructuring can be a harder concept to grasp, because there’s some magic going on… let’s say you have simple assignments where keyshouse
andmouse
are variableshouse
andmouse
:[Sidenote]Reading blog posts is good, but watching video courses is even better because they are more engaging.A lot of developers complained that there is a lack of affordable quality video material on Node. It's distracting to watch to YouTube videos and insane to pay $500 for a Node video course!Go check out Node University which has FREE video courses on Node: node.university.[End of sidenote]var data = $('body').data(), // data has properties house and mouse house = data.house, mouse = data.mouse
Other examples of destructuring assignments (from Node.js):var jsonMiddleware = require('body-parser').json var body = req.body, // body has username and password username = body.username, password = body.password
In ES6, we can replace the ES5 code above with these statements:var {house, mouse} = $('body').data() // we'll get house and mouse variables var {json: jsonMiddleware} = require('body-parser') var {username, password} = req.body
This also works with arrays. Crazy!var [col1, col2] = $('.column'), [line1, line2, line3, , line5] = file.split('\n')
It might take some time to get use to the destructuring assignment syntax, but it’s a sweet sugarcoating.5. Enhanced Object Literals in ES6
What you can do with object literals now is mind blowing! We went from a glorified version of JSON in ES5 to something closely resembling classes in ES6.Here’s a typical ES5 object literal with some methods and attributes/properties:var serviceBase = {port: 3000, url: 'azat.co'}, getAccounts = function(){return [1,2,3]} var accountServiceES5 = { port: serviceBase.port, url: serviceBase.url, getAccounts: getAccounts, toString: function() { return JSON.stringify(this.valueOf()) }, getUrl: function() {return "http://" + this.url + ':' + this.port}, valueOf_1_2_3: getAccounts() }
If we want to be fancy, we can inherit fromserviceBase
by making it the prototype with theObject.create
method:var accountServiceES5ObjectCreate = Object.create(serviceBase) var accountServiceES5ObjectCreate = { getAccounts: getAccounts, toString: function() { return JSON.stringify(this.valueOf()) }, getUrl: function() {return "http://" + this.url + ':' + this.port}, valueOf_1_2_3: getAccounts() }
I know,accountServiceES5ObjectCreate
andaccountServiceES5
are NOT totally identical, because one object (accountServiceES5
) will have the properties in the__proto__
object as shown below:But for the sake of the example, we’ll consider them similar. So in ES6 object literal, there are shorthands for assignmentgetAccounts: getAccounts,
becomes justgetAccounts,
. Also, we set the prototype right there in the__proto__`` property which makes sense (not
‘proto’` though:var serviceBase = {port: 3000, url: 'azat.co'}, getAccounts = function(){return [1,2,3]} var accountService = { __proto__: serviceBase, getAccounts,
Also, we can invokesuper
and have dynamic keys (valueOf_1_2_3
):toString() { return JSON.stringify((super.valueOf())) }, getUrl() {return "http://" + this.url + ':' + this.port}, [ 'valueOf_' + getAccounts().join('_') ]: getAccounts() }; console.log(accountService)
This is a great enhancement to good old object literals!
Both frameworks and libraries are code written by someone else that is used to help solve common problems.For example, let’s say you have a program where you plan on working with strings. You decide to keep your code DRY (don’t repeat yourself) and write some reusable functions like these:function getWords(str) { const words = str.split(' '); return words; }
function createSentence(words) { const sentence = words.join(' '); return sentence; }
Congratulations. You’ve created a library.There isn’t anything magic about frameworks or library. Both libraries and frameworks are reusable code written by someone else. Their purpose is to help you solve common problems in easier ways.I often use a house as a metaphor for web development concepts.A library is like going to Ikea. You already have a home, but you need a bit of help with furniture. You don’t feel like making your own table from scratch. Ikea allows you to pick and choose different things to go in your home. You are in control.A framework, on the other hand, is like building a model home. You have a set of blueprints and a few limited choices when it comes to architecture and design. Ultimately, the contractor and blueprint are in control. And they will let you know when and where you can provide your input.The Technical Difference
The technical difference between a framework and library lies in a term called inversion of control.When you use a library, you are in charge of the flow of the application. You are choosing when and where to call the library. When you use a framework, the framework is in charge of the flow. It provides some places for you to plug in your code, but it calls the code you plugged in as needed.Let’s look at an example using jQuery (a library) and Vue.js (a framework).Imagine we want to display an error message when an error is present. In our example, we will click a button, and pretend an error occurs.With jQuery:
index.html
<html> <head> <script src="https://code.jquery.com/jquery-3.3.1.min.js" </script> <script src="./app.js"></script> </head> <body> <div id="app"> <button id="myButton">Submit</button> </div> </body> </html>
// app.js
// A bunch of our own code, // followed by calling the jQuery library
let error = false; const errorMessage = 'An Error Occurred';
$('#myButton').on('click', () => { error = true; // pretend some error occurs and set error = true if (error) { $('#app') .append(`<p id="error">${errorMessage}</p>`); } else { $('#error').remove(); } });
Notice how we use jQuery. We tell our program where we want to call it. This is much like going to a physical library and pulling certain books off the shelf as we want them.That’s not to say jQuery functions don’t require certain inputs once we call them, but jQuery itself is a library of those functions. We are in charge.
Comments
Post a Comment