<?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>javascript | Bogdan's blog</title>
	<atom:link href="https://blog.bogdancarpean.com/tag/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.bogdancarpean.com</link>
	<description>Code and anything else.</description>
	<lastBuildDate>Fri, 23 Dec 2022 00:48:59 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.1.1</generator>

<image>
	<url>https://blog.bogdancarpean.com/wp-content/uploads/2022/12/icons8-pencil-drawing-96.png</url>
	<title>javascript | Bogdan's blog</title>
	<link>https://blog.bogdancarpean.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Vue 3 is out &#8211; what should I do next?</title>
		<link>https://blog.bogdancarpean.com/vue-3-is-out-what-should-i-do-next/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=vue-3-is-out-what-should-i-do-next</link>
					<comments>https://blog.bogdancarpean.com/vue-3-is-out-what-should-i-do-next/#respond</comments>
		
		<dc:creator><![CDATA[Bogdan]]></dc:creator>
		<pubDate>Thu, 24 Sep 2020 03:00:34 +0000</pubDate>
				<category><![CDATA[vuejs]]></category>
		<category><![CDATA[front-end]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[Typescript]]></category>
		<category><![CDATA[vue 3]]></category>
		<category><![CDATA[vue next]]></category>
		<guid isPermaLink="false">https://blog.bogdancarpean.com/?p=389</guid>

					<description><![CDATA[<p>Long-awaited version 3 of the popular Vue framework is finally released (after 6 months in beta and release candidate), packed with interesting new things for Vue developers. Named &#8220;One Piece&#8221; and hosted in a separate repo, vue-next, for a period of time (to avoid being confused with 2.x and also not to be picked by [&#8230;]</p>
The post <a href="https://blog.bogdancarpean.com/vue-3-is-out-what-should-i-do-next/">Vue 3 is out – what should I do next?</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></description>
										<content:encoded><![CDATA[<p>Long-awaited version 3 of the popular Vue framework is finally released (after 6 months in beta and release candidate), packed with interesting new things for Vue developers.</p>
<p>Named &#8220;One Piece&#8221; and hosted in a separate repo, <a href="https://github.com/vuejs/vue-next" target="_blank" rel="nofollow noopener noreferrer">vue-next</a>, for a period of time (to avoid being confused with 2.x and also not to be picked by <em>npm install </em>as @latest), the new version promises increased performance, smaller bundle size, and interesting new features to at least intriguing us for discovering more.</p>
<p>Let&#8217;s take a first look at what&#8217;s new to decide if we go all-in with the new version or wait for the moment.</p>
<p>Vue 3 introduces the <strong>Composition API</strong>, which addresses the biggest problem (*personal opinion) of Vue, the use of mixins. Mixins are a good way of abstracting code to make it more reusable, but they have some flaws: they hide the code &#8211; at some point, a method defined in the mixin is called into the component, but that method is nowhere to be found inside the component. So you start digging up, losing time tracing the method to debug. In the extreme case of mixins nested in other mixins, this job increases in complexity. Other downsides are possible namespace clash (when you define a method in your component with the same name as one in the mixin) and have side effects hard to trace and the possibility of adding too much code in the mixin that is only partly used in a component at the time, this way incorporating to much bloat in components. The new Composition API in Vue 3 is giving us a new way of defining reusable code in Composables, which are more concise and clear as structure, then import these building blocks to construct our components.</p>
<p>Vue 3 promises to be <strong>faster </strong>and to have a <strong>smaller bundle size</strong>. On Vue 2, one way of gaining performance was to transform stateful components in functional ones when you have a lot of them in the DOM, to save lost time on register/unregister when re-rendering. On Vue 3, the functional prop was taken out from components (only render functions from now on), but the difference in performance between functional components and stateful ones became negligible, so we are advised to use only stateful components (for the part of us that does not like to use render functions).</p>
<p>Another point that will increase the performance of a Vue 3 application is compiler-informed Virtual DOM. This means that at compile-time, the resulting render functions that go into the bundle are flagged when they contain runtime dynamically changing elements. This way, at runtime, the Virtual DOM is aware of the elements to look for changes and not waste time on watching static ones.</p>
<p>In Vue 3, tree-shaking of Vue internals has been added at compile time. This is a step further in the &#8220;progressive framework&#8221; approach, allowing us to transport in the bundle only the Vue internals we are actually using. More than this, we have the possibility to manually flag the compiler for the parts it can&#8217;t detect automatically for tree-shake.</p>
<p>The new proxy-based reactivity system will speed even further the runtime of our application (check the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy" target="_blank" rel="nofollow noopener noreferrer">MDN docs on proxies</a> to find more on this interesting topic).</p>
<p>Some other interesting <strong>new</strong> <strong>features</strong> can be found in Vue 3.</p>
<p>The new <strong>&lt;teleport&gt;</strong> component allows us to render a part of the component template somewhere else in the DOM than the containing component place. Very useful for triggering a modal or a spinner from inside of a component to a more generic point in the DOM (e.g. &lt;body&gt;). Or, when you have a hamburger button on a mobile collapsed layout header to be able to trigger the navigation list outside that layout component.</p>
<p><strong>&lt;suspense&gt;</strong> is another component that acts as a wrapper for our component, allowing it to have an alternate template displayed until async operations are executed. Simply put, it allows us to show a loading template until the actual template is loaded and hydrated.</p>
<p>The new Vue 3 now supports <strong>multiple elements</strong> in the root of the <strong>&lt;template&gt;</strong>. This means no more wrapping all the elements in the template in one big &lt;div&gt; to avoid an error. Nice addition!!!</p>
<p><strong>&lt;v-model&gt;</strong> has a <strong>new API</strong> in the form of &lt;component v-model:key=&#8221;binding&#8221;&gt;. This allows us to pass multiple v-model binding for the same component. Multiple two-way bindings on one component. Nice!!!</p>
<p><strong>Filters</strong> have been <strong>removed</strong> from Vue 3 (these are the pipes for those coming, like myself, from the Angular world). From now on, to avoid confusion, only direct method binding {{ convertToCelsius (degrees) }}.</p>
<p>Some additions have been made to the Single File Components syntax. One is the new <strong>&lt;script setup&gt;</strong>, which is a shorthand to use instead of returning the setup function for the Composition API. The other interesting one is <strong>&lt;style vars&gt;</strong>, which allows us to pass CSS variables to the style sheet and this way to control dynamically the style at runtime.</p>
<p>For those of you wanting to tweak the framework or even to use parts of Vue to build their own framework, new <strong>modular internals</strong> of Vue 3 are here, replacing the monolith core of Vue from former versions.</p>
<p>Lastly, the wide use of <strong>TypeScript</strong> in Vue 3 allows you to have on the fly type inference in your component when you instantiate a variable. And if you already declare the type of your props, you&#8217;re already there.</p>
<p>The last thing to mention is that Vue 3 will stay on @next tag until somewhere the end of 2020 when a coordinated switch of all components to @latest will be made. Also, a minor release of Vue 2.7 is scheduled for Q1/2021, having all the 3.x backward compatible features included and the migration build for 3.x. At that point, 2.7 will enter LTS for 18 months.</p>
<p>Now that we have a clearer picture of what Vue 3 brings to the table, we ask ourselves <strong>what to do next</strong>? And as usual, there are few different answers to this question, depending on the current state of your application.</p>
<p>If you have a small application(s) that work fine and have no benefit from using the above-mentioned changes, just keep them on 2.x.</p>
<p>If you start a new application with Vue, start it directly on Vue 3, this way you have all the new benefits of the framework and your application is future proof for what&#8217;s to come for a longer period of time. The only drawback in this situation is that some of the submodules are not yet on stable releases, but I think most are stable enough (beta or RC) to be usable and soon stable.</p>
<p>If your application is a complex one and you were already thinking of some refactoring, could be the time to start architecting for the transition to Vue 3 and by the time you figure it out, hopefully, all the pieces will be in place for a fast migration and the benefits brought by Vue 3.</p>
<p>Else, if you have a complex application that is working fine now, you will want to wait a bit for the migration build to be in place and do a two-step migration to Vue 3 using this build as an intermediary step.</p>
<p>Either way, hope you will enjoy the new iteration of the framework and happy coding!</p>
<p>&nbsp;</p>The post <a href="https://blog.bogdancarpean.com/vue-3-is-out-what-should-i-do-next/">Vue 3 is out – what should I do next?</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></content:encoded>
					
					<wfw:commentRss>https://blog.bogdancarpean.com/vue-3-is-out-what-should-i-do-next/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Javascript for of index</title>
		<link>https://blog.bogdancarpean.com/javascript-for-of-index/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=javascript-for-of-index</link>
					<comments>https://blog.bogdancarpean.com/javascript-for-of-index/#respond</comments>
		
		<dc:creator><![CDATA[Bogdan]]></dc:creator>
		<pubDate>Mon, 01 Jun 2020 16:36:25 +0000</pubDate>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[for of]]></category>
		<category><![CDATA[index]]></category>
		<category><![CDATA[iterable]]></category>
		<category><![CDATA[js]]></category>
		<guid isPermaLink="false">https://blog.bogdancarpean.com/?p=376</guid>

					<description><![CDATA[<p>Starting with ECMA 6 we have a new loop iterating statement in the form of for&#8230;of. This helps us to loop thru an iterable object (array, string, map, set&#8230;) in a simpler fashion than the classic for loop. To achieve this, we are going to use the entries() method of the Array: for (const [index, [&#8230;]</p>
The post <a href="https://blog.bogdancarpean.com/javascript-for-of-index/">Javascript for of index</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></description>
										<content:encoded><![CDATA[<p>Starting with ECMA 6 we have a new loop iterating statement in the form of <strong>for&#8230;of</strong>. This helps us to loop thru an iterable object (array, string, map, set&#8230;) in a simpler fashion than the classic <strong>for</strong> loop.</p>
<p>To achieve this, we are going to use the <strong>entries()</strong> method of the Array:</p>
<pre>for (const [index, element] of myArray.entries()) {
  console.log(index, element)
}</pre>The post <a href="https://blog.bogdancarpean.com/javascript-for-of-index/">Javascript for of index</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></content:encoded>
					
					<wfw:commentRss>https://blog.bogdancarpean.com/javascript-for-of-index/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Fetch data needed on component&#8217;s template in Vue before render</title>
		<link>https://blog.bogdancarpean.com/fetch-data-needed-on-components-template-in-vue-before-render/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=fetch-data-needed-on-components-template-in-vue-before-render</link>
					<comments>https://blog.bogdancarpean.com/fetch-data-needed-on-components-template-in-vue-before-render/#respond</comments>
		
		<dc:creator><![CDATA[Bogdan]]></dc:creator>
		<pubDate>Thu, 01 Aug 2019 06:00:10 +0000</pubDate>
				<category><![CDATA[vuejs]]></category>
		<category><![CDATA[fetch data]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[router]]></category>
		<guid isPermaLink="false">http://blog.bogdancarpean.com/?p=311</guid>

					<description><![CDATA[<p>Let&#8217;s say in your Vue app you have a component that needs to fetch some data in order to display it on the template. This component needs this data on creation in order to be able to bind it on the template. Let&#8217;s take the following example: &#60;template&#62; &#60;div class="container"&#62; &#60;p&#62;Name: {{name}}&#60;/p&#62; &#60;p&#62;Age: {{age}}&#60;/p&#62; &#60;/div&#62; [&#8230;]</p>
The post <a href="https://blog.bogdancarpean.com/fetch-data-needed-on-components-template-in-vue-before-render/">Fetch data needed on component’s template in Vue before render</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></description>
										<content:encoded><![CDATA[<p>Let&#8217;s say in your Vue app you have a component that needs to fetch some data in order to display it on the template. This component needs this data on creation in order to be able to bind it on the template.</p>
<p>Let&#8217;s take the following example:</p>
<pre class="lang:default decode:true">&lt;template&gt;
  &lt;div class="container"&gt;
    &lt;p&gt;Name: {{name}}&lt;/p&gt;
    &lt;p&gt;Age: {{age}}&lt;/p&gt;
  &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
data():{
  return{
    name: null
    age: null
  }
}

created():{
  fetchUser().
    then(res =&gt; {
     this.name = res.data.name
     this.age = res.data.age 
    }
    )
}
&lt;/script&gt;</pre>
<p>In this example, we have a Vue Component that needs to fetch the user name and age before being able to create the template and display them. We use the lifecycle hook&nbsp;<em>created()&nbsp;</em>to fetch the data in the component. This will finally work, because of the reactive nature of Vue, but we are going to have an error in the console telling us that&nbsp;<em>name&nbsp;</em>is undefined. This happens because when we navigate to the component and this one gets rendered, the value of the variables is not yet fetched, the component rendering first the template, then executing the script. So we get the error on the console, then the script is run, data is fetched and displayed.</p>
<p>Let&#8217;s see how to do that without having the error on the console:</p>
<pre class="lang:default decode:true ">&lt;template&gt;
 &lt;div class="container" v-if="dataFetched"&gt;
   &lt;p&gt;Name: {{name}}&lt;/p&gt;
   &lt;p&gt;Age: {{age}}&lt;/p&gt;
 &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
data: {
  return {
    name: null
    age: null
    dataFetched: false
  }
},

beforeRouteEnter(to, from, next) {
  fetchUser().
    then(res =&gt; {
      next(vm =&gt; vm.setUser(res.data)
    })
},

methods: {
  setUser(user){
    this.name = user.name
    this.age = user.age
    this.dataFetched = true
  }
}
&lt;/script&gt;</pre>
<p>To achieve this, we first use the&nbsp;<em>beforeRouteEnter()&nbsp;</em>guard of the Vue Router that is called before the Router navigates to our component route. This guard has three parameters: to, from and next. From is an object containing the information about the route we are navigating from, also the parameters passed by route, to is the information about the route we are navigating to, next() is the function we call after we executed all we need on the guard to pursue the navigation.</p>
<p>But moving the fetch logic from the lifecycle hook to the guard alone won&#8217;t solve our problem because fetch is an asynchronous operation that will start on the guard, then next is called, leading to template rendering before data being fetched and virtually the same error on console.</p>
<p>To achieve this, we use a trick. We declare a boolean in the component, let&#8217;s say&nbsp;<em>dataFetched,&nbsp;</em>that we instantiate to false and we use it to trigger with&nbsp;<em>v-if&nbsp;</em>the render of the container div only when the data is fetched. We set the variable to true in the setUser method in the component after data is fetched, this way preventing the render of the template and the error on the console.</p>
<p>Happy coding!!!</p>The post <a href="https://blog.bogdancarpean.com/fetch-data-needed-on-components-template-in-vue-before-render/">Fetch data needed on component’s template in Vue before render</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></content:encoded>
					
					<wfw:commentRss>https://blog.bogdancarpean.com/fetch-data-needed-on-components-template-in-vue-before-render/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Deepcopy of JavaScript Objects and Arrays using lodash&#8217;s cloneDeep method</title>
		<link>https://blog.bogdancarpean.com/deepcopy-of-javascript-objects-and-arrays-using-lodashs-clonedeep-method/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=deepcopy-of-javascript-objects-and-arrays-using-lodashs-clonedeep-method</link>
					<comments>https://blog.bogdancarpean.com/deepcopy-of-javascript-objects-and-arrays-using-lodashs-clonedeep-method/#respond</comments>
		
		<dc:creator><![CDATA[Bogdan]]></dc:creator>
		<pubDate>Fri, 12 Jan 2018 14:08:06 +0000</pubDate>
				<category><![CDATA[Angular]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[angular]]></category>
		<category><![CDATA[cloneDeep]]></category>
		<category><![CDATA[copy objects]]></category>
		<category><![CDATA[deep clone]]></category>
		<category><![CDATA[deep copy]]></category>
		<category><![CDATA[lodash]]></category>
		<guid isPermaLink="false">http://blog.bogdancarpean.com/?p=182</guid>

					<description><![CDATA[<p>While developing JavaScript applications, often we need to make copies of Objects or Arrays containing Objects. Then we want to work with those copies without affecting the original objects. In a common scenario, we are going to deal with a simple, one level Object (an Object without other Objects nested inside), like in the following [&#8230;]</p>
The post <a href="https://blog.bogdancarpean.com/deepcopy-of-javascript-objects-and-arrays-using-lodashs-clonedeep-method/">Deepcopy of JavaScript Objects and Arrays using lodash’s cloneDeep method</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></description>
										<content:encoded><![CDATA[<div style="position: relative;">While developing JavaScript applications, often we need to make copies of Objects or Arrays containing Objects. Then we want to work with those copies without affecting the original objects.<br />
In a common scenario, we are going to deal with a simple, one level Object (an Object without other Objects nested inside), like in the following example:</div>
<pre class="EnlighterJSRAW" data-enlighter-language="js">let originalObject = {name: 'Bunt', type: 'dog'};</pre>
<p>Then, we want to make a copy of the <code>originalObject</code>. In <code>ES6</code>, we are going to do something like this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">let copiedObject = Object.assign({}, originalObject);</pre>
<p>This will create the <code>copiedObject</code> with all the properties and respective values of the <code>originalObject</code>. Now, if we want to change a value in the <code>copiedObject</code>, this will not change also the value into the <code>originalObject:</code></p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">copiedObject.type = 'cat';

console.log(originalObject.type); // will print 'dog'
console.log(copiedObject.type); // will print 'cat'</pre>
<p>Now, what is going to happen if we have a nested Object inside our Object, doing the same operations?</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">let originalObject = {name: 'Bunt', details: {type: 'dog', color: 'brown'}};

let copiedObject = Object.assign({}, originalObject);

copiedObject.details.type = 'cat'; 

console.log(originalObject.details.type); // will print 'cat' 
console.log(copiedObject.details.type); // will print 'cat'</pre>
<p>As you can see, when you change the value of a property in the nested Object of <code>copiedObject</code>, that change is perpetuated to the same property of the nested Object in <code>originalObject</code>. You&#8217;ll ask why that happened? Because JavaScript passes the primitive values (string, number, etc.) as <code>value-copy</code> and the compound values (Objects, Arrays, Functions) as <code>reference-copy</code> to the value of the primitives on that Object. This way, when we copied the Object containing the nested Object, we have created a <code>shallow copy</code> of that object, meaning that the primitives found at the first level of the Object have values that are copied, thus when we change them into the <code>copiedObject</code>, they are not going to change in the <code>originalObject</code> while all other property found in a nested object will have the value passed as a <code>reference</code> to the same property value into the nested Object of <code>originalObject</code>, thus when we change its value, we actually change the value of the reference, resulting on both nested Objects having the modified property value.</p>
<p>Now, what&#8217;s the solution to <code>deep copy</code> an Object or Array, meaning that we want to have a copy free of references at all nested levels so we can change the values inside without the fear of breaking the original?</p>
<p>The first solution you are going to find is to serialize the Object to a JSON, then parse back that JSON to a JavaScript Object, practically passing the Object thru a string that will clean up the Object tree from the references nested inside by recreating a new Object with copied properties and values from the original one.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">let copiedObject = JSON.parse(JSON.stringify(originalObject));</pre>
<p>But this is a controversial solution. Why? Because this is going to work fine as long as your Objects and the nested Objects only contains primitives, but if you have objects containing <code>functions</code>, this won&#8217;t work. Neither for <code>Date</code>.</p>
<p>So, what&#8217;s the working solution? We are going to use <a href="https://lodash.com/">lodash&#8217;s</a> <a href="https://lodash.com/docs/4.17.4#cloneDeep">cloneDeep</a> method to <code>deep copy</code> the Object. Lodash is an excellent JavaScript utility library for those not knowing it yet. The <code>cloneDeep</code> method will iterate all levels of the original Object and recursively copying all properties found.</p>
<p>The example I will give here is in Angular. Since we don&#8217;t want to carry all the bundle of <code>lodash</code> to the client, we are going only to import the cloneDeep method.</p>
<p>First, let&#8217;s install <code>lodash</code>into our project:</p>
<p><code>yarn add lodash</code> or <code>npm install lodash</code></p>
<p>Once installed, we are going to use in our component:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">import * as cloneDeep from 'lodash/cloneDeep';

...

clonedObject = cloneDeep(originalObject);</pre>
<p>Importing <code>cloneDeep</code> will add to your build 18kb, a fair price to pay in order to have a reliable <code>deep copy</code> solution for you Objects.</p>
<p>I added a demo app on Github <a href="https://github.com/bogdancar/demo-angular-object-deep-copy">here</a>.</p>
<p><em>Interested in Angular? Join our <a href="https://www.meetup.com/Angular-Montreal/">Angular Montreal Meetup</a>.</em></p>The post <a href="https://blog.bogdancarpean.com/deepcopy-of-javascript-objects-and-arrays-using-lodashs-clonedeep-method/">Deepcopy of JavaScript Objects and Arrays using lodash’s cloneDeep method</a> first appeared on <a href="https://blog.bogdancarpean.com">Bogdan's blog</a>.]]></content:encoded>
					
					<wfw:commentRss>https://blog.bogdancarpean.com/deepcopy-of-javascript-objects-and-arrays-using-lodashs-clonedeep-method/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
