<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>ILJS, Author at I Learn Javascript</title>
	<atom:link href="https://www.ilearnjavascript.com/author/uke5tar/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.ilearnjavascript.com/author/uke5tar/</link>
	<description>Learn Javascript for free</description>
	<lastBuildDate>Sat, 25 Jan 2020 18:11:44 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9</generator>
	<item>
		<title>Task automation with Gulp.JS</title>
		<link>https://www.ilearnjavascript.com/task-automation-with-gulpjs/</link>
		
		<dc:creator><![CDATA[ILJS]]></dc:creator>
		<pubDate>Sat, 30 Mar 2019 21:51:06 +0000</pubDate>
				<category><![CDATA[GulpJS]]></category>
		<category><![CDATA[Web Development Tools]]></category>
		<category><![CDATA[gulpjs]]></category>
		<category><![CDATA[tools]]></category>
		<guid isPermaLink="false">https://www.ilearnjavascript.com/?p=1142</guid>

					<description><![CDATA[<p>Gulp.JS is an open source Javascript toolkit to improve your development workflow. It is a task runner build on top of Node.JS and npm used to automate repetitive tasks in web development.</p>
<p>The post <a href="https://www.ilearnjavascript.com/task-automation-with-gulpjs/">Task automation with Gulp.JS</a> appeared first on <a href="https://www.ilearnjavascript.com">I Learn Javascript</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975">
.flex_column.av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975{
border-radius:0px 0px 0px 0px;
padding:0px 0px 0px 0px;
}
</style>
<div  class='flex_column av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975 av_one_full  avia-builder-el-0  avia-builder-el-no-sibling  blogpost first flex_column_div av-zero-column-padding  '     ><p>
<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-av_heading-4b8886df4adf41e38d6a0c6aebf52934">
#top .av-special-heading.av-av_heading-4b8886df4adf41e38d6a0c6aebf52934{
padding-bottom:10px;
}
body .av-special-heading.av-av_heading-4b8886df4adf41e38d6a0c6aebf52934 .av-special-heading-tag .heading-char{
font-size:25px;
}
.av-special-heading.av-av_heading-4b8886df4adf41e38d6a0c6aebf52934 .av-subheading{
font-size:14px;
}
</style>
<div  class='av-special-heading av-av_heading-4b8886df4adf41e38d6a0c6aebf52934 av-special-heading-h1 blockquote modern-quote  avia-builder-el-1  el_before_av_textblock  avia-builder-el-first '><h1 class='av-special-heading-tag '  itemprop="headline"  >Task automation with Gulp.JS</h1><div class='av-subheading av-subheading_below'><p>20min read</p>
</div><div class="special-heading-border"><div class="special-heading-inner-border"></div></div></div><br />
<section  class='av_textblock_section av-3nl906-9982023120dc9aa3d9f9917892a21262 '   itemscope="itemscope" itemtype="https://schema.org/BlogPosting" itemprop="blogPost" ><div class='avia_textblock'  itemprop="text" ><p><a href="https://gulpjs.com/" target="_blank" rel="noopener noreferrer">Gulp.JS</a> is an open source Javascript toolkit to improve your development workflow. It is a task runner build on top of <a href="https://nodejs.org/en/" target="_blank" rel="noopener noreferrer">Node.JS</a> and <a href="https://www.npmjs.com/" target="_blank" rel="noopener noreferrer">npm</a> used to automate repetitive tasks in web development. Task runners like gulp are used frequently (but not exclusively) during the build process. Examples of such tasks include compiling SASS to CSS, autoprefixing CSS, minification, file concatenation, string replacement within a file, renaming files, injecting code into files, transpiling modern Javascript (ES6+) to browser compatible ES5 with babel, watching for changes in files to automatically reload the development server (hot reloading) and everything else you think that should (and could) be automated.</p>
<p>This article will not compare gulp to <a href="https://webpack.js.org/" target="_blank" rel="noopener noreferrer">webpack, </a><a href="https://docs.npmjs.com/misc/scripts" target="_blank" rel="noopener noreferrer">npm scripts</a> or <a href="https://rollupjs.org/guide/en" target="_blank" rel="noopener noreferrer">rollup.js</a>. There have been many great articles written about that already. The goal of this blog post is to show you with practical examples how to get started with gulp and setup a build process that includes the folowing tasks:</p>
<ul>
<li>compile SASS to CSS</li>
<li>Autoprefix CSS</li>
<li>Minify your CSS and Javascript files</li>
<li>Transpile your ES6+ code to ES5 via babel</li>
<li>Create sourcemaps for the minifcation and transpiling</li>
<li>Rename your files</li>
<li>Inject files into other files</li>
<li>Create a file watcher and development server that automatically reloads when a watched file changes</li>
</ul>
<h2>Setup &amp; Installation</h2>
<p>In order to follow this post and try the examples you need to have a recent version of Node.JS and npm installed (npm comes automatically with a recent node version). You can check if you have Node.js and npm installed by executing in your terminal the following two commands (one after another)</p>
<p>&#8220;node -v&#8221;</p>
<p>and</p>
<p>&#8220;npm -v&#8221;</p>
<p>and wait if there is a version number popping up. If you don&#8217;t have it yet installed I would recommend you to do it first. You can download an install Node.JS directly from <a href="https://nodejs.org/en/" target="_blank" rel="noopener noreferrer">here</a>. Personally I prefer to install Node.JS through <a href="https://github.com/creationix/nvm" target="_blank" rel="noopener noreferrer">nvm</a> (node version manager) because it gives you the flexibility to switch between different node versions at ease. I installed nvm via <a href="https://brew.sh/" target="_blank" rel="noopener noreferrer">homebrew</a> but you can also use curl or wget. There are many <a href="https://gist.github.com/nijicha/e5615548181676873118df79953cb709" target="_blank" rel="noopener noreferrer">instructions</a> on how to intstall it so I will not repeat that here but trust in you that you will manage it :)</p>
<p>Lets start:</p>
<ol>
<li>Install the gulp-cli in order to start gulp commands from your terminal with: &#8220;npm install -g gulp-cli<em>&#8220;</em></li>
<li>Create a new folder &#8220;gulp-example&#8221;</li>
<li>Within that folder create the following files:
<ol>
<li>package.json</li>
<li>gulpfile.js</li>
</ol>
</li>
<li>Within gulp-example create two subfolders &#8220;src&#8221; and &#8220;build&#8221;.</li>
<li>Open the src-folder and create the following files:
<ol>
<li>index.html</li>
<li>main.js</li>
<li>style.scss</li>
</ol>
</li>
</ol>
<p>If you are lazy you can use the following terminal command to setup everything:</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/6cc7053e72de8be959a6efe20c17e822">Gist</a>.</p>
<h3>Package.json</h3>
<p>The package.json stores among a few basic informations about your project all packages that need to either run for developing (devDependencies) or are mandatory for the final application (dependencies). By running <em>npm install</em> all specified packages will be downloaded and stored in a node_modules folder within your project.</p>
<p>In order to setup the build process mentioned in the introduction we need to download some plugins first. Everything what we need is specified in the devDependencies. Please copy the following content into your package.json:</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/afb4e816d1b13d01a7089eb8447e4536">Gist</a>.</p>
<p>Open your terminal and <em>cd</em> into your /gulp-example directory (if you used my provided command to setup everything you are already in the gulp-example directory). Run <em>npm install </em>in order to automatically download and install all node modules. Note that by the time you read this article some of the plugins might be outdated already. If you want to update your packages run <em>npm update </em>but be aware that incompability of versions might break the setup. If this happens go back to the specified setup here.</p>
<h3>Gulpfile.JS</h3>
<p>The gulpfile.js is the heart of our gulp setup in which we will write all our gulp tasks. If you are familiar with Javascript you will pickup gulp very quickly because it is essentially only writing functions.</p>
<h4>Compile SASS, Autoprefix, Minify, Sourcemaps</h4>
<p>Every gulpfile should start with the plugins that are used. Please note that I am using ES6 syntax. If you are not familiar with this please see my <a href="https://www.ilearnjavascript.com/es6/" target="_blank" rel="noopener noreferrer">es6 article series</a>. Since we also compile our sass/ scss to css we need to specify node-sass as our compiler.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/f036dbacd1ebf13fbd138ddc6ffd7573">Gist</a>.</p>
<p>Now we will write our first gulp task. The first argument of our task method is the name of our gulp task <span class="pl-pds">&#8216;</span>compile:sass<span class="pl-pds">&#8216;</span>. With the second argument we define a function that returns multiple chained methods. With gulp.src we specify where our style.scss is located. The &#8220;pipe&#8221; method takes in the output of the previous function, applies new functionality and passes it to a potential next function. Pipe-chaining is very common in gulp tasks and you will see a lot of them. In this case we run our sass compiling and add some error logging. Last but not least we output the compiled css (and any other file we will modify from now on) with gulp.dest into a temp folder. This is necessary for us to create at a later stage without any effort the same pathing for our production and development environment. We will clean this folder later up with another &#8220;clean&#8221;-task so it will not be visible for you in the end.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/7a1d74d658eeae45315604ab190b800c">Gist</a>.</p>
<p>Lets add also autoprefixing, minification and sourcemaps. The tasks are very self explanatory which is one of the great things about gulp.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/c6f3ac6f6574244d370d0d9cf2e219a1">Gist</a>.</p>
<h4>Transpile ES6+ to ES5 with Babel, Minify JS</h4>
<p>Before we can use <a href="https://babeljs.io/" target="_blank" rel="noopener noreferrer">babel</a> to transpile our Javascript ES6+ Code to browser compatible ES5 we need to create a &#8220;.babelrc&#8221; file and specify what presets we want to use. We will create the file within the root level of our app (where the gulpfile.js is). The setting &#8220;modules: false&#8221; prevents babel setting &#8220;use strict&#8221;. Not that I don&#8217;t like &#8220;use strict&#8221; (I am a big fan), but I want to be in control of where it is set. A .babelrc file is technically not necessary, it would also be possible to specify the config within the gulpfile, but I think it is nicer to have it in its own file. Babel will look automatically for a .babelrc file and use it if it is provided.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/1633b0687ca27725318044a2fe215251">Gist</a>.</p>
<p>Now we add the actual transpiling tasks to our gulpfile.js and a task for minification. Note that we need to require additional plugins for our new tasks.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/8a9f0c894e0a61b6970159d41c839d8f">Gist</a>.</p>
<h4>Combine minifier</h4>
<p>Since we have already two minifying tasks, we can combine them both into one task. It also gives us the chance to learn about a new gulp method <em>gulp.parallel</em>. As the name indicates this method allows to run both tasks simultaneously. The sibling of <em>gulp.parallel</em> is <em>gulp.series</em> which runs one task after another.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/41d8d0bc5b0ce1a5c3a4d7cbdeef5828">Gist</a>.</p>
<h4>Cleanup after ourselves</h4>
<p>Since we created a temp folder during the build process and don&#8217;t need it further we will create a task to automatically delete it.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/bea23535d7f225a3123d7155248f98f2">Gist</a>.</p>
<h4>index.html</h4>
<p>We can use gulp-inject to inject Javascript files and Stylesheet files into our index.html file. See how it is done in the following example (the commented lines are the placeholder which gulp automatically identifies and use for insertion):</p>
<p><em>Note that the index.html file is in the src subfolder of your project.</em></p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/483b094aa43ec1833db1abc675d0f08f">Gist</a>.</p>
<h4>style.scss</h4>
<p>Some SCSS for testing our setup. <em>Note that the style.scss file is in the src subfolder of your project.</em></p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/7e394ce06c5af9f930b75d2081f8cec2">Gist</a>.</p>
<h4>main.js</h4>
<p>Some Javascript for testing our setup.</p>
<p><em>Note that the main.js file is in the src subfolder of your project.</em></p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/66e2915a44facbc7f55dab691f6ee15d">Gist</a>.</p>
<h4>Transfer files</h4>
<p>Our stylesheet and javascript files are going to be served by a server which requires a path to the files. In order to make it easy for both our production and development server to serve the files we will create the same relative pathing and therefor transfer all files into a temp folder which sits inside our development and production base folder (gulp will create the folders by itself if they are not yet existing).</p>
<p>Lets start with transfering files for development:</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/572c948c3dc13c4b521da5c9f87860b7">Gist</a>.</p>
<p>Now we will  do the same for production:</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/61b774936c649c115e4ac25fb50eb11d">Gist</a>.</p>
<h4>Hot Reloading Live Server</h4>
<p>A great development experience includes a local webserver that automatically watches your files and reloads your browser tab on every saved code modification. This is how you do it:</p>
<p>First we will define a new const &#8220;connect&#8221;, require &#8220;gulp-connect&#8221; and make a task using it to connect to our server specifying the following specs:</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/947e9ea265abac0731043deefee2383d">Gist</a>.</p>
<p>The next task opens for our convenience the browser tab as soon as our server is started:</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/45697936704c8cfe83d7c2b409de6992">Gist</a>.</p>
<p>Now we will create a file watcher that observes our files and triggers a reload as soon as our files change and are saved:</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/ced1abc6fc617b7c469d189946d05b82">Gist</a>.</p>
<h4>Build development environment</h4>
<p>Let&#8217;s make a build specifically for our development area. We will leave out what we don&#8217;t need (minification) and add some additional features (server with file watcher and hot reloading):</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/9cbd4263680a483913fe12e7f5f8182d">Gist</a>.</p>
<p>Now lets tie it all together in one handy command (running the dev build, connecting to the development sever, open it and start the file watcher):</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/b73dd680844ea1e8761daf29ec379e3d">Gist</a>.</p>
<h4>Build production environment</h4>
<p>Lets combine all our tasks necessary for our production environment in one task &#8220;gulp prod&#8221; which we will call in series (one after another):</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/98bb9559cccbf5bc8b3bdfdde8ea21cb">Gist</a>.</p>
<h2>Try it out</h2>
<p>In order to test it we need to use the gulp-cli and open our terminal. Each command will take a few seconds to run. You will be notified about the process automatically through the gulp cli. If everything worked fine you should have a new folder build/prod or build/dev (depending on the command) with one index.html and a temp folder containing your style and javascript files.</p>
<p>Please &#8220;cd&#8221; in the root project folder (where the gulpfile.js is) and run the following commands:</p>
<h3>Build Development</h3>
<p>gulp dev</p>
<h3>Build dev and start hot reloading dev server</h3>
<p>gulp serve</p>
<h3>Build Production</h3>
<p>gulp prod</p>
<h2>Summary</h2>
<p>If you want to have the whole gulpfile at once I put it together for you here:</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/1453968fa2c706f11ae75651a69ec99a">Gist</a>.</p>
</div></section><br />

<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756">
#top .hr.hr-invisible.av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756{
height:50px;
}
</style>
<div  class='hr av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756 hr-invisible  avia-builder-el-3  el_after_av_textblock  el_before_av_comments_list '><span class='hr-inner '><span class="hr-inner-style"></span></span></div><br />
<div  class='av-buildercomment av-339ap2-f96642c7864cc12617740872af42902b'></div></p></div>
<p>The post <a href="https://www.ilearnjavascript.com/task-automation-with-gulpjs/">Task automation with Gulp.JS</a> appeared first on <a href="https://www.ilearnjavascript.com">I Learn Javascript</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>PlainJS: fade-in &#038; fade-out</title>
		<link>https://www.ilearnjavascript.com/plainjs-fadein-fadeout/</link>
		
		<dc:creator><![CDATA[ILJS]]></dc:creator>
		<pubDate>Sun, 24 Mar 2019 21:28:08 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[PlainJS]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[plainjs]]></category>
		<guid isPermaLink="false">https://www.ilearnjavascript.com/?p=1058</guid>

					<description><![CDATA[<p>How to build a performant and reusable fade-in and fade-out animation using plain javascript and the requestAnimationFrame method.</p>
<p>The post <a href="https://www.ilearnjavascript.com/plainjs-fadein-fadeout/">PlainJS: fade-in &#038; fade-out</a> appeared first on <a href="https://www.ilearnjavascript.com">I Learn Javascript</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975">
.flex_column.av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975{
border-radius:0px 0px 0px 0px;
padding:0px 0px 0px 0px;
}
</style>
<div  class='flex_column av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975 av_one_full  avia-builder-el-0  avia-builder-el-no-sibling  blogpost first flex_column_div av-zero-column-padding  '     ><p>
<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-av_heading-4677f5c828b854f68448a0f51c6f4ecb">
#top .av-special-heading.av-av_heading-4677f5c828b854f68448a0f51c6f4ecb{
padding-bottom:10px;
}
body .av-special-heading.av-av_heading-4677f5c828b854f68448a0f51c6f4ecb .av-special-heading-tag .heading-char{
font-size:25px;
}
.av-special-heading.av-av_heading-4677f5c828b854f68448a0f51c6f4ecb .av-subheading{
font-size:14px;
}
</style>
<div  class='av-special-heading av-av_heading-4677f5c828b854f68448a0f51c6f4ecb av-special-heading-h1 blockquote modern-quote  avia-builder-el-1  el_before_av_textblock  avia-builder-el-first '><h1 class='av-special-heading-tag '  itemprop="headline"  >PlainJS: fade-in <span class='special_amp'>&amp;</span> fade-out</h1><div class='av-subheading av-subheading_below'><p>8min read</p>
</div><div class="special-heading-border"><div class="special-heading-inner-border"></div></div></div><br />
<section  class='av_textblock_section av-484hle-406149cc130335ef8e30129389794269 '   itemscope="itemscope" itemtype="https://schema.org/BlogPosting" itemprop="blogPost" ><div class='avia_textblock'  itemprop="text" ><p>We use fade-in and -out animations on elements to give our users a more pleasant experience when they view our website or app. We use them for elements that get <a href="https://www.ilearnjavascript.com/glossary/#toggle-id-5" target="_blank" rel="noopener">lazyloaded</a>, toggled or whenever we want to make the appearance/ disappearance of something look smooth.</p>
<p>Back in the days most developers probably used jQuery to do the job since it was part of most websites anyway and provided a very convenient way to do it (<a href="https://api.jquery.com/fadeIn/" target="_blank" rel="noopener noreferrer">fadeIn</a>/ <a href="https://api.jquery.com/fadeout/" target="_blank" rel="noopener noreferrer">fadeOut</a>). With jQuery slowly fading out from web development I want to show in this article how to make a fadeIn and fadeOut function in plain javascript.</p>
<p>In order to make an element fade-in/fade-out we essentially need to change its opacity from 0 to 1 in a timeframe that is detectable for the human eye. Please note that changing the opacity of an element can also be done purely via CSS3 and if we just need to do that it is the most preferable because most performant solution. The way how to achieve this with CSS3 would be to either use the</p>
<p><a href="https://www.w3schools.com/css/css3_transitions.asp" target="_blank" rel="noopener noreferrer">transition property:</a></p>
<ul>
<li>set the opacity of the element to either zero or 1 (depending on whether fade-in or fade-out is desired)</li>
<li>set<em> transition: [property] [time] [easing] </em>=&gt; for example <em>transition: opacity .4s ease</em></li>
<li>apply via javascript a new class .fadein/.fadeout to the element with opacity set to zero (fade-out) or 1 (fade-in)</li>
</ul>
<p>or via a</p>
<p><a href="https://css-tricks.com/snippets/css/keyframe-animation-syntax/" target="_blank" rel="noopener noreferrer">keyframe animation:</a></p>
<ul>
<li>create a new keyframe animation @keyframe fadein (or @keyframe fadeout) that goes from <em>opacity: 0</em> to <em>opacity: 1</em> (or <em>opacity: 1</em> to <em>opacity: 0</em>)</li>
<li>apply via javascript a new class .fadein/.fadeout that has all required animation properties =&gt; e.g. <em>animation: fadein .4s linear</em></li>
</ul>
<p>However, with both of these techniques an element that gets faded out still would occupy blank space. It would be invisible but not gone (similar to <em>visibility: hidden</em>)<em>. </em>Sometimes we want the element to be gone and not take any space after it is faded out. We want it to be set to<em> display: none</em>. We can achieve this easily with Javascript.</p>
<p>Please note that I am using ES6 syntax. If you are not familiar with this please see my <a href="https://www.ilearnjavascript.com/es6/" target="_blank" rel="noopener">es6 article series</a> and keep in mind that it needs to be transpiled to ES5 for older browsers via <a href="https://babeljs.io/" target="_blank" rel="noopener noreferrer">babel.io</a>.</p>
<h2>fadeIn</h2>
<p>First we assign an anonymus function to our variable fadeIn that has an element (el) as it&#8217;s first parameter, an option to make a smooth fade-in animation which defaults to true as it&#8217;s second parameter and displayStyle &#8216;block&#8217; as default for it&#8217;s third parameter. We start with setting the elements opacity to zero and apply <em>display: block</em> because we assume that it&#8217;s current value could be <em>display: none</em>. If smooth is not <em>false</em> we declare a variable with <em>let</em> <em>opacity</em>, starting from zero, and also declare another variable <em>let</em> <em>request,</em> without assigning any value yet.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/8d1e97f48a8751975fe2b6973d5889cd">Gist</a>.</p>
<p>Afterwards we create another anonymus function that is bound to the variable <em>animation</em> and sets the opacity of our element equal to the result of the value from our previously declared opacity variable plus 0.04. After the first iteration the value would be 0 + 0.04 = 0.04, in the second round 0.08 and so on until it reaches the condition being higher or equal to 1.</p>
<p>I chose 0.04 as it creates a fadeIn animation in approximately 400ms. Feel free to play with the numbers to make it optimal for your case. You can use <em>console.time()</em> (in the beginning of your function run) and <em>console.timeEnd()</em> (in the end of your function run) to understand the timings.</p>
<p>Once the condition is passed we make sure that opacity is exactly one and cancel our animation frame (see next step) via the cancelAnimationFrame(fn) method.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/47436e9bace99336d47b73f3417134eb">Gist</a>.</p>
<p>We use <a href="https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame" target="_blank" rel="noopener noreferrer">requestAnimationFrame</a> for creating the iteration because this way we give the control to the browser when to re-render the layout and not force it on it as we would do with either <a href="https://www.w3schools.com/jsref/met_win_settimeout.asp" target="_blank" rel="noopener noreferrer">setTimeout</a> or <a href="https://www.w3schools.com/jsref/met_win_setinterval.asp" target="_blank" rel="noopener noreferrer">setInterval</a>. The &#8220;problem&#8221; with using a recursive setTimeout or setInterval for drawing our animations is that we command the browser at a predefined time to run our animation. Since the browser is single threaded this intervention could lead to a sluggish experience as other javascript (potentially with other animations) may need to be executed too. With requestAnimationFrame the browser controls the redrawing of the layout at an eye-friendly approximate 60hz framerate and provides us with a smooth animation that is not conflicting with any other javascript tasks which may run simultaneously. To be fair it is unlikely that our fade-in or fade-out animation would cause a sluggish experience for the user because it is very fast over but it is generally good practice to use requestAnimationFrame for animations and that&#8217;s why we will go with it.</p>
<p>We assign an anonymus function to our rAf variable that assigns a recursive call to itself via the requestAnimationFrame method. In other words we let the function call itself. Please be careful when you do recursive calls and always define a condition under which it gets cancelled. Otherwise you will create an infinite loop and crash your system/ browser.</p>
<p>We assign the function call to our variable <em>request</em> which we declared earlier. The reason we declared <em>request</em> outside of the rAf function is scope. We need to be able to access it via the cancelAnimationFrame method from within the animation function. We run animation and alter the opacity of our element on each iteration.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/a85145d737884abbecc370c6acb1fc8d">Gist</a>.</p>
<p>Finally we call our rAf function to get it all started. In case you wonder about the else condition which runs when <em>smooth</em> is set to false: Technically it does ruin the &#8220;fadein experience&#8221; because it would set the element&#8217;s opacity &#8220;instantly&#8221; to 1 but it makes the function more versatile and we can achieve that only with a few lines of code.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/ac50beeadaf1dafc53c1a0e12154e671">Gist</a>.</p>
<h2>fadeOut</h2>
<p>The fadeOut method is basically an inverted function of our previous explained fadeIn method. I will not go through it in such detail because it is essentially the same as the fadein method just altering the opacity from 1 back to zero and applying <em>display: none</em> in the end right before the iteration gets stopped to leave no blank space behind.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/f1faf3280473e7b5a3830e1c661eb846">Gist</a>.</p>
</div></section><br />

<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756">
#top .hr.hr-invisible.av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756{
height:50px;
}
</style>
<div  class='hr av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756 hr-invisible  avia-builder-el-3  el_after_av_textblock  el_before_av_comments_list '><span class='hr-inner '><span class="hr-inner-style"></span></span></div><br />
<div  class='av-buildercomment av-2ruuea-5d0b64f49ac6d97814b6ef45d01162b0'></div></p></div>
<p>The post <a href="https://www.ilearnjavascript.com/plainjs-fadein-fadeout/">PlainJS: fade-in &#038; fade-out</a> appeared first on <a href="https://www.ilearnjavascript.com">I Learn Javascript</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>ES8: async await</title>
		<link>https://www.ilearnjavascript.com/es8-async-await/</link>
		
		<dc:creator><![CDATA[ILJS]]></dc:creator>
		<pubDate>Mon, 11 Mar 2019 22:41:00 +0000</pubDate>
				<category><![CDATA[ES6+]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[es6+]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://www.ilearnjavascript.com/?p=1024</guid>

					<description><![CDATA[<p>Async await improves how we handle asynchronous code. It is built on top of ES6 Promises and aims to give a cleaner and more concise syntax.</p>
<p>The post <a href="https://www.ilearnjavascript.com/es8-async-await/">ES8: async await</a> appeared first on <a href="https://www.ilearnjavascript.com">I Learn Javascript</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975">
.flex_column.av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975{
border-radius:0px 0px 0px 0px;
padding:0px 0px 0px 0px;
}
</style>
<div  class='flex_column av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975 av_one_full  avia-builder-el-0  avia-builder-el-no-sibling  blogpost first flex_column_div av-zero-column-padding  '     ><p>
<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-av_heading-eea419eebf352b6340575a7a24eb24a1">
#top .av-special-heading.av-av_heading-eea419eebf352b6340575a7a24eb24a1{
padding-bottom:10px;
}
body .av-special-heading.av-av_heading-eea419eebf352b6340575a7a24eb24a1 .av-special-heading-tag .heading-char{
font-size:25px;
}
.av-special-heading.av-av_heading-eea419eebf352b6340575a7a24eb24a1 .av-subheading{
font-size:14px;
}
</style>
<div  class='av-special-heading av-av_heading-eea419eebf352b6340575a7a24eb24a1 av-special-heading-h1 blockquote modern-quote  avia-builder-el-1  el_before_av_textblock  avia-builder-el-first '><h1 class='av-special-heading-tag '  itemprop="headline"  >ES8: async await</h1><div class='av-subheading av-subheading_below'><p>7min read</p>
</div><div class="special-heading-border"><div class="special-heading-inner-border"></div></div></div><br />
<section  class='av_textblock_section av-3rzn2o-833a4470f9295a6b247b6e1e43c06906 '   itemscope="itemscope" itemtype="https://schema.org/BlogPosting" itemprop="blogPost" ><div class='avia_textblock'  itemprop="text" ><p>Async await improves how we handle asynchronous code. It is built on top of <a href="https://www.ilearnjavascript.com/es6-promises/" target="_blank" rel="noopener noreferrer">ES6 Promises</a> (our rescue from <a href="/glossary/#toggle-id-4" target="_blank" rel="noopener noreferrer">callback hell</a>) and aims to give a cleaner and more concise syntax. Similar to <a href="https://www.ilearnjavascript.com/es6-classes/" target="_blank" rel="noopener noreferrer">ES6 Classes</a> and prototypal inheritance the async await syntax is basically syntactic sugar for Promises.</p>
<h2>How it works</h2>
<p>The syntax for async await is actually quite intuitive. We use the keyword <em>async</em> to define an asynchronous function. Within the async function we can use the keyword <em>await</em> to literally wait until a Promise is resolved/ rejected (note: fetch also returns a Promise). Another benefit of async await is that we can use try/ catch statements as in synchronous code to do our error handling.</p>
<p>In the following example we will create an async function, fetch the random joke API and await the returned Promise from the API call to be resolved and parsed to json. Then we call the async function getJoke and log the data we receive as soon as getJoke is processed and has a value returned to us. We execute this in a try/ catch statement to do the error handling in case the API call is rejected.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/13bc1c87fa0cee1f195a042c997c37c5">Gist</a>.</p>
<h2>Async await is non blocking</h2>
<p>Async await is non blocking code. This is especially important as the Browser has only one single thread for all the tasks (parse HTML, apply CSS, render layout, execute Javascript etc.) and Javascript code is &#8220;usually&#8221; blocking. Using async code can help to improve the performance and user experience of an app/ website.</p>
<p>In the following example we will create a Promise which will resolve after 2 seconds, clearing our interval &#8220;tick&#8221;. Then we create an async function asyncCall which calls our Promise resolveAfter2Seconds and awaits its result &#8220;resolved&#8221; and logs it. The interval tick runs every 100ms and logs &#8220;tick&#8221; to the console. Immediately after the tick interval is set up, asyncCall is executed. Since setInterval is by default also asynchronous and the way the Javascript event loop works, &#8220;calling&#8221; from within the asyncCall function gets logged before the first &#8220;tick&#8221; is logged.</p>
<p>Tick will log exactly 20 times (2000ms) until the Promise is resolved and the interval is cleared. This example shows that async await handles the Promise in the background until it is resolved/ rejected.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/28afd4e5345e983f0031112d05c670e4">Gist</a>.</p>
<h2>Callbacks vs Promises vs async await</h2>
<p>Async await gives us arguably a nicer and more concise syntax over Promises and unquestionable over multiple nested callbacks. But judge for yourself comparing callbacks, Promises and async await:</p>
<h3>Callback(hell)</h3>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/6967a814aa877a42f2cb3478a1288be8">Gist</a>.</p>
<h3>ES6 Promises</h3>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/80d82902b8a0a51927330e46d46baacc">Gist</a>.</p>
<h3>Async await</h3>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/a0af3c4d06f201207d8c7eb61b81e7e7">Gist</a>.</p>
<p>I am personally a big fan of async await and thanks to Babel it is easy integratable into our code. For everyone who doesn&#8217;t transpile their code: async await is not fully supported yet (and won&#8217;t be as long as we need to support IE11. See: <a href="https://caniuse.com/#search=async">https://caniuse.com/#search=async</a>)</p>
<p>Let me know what you think in the comments.</p>
</div></section><br />

<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756">
#top .hr.hr-invisible.av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756{
height:50px;
}
</style>
<div  class='hr av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756 hr-invisible  avia-builder-el-3  el_after_av_textblock  el_before_av_comments_list '><span class='hr-inner '><span class="hr-inner-style"></span></span></div><br />
<div  class='av-buildercomment av-2j8p8w-410812da681fe4d135e1c91fb9db8328'></div></p></div>
<p>The post <a href="https://www.ilearnjavascript.com/es8-async-await/">ES8: async await</a> appeared first on <a href="https://www.ilearnjavascript.com">I Learn Javascript</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>ES6: Modules</title>
		<link>https://www.ilearnjavascript.com/es6-modules/</link>
		
		<dc:creator><![CDATA[ILJS]]></dc:creator>
		<pubDate>Sun, 10 Mar 2019 09:27:11 +0000</pubDate>
				<category><![CDATA[ES6+]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[es6+]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://www.ilearnjavascript.com/?p=796</guid>

					<description><![CDATA[<p>With ECMAScript 2015 (ES6) Modules become finally native to modern Browsers. In this article I will explain how you can use them in your projects.</p>
<p>The post <a href="https://www.ilearnjavascript.com/es6-modules/">ES6: Modules</a> appeared first on <a href="https://www.ilearnjavascript.com">I Learn Javascript</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975">
.flex_column.av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975{
border-radius:0px 0px 0px 0px;
padding:0px 0px 0px 0px;
}
</style>
<div  class='flex_column av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975 av_one_full  avia-builder-el-0  avia-builder-el-no-sibling  blogpost first flex_column_div av-zero-column-padding  '     ><p>
<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-av_heading-adc9f3652e958ac1a6f75e8f4e9a0396">
#top .av-special-heading.av-av_heading-adc9f3652e958ac1a6f75e8f4e9a0396{
padding-bottom:10px;
}
body .av-special-heading.av-av_heading-adc9f3652e958ac1a6f75e8f4e9a0396 .av-special-heading-tag .heading-char{
font-size:25px;
}
.av-special-heading.av-av_heading-adc9f3652e958ac1a6f75e8f4e9a0396 .av-subheading{
font-size:14px;
}
</style>
<div  class='av-special-heading av-av_heading-adc9f3652e958ac1a6f75e8f4e9a0396 av-special-heading-h1 blockquote modern-quote  avia-builder-el-1  el_before_av_textblock  avia-builder-el-first '><h1 class='av-special-heading-tag '  itemprop="headline"  >ES6: Modules</h1><div class='av-subheading av-subheading_below'><p>8min read</p>
</div><div class="special-heading-border"><div class="special-heading-inner-border"></div></div></div><br />
<section  class='av_textblock_section av-gs2r8-904cacc4c99d2dbf28bd17b8c81e275c '   itemscope="itemscope" itemtype="https://schema.org/BlogPosting" itemprop="blogPost" ><div class='avia_textblock'  itemprop="text" ><p>With ECMAScript 2015 (ES6) Modules become finally native to modern Browsers. In JavaScript Modules represent small units of independent, reusable code. They essentially make our code more maintainable and flexible. One file could contain one or multiple Modules. We can import and export them as per need. Therefore multiple Modules combined could also make up a larger Module. They are the foundation of many JavaScript design patterns and are critically necessary when building any non-trivial JavaScript-based application.</p>
<p>This being said, the concept of Modules itself is not new to the Javascript community. Developers so far usually fall back to one of the following options</p>
<ul>
<li>load multiple Javascript files into the Document (very bad for performance because each file needs to be requested and served individually)</li>
<li>use separate Javascript files for Development and concatenate them into one file for Production (better performance-wise but fairly hard to maintain)</li>
</ul>
<p>or the modern approach</p>
<ul>
<li>use a Library such as CommonJS or AMD (requireJS) to do the job (defacto standard which tools like Webpack make use of)</li>
</ul>
<h2>How it works</h2>
<p>We declare our script tag with type &#8220;module&#8221; and let the Browser this way know that it is an ES6 Module.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/c81dbe94979f3db33ddced7719a1af90">Gist</a>.</p>
<p>We differentiate between named exports and default exports. We can have multiple named exports per file and one default export per file. With the keyword <em>export</em> we let the Javascript engine know that we want to export this Variable, Object, Array, Function or Class (technically also a Function). ES6 Modules are automatically strict-mode code, even if we don’t declare them with &#8220;use strict&#8221;. Also, everything declared within a Module is scoped to this Module and not automatically Global. The Scope in Javascript from top to bottom is:</p>
<ul>
<li>Global scope</li>
<li>Module scope</li>
<li>Function scope</li>
<li>Block scope</li>
</ul>
<h3>Named Export</h3>
<p>In the following example we will export multiple named variables, each representing a different Module. For simplicity we will store them all in one file but each of them could generally also be in it&#8217;s own file.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/5b87bd7c80bbdd1ac20cc4bc77695ce0">Gist</a>.</p>
<h3>Import named export</h3>
<p>In our index.js file we <em>import</em> module1, module2 and module3 from modules.js. When we <em>import</em> them as named exports we need to enclose them in brackets and use the correct name that was specified in the export. Then we will insert them into our index.html Document.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/70dc1a9c02d0a3b34f096b16d44afb09">Gist</a>.</p>
<h3>Default Exports</h3>
<p>When we make a default export we don&#8217;t specify a name. We just write</p>
<ul>
<li><em>export default function foo()</em></li>
<li><em>export default { foo: &#8216;bar&#8217; }</em></li>
<li><em>export default [&#8216;arr1‘]</em></li>
<li><em>export default &#8216;string&#8217;</em></li>
</ul>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/87bae57783d94041d3525816f3bbd72c">Gist</a>.</p>
<h3>Import default export</h3>
<p>When we import a default export we don&#8217;t enclose it in brackets and can choose any name for it. In our example we will call it defaultModule for clarity.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/9f3b7b1aa6e4badcc5694477be939584">Gist</a>.</p>
<p>ES6 Modules, allthough becoming now native to modern Browsers, will at the current stage most probably not change how code is organized in most existing projects. There is no real benefit of replacing native ES6 Modules with whatever Library is currently used. Especially since Browsers such as IE11 and older Browserversions of modern Browsers don&#8217;t support ES6 Modules at this time fully and therefore require some kind of fallback: <a href="https://caniuse.com/#search=modules">https://caniuse.com/#search=modules</a></p>
<p>But it is only a matter of time until Modules are going to be the new standard and especially for smaller projects that don&#8217;t have an elaborate build process it could be a real benefit to use the native implementation.</p>
</div></section><br />

<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756">
#top .hr.hr-invisible.av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756{
height:50px;
}
</style>
<div  class='hr av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756 hr-invisible  avia-builder-el-3  el_after_av_textblock  el_before_av_comments_list '><span class='hr-inner '><span class="hr-inner-style"></span></span></div><br />
<div  class='av-buildercomment av-9vxvw-e2fcc71aac98f2d4e886686b1f563976'></div></p></div>
<p>The post <a href="https://www.ilearnjavascript.com/es6-modules/">ES6: Modules</a> appeared first on <a href="https://www.ilearnjavascript.com">I Learn Javascript</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>PlainJS: postMessage() and iframes</title>
		<link>https://www.ilearnjavascript.com/plainjs-postmessage-and-iframes/</link>
		
		<dc:creator><![CDATA[ILJS]]></dc:creator>
		<pubDate>Wed, 06 Mar 2019 19:43:51 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[PlainJS]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[plainjs]]></category>
		<guid isPermaLink="false">https://www.ilearnjavascript.com/?p=827</guid>

					<description><![CDATA[<p>How to communicate between a window and an embedded iFrame via postMessage.</p>
<p>The post <a href="https://www.ilearnjavascript.com/plainjs-postmessage-and-iframes/">PlainJS: postMessage() and iframes</a> appeared first on <a href="https://www.ilearnjavascript.com">I Learn Javascript</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975">
.flex_column.av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975{
border-radius:0px 0px 0px 0px;
padding:0px 0px 0px 0px;
}
</style>
<div  class='flex_column av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975 av_one_full  avia-builder-el-0  avia-builder-el-no-sibling  blogpost first flex_column_div av-zero-column-padding  '     ><p>
<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-jzu3o4qe-b1146c47711287d85e4bc89ff46cb642">
#top .av-special-heading.av-jzu3o4qe-b1146c47711287d85e4bc89ff46cb642{
padding-bottom:10px;
}
body .av-special-heading.av-jzu3o4qe-b1146c47711287d85e4bc89ff46cb642 .av-special-heading-tag .heading-char{
font-size:25px;
}
.av-special-heading.av-jzu3o4qe-b1146c47711287d85e4bc89ff46cb642 .av-subheading{
font-size:14px;
}
</style>
<div  class='av-special-heading av-jzu3o4qe-b1146c47711287d85e4bc89ff46cb642 av-special-heading-h1 blockquote modern-quote  avia-builder-el-1  el_before_av_textblock  avia-builder-el-first '><h1 class='av-special-heading-tag '  itemprop="headline"  >PlainJS: postMessage() and iFrames</h1><div class='av-subheading av-subheading_below'><p>12min read</p>
</div><div class="special-heading-border"><div class="special-heading-inner-border"></div></div></div><br />
<section  class='av_textblock_section av-jsxpv2aj-a70af1baa44283dc0386ec397195a3ff '   itemscope="itemscope" itemtype="https://schema.org/BlogPosting" itemprop="blogPost" ><div class='avia_textblock'  itemprop="text" ><p>Many websites, especially blogs or newssites, earn money with advertising. A common way to display these ads is through <a href="https://www.ilearnjavascript.com/glossary/#toggle-id-3" target="_blank" rel="noopener noreferrer">iFrames</a>. In this article I will explain how to communicate between a <em>window</em> and an embedded iFrame.</p>
<p>In general the <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy">same-origin policy</a> forbids scripts on different pages to access each other unless they share the same protocol, port number and host. The <em>window.postMessage() </em>method enables cross-origin communication between a window object and an embedded iFrame and therefore provides a mechanism to circumvent this restriction. PostMessage used incorrectly could potentially make your website vulnerable for crosssite-scripting attacks. It is important to be aware of these pitfalls before we use it in production.</p>
<h2>Listening for a message</h2>
<p>First we need to setup a listener function on our <em>window</em> (we will call it outer window from now on to differentiate since each iFrame also owns its own window) which executes code when the <em>message</em> event gets fired from our iFrame via <em>postMessage()</em>. Allowing the outer window to receive messages from an embedded iframe is a potential risk for cross-site scripting attacks. It is therefore important to verify the <em>event.origin</em> of the <em>window</em> that send the message and only allow controlled <em>event.data</em> to reach our outer window. Lets go through the terminology first:</p>
<ol>
<li><em>event.origin</em> = The origin of the window that sent the message at the time <em>postMessage</em> was called. We want this to be a domain we trust.</li>
<li><em>event.data</em> = The data that gets passed through with the <em>postMessage</em> function.</li>
<li><em>event.source</em> = Reference to the window that sent the message. In our case the iFrame.</li>
<li><em>postMessage()</em> = function we call in order to pass data to another window.</li>
</ol>
<p>We will create a receiveMessage Function on our outer window, check if the <em>event.origin</em> is the domain of our iframe and if <em>event.data</em> is the message we exppect. Then we listen via the addEventListener method for the <em>message</em> event and bind the <em>receiveMessage()</em> function to it.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/c9095d2d5bb1e74d176372502faac31d">Gist</a>.</p>
<p>We could generally make it even more safe by restricting <em>event.data</em> to a specific length and test for <em>typeof string</em> since we expect a string. So lets add this:</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/451ecda2e7c4de2bc9b95a28dac3cb02">Gist</a>.</p>
<h2>Sending a message</h2>
<p>We send a message via the postMessage function. The syntax for it is:</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/7b2fb314e732e054e003d1287b47dcc6">Gist</a>.</p>
<p>The targetWindow in our case could be either <em>window.parent</em> (immediate parent window) or <em>window.top</em> (the most far outer window) because they are the same in our scenario. But since it is generally possible to nest multiple Iframes it is important to be aware of the difference. In doubt pick window.top because it will definitely reach the client window and not another parent Iframe by accident. As message we will send &#8220;message we expect&#8221; and the targetOrigin is the domain of our outer window&#8217;s domain.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/4105bc66799179b611321558885a2292">Gist</a>.</p>
<p>Note: Avoid using &#8220;*&#8221; for the targetOrigin and specify it properly instead with the domain of your outer window.</p>
<h3>Working Example</h3>
<p>Here is an working example. If you want to test it just</p>
<ol>
<li>copy the code from both files (I named them window.html and iframe.html) into a directory</li>
<li>setup a small local server (I use for this https://www.npmjs.com/package/http-server) for each of the files</li>
<li>run it within the directory and choose to display window.html for the server located on http://127.0.0.1:8080 and the iframe.html on http://127.0.0.1:8081</li>
<li>play with it</li>
</ol>
<h4>window.html</h4>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/0a793e2732e17788900c12fbf0b37c91">Gist</a>.</p>
<h4>Iframe.html</h4>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/8edbf5e143c962b8f3e85c1997614aac">Gist</a>.</p>
<h2>Two Way Communication</h2>
<p>So far we looked at a one way communication in which we receive a message from an iFrame. But what if we want to have a two way communication and send something back from our outer window to the iFrame? If we embed our iFrame on the <strong>same domain</strong> as the window we can use the <em>postMessage()</em> function and <em>event.source</em> for achieving exactly this. We use <em>event.source</em> to get a reference to our iframe and trigger the <em>postMessage()</em> function from it.</p>
<h3>Working Example</h3>
<p>We will trigger <em>event.source.postMessage()</em> with a one second delay from our window.html to visualize the chronology of the functions getting triggered. In order for the iframe.html to show a response we also need to setup a<em> receiveMessage()</em> function there and bind it to the iframe&#8217;s <em>window</em> via <em>window.addEventlistener(&#8216;message&#8217;, receiveMessage, false)</em>.</p>
<ol>
<li>copy the code from both files (I named them window.html and iframe.html) into a directory</li>
<li>setup a small local server (I use for this https://www.npmjs.com/package/http-server) for both of the files</li>
<li>run it within the directory and choose to display window.html for the server located on http://127.0.0.1:8080</li>
<li>play with it</li>
</ol>
<h4>window.html</h4>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/9d4855b9a189b1144d675c1cb8f52179">Gist</a>.</p>
<h4>Iframe.html</h4>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/385e3f6af6d301e140baf4c03249e08f">Gist</a>.</p>
<h2>Security concerns</h2>
<p>A listener for a <em>message</em> event should only be applied to your website if you generally expect a postMessage. Cross-site scripting attacks are a real risk. Failure to check the <em>origin, data </em>and potentially<em> source </em>properties could make your website vulnerable. Always specify an exact target origin and do not just use &#8220;*&#8221; with <em>postMessage()</em> to send data to other windows. A potential attacker could change the location of the window and intercept the data sent using <em>postMessage()</em>. Add extra levels of security by restricting the <em>event.data</em> to a type and length (if applicable).</p>
</div></section><br />

<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756">
#top .hr.hr-invisible.av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756{
height:50px;
}
</style>
<div  class='hr av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756 hr-invisible  avia-builder-el-3  el_after_av_textblock  el_before_av_comments_list '><span class='hr-inner '><span class="hr-inner-style"></span></span></div><br />
<div  class='av-buildercomment av-7d32r-9d486d985b57f31e9e677555abdb4223'></div></p></div>
<p>The post <a href="https://www.ilearnjavascript.com/plainjs-postmessage-and-iframes/">PlainJS: postMessage() and iframes</a> appeared first on <a href="https://www.ilearnjavascript.com">I Learn Javascript</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>ES6: Rest Parameter</title>
		<link>https://www.ilearnjavascript.com/es6-rest-parameter/</link>
		
		<dc:creator><![CDATA[ILJS]]></dc:creator>
		<pubDate>Sun, 03 Mar 2019 11:52:17 +0000</pubDate>
				<category><![CDATA[ES6+]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[es6+]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://www.ilearnjavascript.com/?p=718</guid>

					<description><![CDATA[<p>The Rest Paramameter collects all the remaining elements into an array. It is a sibling of the Spread Operator and uses the same syntax of three dots "...".</p>
<p>The post <a href="https://www.ilearnjavascript.com/es6-rest-parameter/">ES6: Rest Parameter</a> appeared first on <a href="https://www.ilearnjavascript.com">I Learn Javascript</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975">
.flex_column.av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975{
border-radius:0px 0px 0px 0px;
padding:0px 0px 0px 0px;
}
</style>
<div  class='flex_column av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975 av_one_full  avia-builder-el-0  avia-builder-el-no-sibling  blogpost first flex_column_div av-zero-column-padding  '     ><p>
<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-av_heading-2bf2dd9cc7a03e10963953850e4ba35b">
#top .av-special-heading.av-av_heading-2bf2dd9cc7a03e10963953850e4ba35b{
padding-bottom:10px;
}
body .av-special-heading.av-av_heading-2bf2dd9cc7a03e10963953850e4ba35b .av-special-heading-tag .heading-char{
font-size:25px;
}
.av-special-heading.av-av_heading-2bf2dd9cc7a03e10963953850e4ba35b .av-subheading{
font-size:14px;
}
</style>
<div  class='av-special-heading av-av_heading-2bf2dd9cc7a03e10963953850e4ba35b av-special-heading-h1 blockquote modern-quote  avia-builder-el-1  el_before_av_textblock  avia-builder-el-first '><h1 class='av-special-heading-tag '  itemprop="headline"  >ES6: Rest Parameter</h1><div class='av-subheading av-subheading_below'><p>5min read</p>
</div><div class="special-heading-border"><div class="special-heading-inner-border"></div></div></div><br />
<section  class='av_textblock_section av-jssv0bgo-2bba0c68031560dc18f0dbe9654fc1d9 '   itemscope="itemscope" itemtype="https://schema.org/BlogPosting" itemprop="blogPost" ><div class='avia_textblock'  itemprop="text" ><p>The Rest Paramameter collects all the remaining elements into an array. It is the sibling of the <a href="https://www.ilearnjavascript.com/es6-spread-operator/">Spread Operator</a> and uses the same syntax of three dots &#8220;&#8230;&#8221; preceeding it.</p>
<h2>Sum up function parameters</h2>
<p>The typical usecase for the Rest Paramter is to sum up all remaining parameters of a function which we don&#8217;t want to specify. In this case we sum up all the adress data into one array.</p>
<p><strong>Note</strong>: The Rest Parameter can only be used at the end after all other parameters have been specified.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/2e0b6d9c21ba434849a40644f2cb5c95">Gist</a>.</p>
<p>If we want to output the adress as a String instead of an array we can use the <a href="https://www.ilearnjavascript.com/es6-spread-operator/">Spread Operator</a>to do it.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/8c70d3a3e366a22ed837a934366c8354">Gist</a>.</p>
<h2>Rest Paramter vs Arguments Object</h2>
<p>Dont cofuse the Rest Paramter with the Arguments Object in Javascript. A short recap: The Arguments object allows us to access all arguments that have been passed into the function in form of an array-like object.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/e6b3324b9c7a293e76e7a844594869e9">Gist</a>.</p>
<p>There are three main differences:</p>
<ul>
<li>The arguments object contains all arguments passed to the function while the Rest Parameter only contains the one&#8217;s that haven&#8217;t been specified at the end of the parameters list.</li>
<li>The arguments object is in contrary to the Rest Parameter only an array-like object which means it inherits not the same methods (e.g. sort, map, filter) as a real array. The Rest Paramter is an instance of the Array Object and therefor has full access to all its methods.</li>
<li>the arguments object has additional functionality specific to itself (like the calleeproperty).</li>
</ul>
<h2>Rest Parameter in Destructuring</h2>
<p>The Rest Paramater comes in really handy when used with <a href="https://www.ilearnjavascript.com/es6-descructuring/">Destructuring</a> to collect all non-specified values in an array.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/732b7a454734ea42ce7fc13ba327ce1f">Gist</a>.</p>
</div></section><br />

<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756">
#top .hr.hr-invisible.av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756{
height:50px;
}
</style>
<div  class='hr av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756 hr-invisible  avia-builder-el-3  el_after_av_textblock  el_before_av_comments_list '><span class='hr-inner '><span class="hr-inner-style"></span></span></div><br />
<div  class='av-buildercomment av-15jxa-39b448e935f3a8616855caac3db425ae'></div></p></div>
<p>The post <a href="https://www.ilearnjavascript.com/es6-rest-parameter/">ES6: Rest Parameter</a> appeared first on <a href="https://www.ilearnjavascript.com">I Learn Javascript</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>ES6: Classes</title>
		<link>https://www.ilearnjavascript.com/es6-classes/</link>
		
		<dc:creator><![CDATA[ILJS]]></dc:creator>
		<pubDate>Sun, 03 Mar 2019 10:54:55 +0000</pubDate>
				<category><![CDATA[ES6+]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[es6+]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://www.ilearnjavascript.com/?p=700</guid>

					<description><![CDATA[<p>Classes in Javascript - Sugarcoat for prototypal inheritance.</p>
<p>The post <a href="https://www.ilearnjavascript.com/es6-classes/">ES6: Classes</a> appeared first on <a href="https://www.ilearnjavascript.com">I Learn Javascript</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975">
.flex_column.av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975{
border-radius:0px 0px 0px 0px;
padding:0px 0px 0px 0px;
}
</style>
<div  class='flex_column av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975 av_one_full  avia-builder-el-0  avia-builder-el-no-sibling  blogpost first flex_column_div av-zero-column-padding  '     ><p>
<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-av_heading-df9d9d1fae884479b87de8f00f1a544a">
#top .av-special-heading.av-av_heading-df9d9d1fae884479b87de8f00f1a544a{
padding-bottom:10px;
}
body .av-special-heading.av-av_heading-df9d9d1fae884479b87de8f00f1a544a .av-special-heading-tag .heading-char{
font-size:25px;
}
.av-special-heading.av-av_heading-df9d9d1fae884479b87de8f00f1a544a .av-subheading{
font-size:14px;
}
</style>
<div  class='av-special-heading av-av_heading-df9d9d1fae884479b87de8f00f1a544a av-special-heading-h1 blockquote modern-quote  avia-builder-el-1  el_before_av_textblock  avia-builder-el-first '><h1 class='av-special-heading-tag '  itemprop="headline"  >ES6: Classes</h1><div class='av-subheading av-subheading_below'><p>20min read</p>
</div><div class="special-heading-border"><div class="special-heading-inner-border"></div></div></div><br />
<section  class='av_textblock_section av-jssstan3-903ca3be2179c219893a588554cc5b06 '   itemscope="itemscope" itemtype="https://schema.org/BlogPosting" itemprop="blogPost" ><div class='avia_textblock'  itemprop="text" ><p>Object-oriented programming languages like PHP, Java or C++ have natively classes built-in to their language. Don&#8217;t get fooled by the new ES6 class syntax. Javascript doesn&#8217;t have this feature but rather makes use of its powerful prototypal inheritance concept to &#8220;simulate&#8221; them or in nicer words &#8220;sugarcoat&#8221; it. In Javascript you can program both object-oriented and functional because prototyal inheritance is extremly powerful.</p>
<p>This article will start with a quick recap on prototypal inheritance in Javascript, feel free to jump directly to the <a href="#class-anchor">new class concept</a>.</p>
<h2>Prototypal inheritance</h2>
<p>Prototypal inheritance and object orientation are complex topics and could easily each on their own fill multiple long articles. This is just a quick recap of the concepts behind.</p>
<p>Lets start with a person object john that has a greeting method that ouputs its name. Remember: if we have a method on an object the <em>this</em> keyword will always point to the object itself.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/aa2d0cefe10690d9654ea18843205ded">Gist</a>.</p>
<p>Lets say now we need to make another person object Jane. How shall we do it? Just copy the previous one and give it different values? What if we need 10 or 100 different person objects? Copy and paste them all with different values?</p>
<p>Allthough it would technically work it really shouldn&#8217;t be how a developer approach this task. There is a fundamental concept that is universal to programming which is called <strong>Dont Repeat Yourself (DRY)</strong>. So lets stick to it and make our code dynamic by creating a function that serves us as a blue-print for unlimited person object instances.</p>
<h3>Object Constructor Function</h3>
<p>First we need to create an object constructor function with the properties we want our person objects to have. Object constructor functions are normal functions which are invoked with the <em>new</em> keyword preceeding it. We define its properties with <em>this.propertyname = propertyname</em>.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/9d5f13b976470150cd2034a86c173baf">Gist</a>.</p>
<p>In Javascript every function is an object but not every object is a function. Higher-order functions are functions that accept other functions as arguments which is only possible if functions are treated like objects. In order to make an instance of an object we call the object constructor function we want to inherit from with the <em>new</em> keyword beforehand. This way the Javascript engine knows that we intend to create a new instance of that object.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/7636128cf99dd4c20bf87d7353dc3e28">Gist</a>.</p>
<h3>Adding methods to all instances</h3>
<p>Now its time to add our greet method to the object constructor function. We want to add it to the object constructor function (our blue-print object) that all instances have access to. We can do this in two ways:</p>
<p>Adding the method from the very beginning directly to our object constructor function (same as we add properties)&#8230;</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/d139b9871b392a8b32f59690c8c38bcb">Gist</a>.</p>
<p>&#8230; or add it to the prototype of the object constructor function. Each function has a prototype property object with a constructor method that points to the function itself. Whenever we create a new instance (keyword new) we automatically invoke this constructor method which lives on the prototype of the object constructor function.</p>
<p>Every plain object has a __proto__ object and the __proto__ object of objects created as instances of another object (like in our example) point to the prototype of the object it is created from (remember: All functions are objects but not all objects are functions).</p>
<p>What is important here: Instances of objects (like john) have a reference to the objects they inherit from (like es5_Person). John&#8217;s __proto__ points to the prototype of es5_Person. One could also say that john&#8217;s __proto__ gets replaced with the prototype of its parent and therefor inherits all its methods. Both objects point to the same spot in memory. Their destinies are linked from now on. If you change the parents prototype you will also change the __proto__ of all their instances.</p>
<p>This also means if we add a method to the prototype of the object constructor function (es5_person) all their instances (john) will have access to it. Even if they are already created.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/08b59458eeed32bc9a8391eb71d4cbde">Gist</a>.</p>
<p>This works because when we call the method greet on john the Javascript engine looks if it can finds it on the john object first. If it is not present there (like in our example) it goes down the &#8220;prototype chain&#8221;. Since johns __proto__ points to the es5_Person prototype the Javascript Engine will find the method there and can run it.</p>
<h2 id="class-anchor">Classes</h2>
<p>Now that we understood how prototypal inheritance work lets look at ES6 classes but remember: under the hood it is still prototypal inheritance. It starts with the <em>class</em> keyword and the name of our class. It is written without parenthesis, has a constructor function and any method will be written just with its methodname, followed by parenthesis without comma seperation inbetween them.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/7a95fc91a76971af13d586a5ec4b1670">Gist</a>.</p>
<h2>Subclasses</h2>
<p>A subclass extends the functionality of its parent class. All instances of a subclass own the full functionality of the base class but additionally have methods which only instances of this subclass have access to. Let&#8217;s define a soldier subclass. Every soldier is a also a person but not every person is a soldier. Let&#8217;s look at it first how it was done in ES5 and how it is done now in ES6. Jump directly to <a href="#anchor-subclasses">ES6 Subclasses</a> if you don&#8217;t need this recap.</p>
<h3>ES5</h3>
<p>In ES5 we would create a new object constructor function with all the properties we want to inherit from the base class (firstname, lastname) and additonally all the properties that only exist in the subclass (weapon). Then we would call the base class within the context of the soldier subclass via <em>call</em> or <em>apply </em>and pass the current this context as well as all the properties of the base class (firstname, lastname). Afterwards we set the property only relevant for the subclass (weapon) normally how we are used to it in the object constructor function.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/7ee283b8b74f8b435494d73077426c81">Gist</a>.</p>
<p>Now we have a subclass who&#8217;s instances have the properties firstname, lastname and weapon but we dont inherit the methods from es5_Person. We don&#8217;t have access to its prototype. One solution is to use Object.create() to create a new object on the es5_Soldier.prototype and pass it the es5_Person.prototype. The Object.create() method creates a new object, using an existing object as the prototype of the newly created object. This means on the es5_Soldier.prototype a new object is created which has the es5_person.prototype as its __proto__. This way all instances of es5_Soldier are able to access the methods of es5_Person through the prototype chain.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/6c16bb7a1186882bfb0e2a67e9c96049">Gist</a>.</p>
<p>Any method which we add now to the prototype of our subclass will live there while the methods of its base class can be accessed through the __proto__ of the prototype of the subclass. Since the Javascript Engine goes down the prototype-chain automatically when it doesn&#8217;t find it we can call our methods as we are used to on the object. Let&#8217;s add a method for all our soldier instances.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/b3048557464e31fcabbd32908af6e4a4">Gist</a>.</p>
<p>Lets now create a new es5_Soldier instance &#8220;jackTheSoldier&#8221; and try if we can access both the shoot() method of its parent class and the greet() method of the base class es5_Person.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/ed25ff623e3d4c7bf0e31805812ffd6e">Gist</a>.</p>
<p>There is also another way to access the greet method from es5_Person but with Object.create(). We can define <em>greet()</em> as a new method on the es5_Soldier.prototype and call from within the function the es5_Person.prototype.greet() method and apply the current <em>this</em> context.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/02017e7e0bc15abe4d07cada1b67a626">Gist</a>.</p>
<p>Both is possible but I personally prefer the Object.create() method as it feels more straightforward to me.</p>
<p>Last but not least we can also prove that john can <em>greet()</em> but not <em>shoot()</em> because it has as an instance of es5_Person only access to <em>greet()</em>. Only instances of es5_Soldier can both <em>greet()</em> and <em>shoot()</em>.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/f351a9491d375a16b62501a37d2096f1">Gist</a>.</p>
<h3 id="anchor-subclasses">ES6</h3>
<p>In the ES6 class syntax the subclass concept is hugely simplified which is why a lot of developer like it. But remember it is all still prototypal inheritance under the hood. If we want to make es6_Soldier a subclass of es6_person we just use the keyword <em>extends</em>.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/4c40959317c49f5681ebebb87b825546">Gist</a>.</p>
<p>Since our es6_Soldier subclass adds a new property (weapon) we have to manually call the constructor function, pass it the base class properties firstname + lastname and then add weapon as a new parameter. The <em>super()</em> method is built-in and is used to call the parents constructor in our current context. If we wouldn&#8217;t add any new parameters we could leave it out because&#8230;</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/11fadf62f9dd0767aa22f0b16c439d53">Gist</a>.</p>
<p>&#8230;would be called otherwise automatically in the class.</p>
<p>If we want to override a parent method we can simply define it with the same name in our subclass and because within the prototype chain it will be before the parent method it will get run. If we however want to build on top of it, we also define it first in our subclass but also call the parent&#8217;s method from within via super.methodName(). Overwriting the greet() method from the es6_Person class within the es6_Soldier subclass would look like this:</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/93fb82685126f095c35baf624aa51cb6">Gist</a>.</p>
<p>This is it about classes. If you have any feedback or questions please let me know in the comments.</p>
</div></section><br />

<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756">
#top .hr.hr-invisible.av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756{
height:50px;
}
</style>
<div  class='hr av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756 hr-invisible  avia-builder-el-3  el_after_av_textblock  el_before_av_comments_list '><span class='hr-inner '><span class="hr-inner-style"></span></span></div><br />
<div  class='av-buildercomment av-72pis-30bb8351bf6d90489b0835edcf022e4d'></div></p></div>
<p>The post <a href="https://www.ilearnjavascript.com/es6-classes/">ES6: Classes</a> appeared first on <a href="https://www.ilearnjavascript.com">I Learn Javascript</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>ES6: Enhanced Object Literals</title>
		<link>https://www.ilearnjavascript.com/es6-enhanced-object-literals/</link>
		
		<dc:creator><![CDATA[ILJS]]></dc:creator>
		<pubDate>Sun, 03 Mar 2019 00:49:05 +0000</pubDate>
				<category><![CDATA[ES6+]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[es6+]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://www.ilearnjavascript.com/?p=690</guid>

					<description><![CDATA[<p>ES6 brings us a better version of object literals. We will write less code to reach the same result.</p>
<p>The post <a href="https://www.ilearnjavascript.com/es6-enhanced-object-literals/">ES6: Enhanced Object Literals</a> appeared first on <a href="https://www.ilearnjavascript.com">I Learn Javascript</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975">
.flex_column.av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975{
border-radius:0px 0px 0px 0px;
padding:0px 0px 0px 0px;
}
</style>
<div  class='flex_column av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975 av_one_full  avia-builder-el-0  avia-builder-el-no-sibling  blogpost first flex_column_div av-zero-column-padding  '     ><p>
<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-av_heading-5161523c1b8041f37473c6bfd0a68dbd">
#top .av-special-heading.av-av_heading-5161523c1b8041f37473c6bfd0a68dbd{
padding-bottom:10px;
}
body .av-special-heading.av-av_heading-5161523c1b8041f37473c6bfd0a68dbd .av-special-heading-tag .heading-char{
font-size:25px;
}
.av-special-heading.av-av_heading-5161523c1b8041f37473c6bfd0a68dbd .av-subheading{
font-size:14px;
}
</style>
<div  class='av-special-heading av-av_heading-5161523c1b8041f37473c6bfd0a68dbd av-special-heading-h1 blockquote modern-quote  avia-builder-el-1  el_before_av_textblock  avia-builder-el-first '><h1 class='av-special-heading-tag '  itemprop="headline"  >ES6: Enhanced Object Literals</h1><div class='av-subheading av-subheading_below'><p>4min read</p>
</div><div class="special-heading-border"><div class="special-heading-inner-border"></div></div></div><br />
<section  class='av_textblock_section av-jss73s39-39503979b53a0a9bcd82e498634a02ee '   itemscope="itemscope" itemtype="https://schema.org/BlogPosting" itemprop="blogPost" ><div class='avia_textblock'  itemprop="text" ><p>ES6 brings us a better version of object literals. We will write less code to reach the same result.</p>
<h2>No repetition: key-value</h2>
<p>Sometimes we want to create objects on the fly with dynamic values. We can use functions to achieve this by passing them arguments and return objects from them. The object-factory-function needs to initialize the objects with properties. It is quite common to use the same placeholder-name for the key : value pair in such a case. The enhanced object literals in ES6 allow us to just write the placeholdername as the initialized property on the object if key and value pair are the same.</p>
<h3>ES5</h3>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/0b92c758c1e1f989249df17037ecfe88">Gist</a>.</p>
<h3>ES6</h3>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/205d5562bd9134757b3cff45c3606524">Gist</a>.</p>
<h2>No repetition: methods</h2>
<p>Not only key-value pairs can be written short but also methods receive a more concise syntax update. Instead of writing&#8230;</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/6081bfbb43c64382bdccee432d9a84e3">Gist</a>.</p>
<p>&#8230;we can shorten it to:</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/b418edfc0777cd2ff88b6e12b2503c90">Gist</a>.</p>
<h3>ES5</h3>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/2b3d18d626a761a8e9f5046de7858c96">Gist</a>.</p>
<h3>ES6</h3>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/bc456504616606e9eef013069936fbf8">Gist</a>.</p>
<h2>Use variables as keys</h2>
<div>
<div>In ES5 it was not possible to use a variable for a key except it was added afterwards like in the following example:</div>
<h3>ES5</h3>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/1e76dfba127e425c0ef98caa890c8372">Gist</a>.</p>
<h3>ES6</h3>
<p>We can use the short-syntax for writing key-value pairs except for the dynamic added<em> [key1] which </em>has to be written in the classical way.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/df7acdbdddb816ce8d7e42f662d72184">Gist</a>.</p>
<p>Dynamic keys <em>[key1]</em> can be combined with incrementable variables in order to make the keys even more dynamic.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/bd25c67a19d2cb9ddd90c61cf998954e">Gist</a>.</p>
</div>
</div></section><br />

<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756">
#top .hr.hr-invisible.av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756{
height:50px;
}
</style>
<div  class='hr av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756 hr-invisible  avia-builder-el-3  el_after_av_textblock  el_before_av_comments_list '><span class='hr-inner '><span class="hr-inner-style"></span></span></div><br />
<div  class='av-buildercomment av-8393m-fffacd921dc9ef027db8eab1c632e5c4'></div></p></div>
<p>The post <a href="https://www.ilearnjavascript.com/es6-enhanced-object-literals/">ES6: Enhanced Object Literals</a> appeared first on <a href="https://www.ilearnjavascript.com">I Learn Javascript</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>ES6: Descructuring</title>
		<link>https://www.ilearnjavascript.com/es6-descructuring/</link>
		
		<dc:creator><![CDATA[ILJS]]></dc:creator>
		<pubDate>Sat, 02 Mar 2019 18:28:54 +0000</pubDate>
				<category><![CDATA[ES6+]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[es6+]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://www.ilearnjavascript.com/?p=623</guid>

					<description><![CDATA[<p>With ES6 we get a convenient way of extracting multiple values from data stored in (possibly nested) objects and Arrays.</p>
<p>The post <a href="https://www.ilearnjavascript.com/es6-descructuring/">ES6: Descructuring</a> appeared first on <a href="https://www.ilearnjavascript.com">I Learn Javascript</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975">
.flex_column.av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975{
border-radius:0px 0px 0px 0px;
padding:0px 0px 0px 0px;
}
</style>
<div  class='flex_column av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975 av_one_full  avia-builder-el-0  avia-builder-el-no-sibling  blogpost first flex_column_div av-zero-column-padding  '     ><p>
<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-av_heading-1781cb5eecc0c5c73ac7e3a9b32b8dba">
#top .av-special-heading.av-av_heading-1781cb5eecc0c5c73ac7e3a9b32b8dba{
padding-bottom:10px;
}
body .av-special-heading.av-av_heading-1781cb5eecc0c5c73ac7e3a9b32b8dba .av-special-heading-tag .heading-char{
font-size:25px;
}
.av-special-heading.av-av_heading-1781cb5eecc0c5c73ac7e3a9b32b8dba .av-subheading{
font-size:14px;
}
</style>
<div  class='av-special-heading av-av_heading-1781cb5eecc0c5c73ac7e3a9b32b8dba av-special-heading-h1 blockquote modern-quote  avia-builder-el-1  el_before_av_textblock  avia-builder-el-first '><h1 class='av-special-heading-tag '  itemprop="headline"  >ES6: Descructuring</h1><div class='av-subheading av-subheading_below'><p>8min read</p>
</div><div class="special-heading-border"><div class="special-heading-inner-border"></div></div></div><br />
<section  class='av_textblock_section av-jsrtlage-dab38bbad308c49e81ee307ceaa1cf0a '   itemscope="itemscope" itemtype="https://schema.org/BlogPosting" itemprop="blogPost" ><div class='avia_textblock'  itemprop="text" ><p>With ES6 we get a convenient way of extracting multiple values from data stored in (possibly nested) objects and Arrays.</p>
<h3>ES5</h3>
<p>If we wanted to extract single values from an array in ES5 we would manually go through it by its index.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/c17076fa6e01479078a2c04df23c3d2a">Gist</a>.</p>
<h3>ES6</h3>
<p>In ES6 we can simply sum up all variables in an array, give them appropriate names and reference it to the array we want to destruct.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/3a22a810db199a4a59b0205fe6f347d1">Gist</a>.</p>
<h2>Skip values</h2>
<p>If we want to skip some values we just leave them out, but comma separate it that the length of both arrays will still match.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/a0449f6d87601e8509487fe3edff1ea1">Gist</a>.</p>
<h2>Rest Paramter + Destructuring</h2>
<p>Another ES6 feature which comes really handy in combination with destructuring is the <a href="https://www.ilearnjavascript.com/es6-rest-parameter/">Rest Parameter</a>. It is a sibling of the <a href="https://www.ilearnjavascript.com/es6-spread-operator/">Spread Operator</a> (they share the same syntax) and allows us to collect all the remaining elements into an array.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/402da9b8e3996a7600dcdcad70ad2f69">Gist</a>.</p>
<h2>Destructure from Functions</h2>
<p>We can destructure not only directly from an array but also from a function.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/c1e2b7157cdeab17f1089eca77b9d997">Gist</a>.</p>
<h2>Default Parameters + Destructuring</h2>
<p>By using <a href="https://www.ilearnjavascript.com/default-parameters/">Default Paramters</a> we can assign default values in case our array has some <em>undefined</em> values. This could be for example the case when we retrieve the array via an API and cannot assure data reliability but need values to work with.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/9960450dfd46681b69a1ab658641c7d7">Gist</a>.</p>
<h2>Swap values</h2>
<p>A feature of destructuring that is not always easy to find real world applications for is swapping values. So in our case of the person object we can switch the values for the variables of firstname and lastname in one line.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/26a3fdcdf986ef48b90bcbf728ba6014">Gist</a>.</p>
<p>Obviously this example doesn&#8217;t make a lot of sense because why would we switch firstname and lastname. I couldn&#8217;t come up with my own example that makes sense but I found a very good example on github: https://github.com/wesbos/es6-articles/blob/master/20%20-%20Swapping%20Variables%20with%20Destructuring.md</p>
<p>The example in a nutshell: We have a wrestling application in which the tag team partner always switch when they go into the ring. Without destructuring that problem would have been fixed with a temporare variable. Now we can use an easy one-liner.</p>
<h2>Destructuring objects</h2>
<p>Last but not least: Destructuring works also with objects.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/371306e8e8ca1050578f0717e22f4c2d">Gist</a>.</p>
</div></section><br />

<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756">
#top .hr.hr-invisible.av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756{
height:50px;
}
</style>
<div  class='hr av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756 hr-invisible  avia-builder-el-3  el_after_av_textblock  el_before_av_comments_list '><span class='hr-inner '><span class="hr-inner-style"></span></span></div><br />
<div  class='av-buildercomment av-82e6n-786618bb4597a67cf91ef83c54314d54'></div></p></div>
<p>The post <a href="https://www.ilearnjavascript.com/es6-descructuring/">ES6: Descructuring</a> appeared first on <a href="https://www.ilearnjavascript.com">I Learn Javascript</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>ES6: Promises</title>
		<link>https://www.ilearnjavascript.com/es6-promises/</link>
		
		<dc:creator><![CDATA[ILJS]]></dc:creator>
		<pubDate>Wed, 27 Feb 2019 17:21:03 +0000</pubDate>
				<category><![CDATA[ES6+]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[es6+]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://www.ilearnjavascript.com/?p=424</guid>

					<description><![CDATA[<p>Javascript Promises arrived natively with ES6 and are essentially a simpler way of dealing with asynchronous (async) operations in comparison to traditional callback-based approaches (ES5).</p>
<p>The post <a href="https://www.ilearnjavascript.com/es6-promises/">ES6: Promises</a> appeared first on <a href="https://www.ilearnjavascript.com">I Learn Javascript</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975">
.flex_column.av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975{
border-radius:0px 0px 0px 0px;
padding:0px 0px 0px 0px;
}
</style>
<div  class='flex_column av-jsm56n9k-b89ad28a2e87aea11f86249f3e974975 av_one_full  avia-builder-el-0  avia-builder-el-no-sibling  blogpost first flex_column_div av-zero-column-padding  '     ><p>
<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-av_heading-b2727471536c9c28fce48532cb90f334">
#top .av-special-heading.av-av_heading-b2727471536c9c28fce48532cb90f334{
padding-bottom:10px;
}
body .av-special-heading.av-av_heading-b2727471536c9c28fce48532cb90f334 .av-special-heading-tag .heading-char{
font-size:25px;
}
.av-special-heading.av-av_heading-b2727471536c9c28fce48532cb90f334 .av-subheading{
font-size:14px;
}
</style>
<div  class='av-special-heading av-av_heading-b2727471536c9c28fce48532cb90f334 av-special-heading-h1 blockquote modern-quote  avia-builder-el-1  el_before_av_textblock  avia-builder-el-first '><h1 class='av-special-heading-tag '  itemprop="headline"  >ES6: Promises</h1><div class='av-subheading av-subheading_below'><p>10min read</p>
</div><div class="special-heading-border"><div class="special-heading-inner-border"></div></div></div><br />
<section  class='av_textblock_section av-jsngzkqe-4712b41a3518dc1ee970bcde40566071 '   itemscope="itemscope" itemtype="https://schema.org/BlogPosting" itemprop="blogPost" ><div class='avia_textblock'  itemprop="text" ><p>ES6 Promises &#8211; I will promise you love them.</p>
<p>Javascript Promises arrived natively with ES6 and are essentially a simpler way of dealing with asynchronous (async) operations in comparison to traditional callback-based approaches (ES5). They also provide us with a solid error handling simliar to try/ catch and bring a few helpful methods to manage multiple Promises simultaneously.</p>
<p>Typical async operations which Promises can be used for include API calls, DB queries aswell as reading and downloading files.</p>
<p>An ES6 Promise much like a promise in real life can have three possible states:</p>
<ul>
<li><strong>Pending</strong> &#8211; the promise’s outcome hasn’t yet been determined, because the asynchronous operation that will produce its result hasn’t completed yet.</li>
<li><strong>Fulfilled</strong> &#8211; the asynchronous operation has completed, and the promise has a value.</li>
<li><strong>Rejected</strong> &#8211; the asynchronous operation failed, and the promise will never be fulfilled. In the rejected state, a promise has a reason that indicates why the operation failed.</li>
</ul>
<p>Promises are created via the <em>new</em> keyword and take in a function with two arguments <em>resolve</em> and <em>reject</em>. <em>Resolve</em> and <em>reject</em> are essentially methods which return whatever <em>value</em> we pass it. The Promise itself can be chained with a <em>then() and a catch() </em>method which each take a function with one argument. If the Promise gets fullfilled the <em>then()</em> method gets called and the <em>value</em> of <em>resolve()</em> gets passed to the <em>then()</em> method and can be used for any kind of operation. If the Promise gets rejected the <em>catch()</em> method runs with the <em>value</em> (reason) from <em>rejected()</em>.</p>
<p>Lets see that in action. The setTimeout function represents in this simplified example an async operation like an API call, which returns successfull after 2 seconds (fullfilled) and calls the <em>resolve()</em> method with the <em>value &#8216;Win&#8217;.</em> <em>&#8216;Win&#8217;</em> gets passed to the <em>then()</em> method and <em>console.log()</em> outputs it<em> </em>to the console.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/e58ce709abfb5063efa19c80214aac69">Gist</a>.</p>
<h2>Chaining Promises</h2>
<p>Promises can be chained to one another via the <em>then()</em> method and subsequently pass the previously processed value to the next Promise in chain. This works only because both the<em> then()</em> and the <em>catch()</em> method return itself a new Promise.</p>
<p>Lets create a celebrate function which gets called after the sprinter Promise successfully resolved. It takes one argument (the <em>value state</em> which is returned from the sprinter Promise) and returns a resolved Promise with the value of the variable <em>msg</em>. Now we chain to the resolved Promise from the celebrate function an anonymus function that simply logs <em>msg</em>.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/725565a144512930b2d65721c6aa786a">Gist</a>.</p>
<h2>Handling Multiple Promises</h2>
<p>Promises have additionally to<em> resolve()</em> and <em>reject()</em> two more built-in methods <em>all()</em> and<em> race()</em>.</p>
<h3>Promise.all()</h3>
<p>The Promise.all() method takes in an array of multiple promisses and only resolves when all promises are fullfilled. Lets create three different sprinters, which take each a different time to resolve (3 seconds, 2seconds, 1 seconds). The <em>Promise.all()</em> method fires only after 3s when alle Promises are fullfilled.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/a4119ad5885bfcd23236c6658d4b0049">Gist</a>.</p>
<h3>Promise.race()</h3>
<p>The <em>Promise.race()</em> method also takes in an array of multiple promisses and will resolve as soon as the first promise fullfills. The <em>Promise.race()</em> method called on the same three sprinters from the previous example this time will resolve already after 1 seconds (the fastest), because this is when the first sprinter (sprinter3) finishes.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/524dcc36ad870e02b2d2f560c4b4015b">Gist</a>.</p>
<h2>Promises are async</h2>
<p>Promises are not only used for async operations but they are async themselves. Meaning: Any synchronous code which is run before or after the Promise will run first before the Promise resolves or rejects. Lets prove it by creating a very simple Promise that resolves without any delay and console.log(&#8216;middle&#8217;). Before the Promise we console.log(&#8216;start&#8217;) and after the Promise we will console.log(&#8216;end&#8217;).</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/5110c71c4e929c197c2a13a591154c0a">Gist</a>.</p>
<p>Both the &#8216;start&#8217; and &#8216;end&#8217; console.log() statements get evaluated first because they run synchronous opposed to the async Promise.</p>
<h2>Fetch and Promises</h2>
<p>Most developers probably already used Promises without being aware of it. The Fetch API, a simple way to make network requests (similar to XMLHttpRequest or jQuery&#8217;s Ajax), infact returns a Promise.</p>
<p>In the following example we make an API call to a random joke API via fetch which resolves when the server responds with a status somewhere within the 2xx range and provides us with the joke in JSON format. If the Promise gets resolved the <em>then()</em> method gets called and the json is being parsed to an object. Since the json() method returns a Promise itself we can chain it with another <em>then()</em> and log the joke to the console.</p>
<p>View the code on <a href="https://gist.github.com/ilearnjavascript/6b8f8d2dff2c29b38845e62ce9054266">Gist</a>.</p>
<h2></h2>
</div></section><br />

<style type="text/css" data-created_by="avia_inline_auto" id="style-css-av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756">
#top .hr.hr-invisible.av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756{
height:50px;
}
</style>
<div  class='hr av-jsm56dz6-c6cf5812234ac3bae2a3b34780952756 hr-invisible  avia-builder-el-3  el_after_av_textblock  el_before_av_comments_list '><span class='hr-inner '><span class="hr-inner-style"></span></span></div><br />
<div  class='av-buildercomment av-7dm20-079f3e7babc347d18bc7a7d7ce0b6310'></div></p></div>
<p>The post <a href="https://www.ilearnjavascript.com/es6-promises/">ES6: Promises</a> appeared first on <a href="https://www.ilearnjavascript.com">I Learn Javascript</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
