<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ hacks - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ hacks - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 25 May 2026 22:38:32 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/hacks/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ 10 CSS Hacks Every Web Developer Should Know ]]>
                </title>
                <description>
                    <![CDATA[ By Gert Svaiko While CSS isn’t as widely used as JavaScript, it’s still in the top 10 coding languages, according to Redmonk. Since CSS is quite robust, reasonably easy to learn, and universal across different browsers, it’s popular among website dev... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/10-css-hacks-every-web-developer-should-know/</link>
                <guid isPermaLink="false">66d45edb246e57ac83a2c761</guid>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ hacks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Design ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 10 Feb 2021 18:34:13 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/02/css-hacks.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Gert Svaiko</p>
<p>While CSS isn’t as widely used as <a target="_blank" href="https://www.freecodecamp.org/news/javascript-hacks/">JavaScript</a>, it’s still in the <a target="_blank" href="https://redmonk.com/sogrady/2020/07/27/language-rankings-6-20/">top 10 coding languages</a>, according to Redmonk. Since CSS is quite robust, reasonably easy to learn, and universal across different browsers, it’s popular among website developers.</p>
<p>As it is with every coding language, there are several shortcuts or hacks with CSS that allow you to write cleaner code, improve design elements, and save valuable time. Furthermore, you can directly insert these snippets to your site using a <a target="_blank" href="https://www.freecodecamp.org/news/source-code-editors-explained/">code editor</a>. </p>
<p>It is also important to know that you don’t have to be a senior web developer to use CSS. Data from W3Techs show that CSS is used by <a target="_blank" href="https://w3techs.com/technologies/details/ce-css">96 percent of all websites</a>, and being able to use CSS to enhance the layout and appearance of a website is integral to the functioning of major open source CMSs like WordPress. </p>
<p>In fact, most of <a target="_blank" href="https://websitesetup.org/best-website-builder-tools/">the biggest website builder tools</a> (generally known for promoting a “What You See Is What You Get” or WYSIWYG approach) now allow users to insert custom CSS code.</p>
<p>If you’re new to CSS, freeCodeCamp has an excellent <a target="_blank" href="https://www.youtube.com/watch?v=kMT54MPz9oE">tutorial video on Youtube</a> where you can learn the basics. If you already know the fundamental aspects, then let’s get started with these ten CSS hacks.</p>
<h2 id="heading-1-how-to-position-content-in-the-center-with-css">1. How to position content in the center with CSS</h2>
<p>Placing content in the middle of the screen might be tricky. However, you can use <code>position: absolute</code> to override the dynamic placement and always position the content in the center. </p>
<p>It also works with every resolution across devices. However, always double-check if everything is positioned as you want it and the element looks natural even on smaller screens.</p>
<p>Example snippet:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">position</span>: absolute;
  <span class="hljs-attribute">left</span>: <span class="hljs-number">50%</span>;
  <span class="hljs-attribute">top</span>: <span class="hljs-number">50%</span>;
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">translate</span>(-<span class="hljs-number">50%</span>, -<span class="hljs-number">50%</span>);
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">30px</span>;
}
</code></pre>
<h2 id="heading-2-how-to-fix-an-elements-position-in-css">2. How to fix an element’s position in CSS</h2>
<p>Despite websites being dynamic, you might have some elements that you want to fix in certain positions. You can do so by using the <code>position:absolute</code> script.</p>
<p>However, use this method carefully and test it beforehand on every screen size and resolution so that it doesn’t break your site’s design.</p>
<p>Following this script with a specific position node assures that the element remains in the same position for all users.</p>
<p>Example snippet:</p>
<pre><code class="lang-css"><span class="hljs-comment">/* suppose you want to fix your sidebar’s position and size */</span>
<span class="hljs-selector-class">.sidebar</span> {
  <span class="hljs-attribute">position</span>: absolute;
  <span class="hljs-attribute">top</span>: <span class="hljs-number">15px</span>;
  <span class="hljs-attribute">right</span>: <span class="hljs-number">15px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">300px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">150px</span>;
}
</code></pre>
<h2 id="heading-3-how-to-fit-images-to-the-page-in-css">3. How to fit images to the page in CSS</h2>
<p>There are few things worse than your images spilling over your site visitor's screen. It can absolutely break your site’s design and discourage users.</p>
<p>However, with this simple hack, you can make sure that your images always fit the visitor’s screen regardless of the device they’re using.</p>
<p>Example snippet:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">max-width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">height</span>: auto;
}
</code></pre>
<h2 id="heading-4-how-to-edit-styles-on-a-single-page-in-css">4. How to edit styles on a single page in CSS</h2>
<p>If you have a CMS and want some of your posts to look different than others, you can use a custom class to override the site's CSS styles. This ensures that you only tweak a single post page and leave the others as the default.</p>
<p>When you create a post on a WordPress blog it includes the post's id as a class in the <code>body</code>, for example:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/image-97.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Then you could do something like this to change the styling for just that post's page:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.postid-330</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">24px</span>;
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">750</span>;
  <span class="hljs-attribute">color</span>: red;
}
</code></pre>
<p>Other popular CMSs allow you to add custom classes to individual posts. For example, Ghost lets you mark a post as a featured post and adds a <code>.featured</code> class.</p>
<p>However, if you find yourself using this method a lot, it's best to modify the main CSS style sheet to avoid writing unnecessary code.</p>
<p>And this doesn't just apply to CMSs – if you have a simple website with multiple HTML files, you could apply custom styling to elements throughout your project, and adjust them through the same CSS file.</p>
<p>For example, if you have page with the class <code>.landing</code>:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Landing Page<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width,initial-scale=1"</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"css/style.css"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"landing"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Landing Page<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>My landing page.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>And another with the class <code>.about</code>:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>About Page<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width,initial-scale=1"</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"css/style.css"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"landing"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>About Page<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>My about page.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>You could add this to your main style sheet to only adjust the styling on the about page:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.about</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">24px</span>;
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">750</span>;
  <span class="hljs-attribute">color</span>: red;
}
</code></pre>
<h2 id="heading-5-how-to-consolidate-styling-in-css">5. How to consolidate styling in CSS</h2>
<p>If you know that you want to add CSS styling to multiple items, then writing these pieces of code out one by one takes time. However, when you separate items with commas and write the CSS style inside, then the style is added to all of them. </p>
<p>This helps you save time and lower your code’s weight because you don’t have to write a similar line of code multiple times.</p>
<p>Example snippet:</p>
<pre><code class="lang-css"><span class="hljs-comment">/* suppose you want to add a solid border around your caption element, image, and paragraph element */</span>
<span class="hljs-selector-class">.caption</span>, <span class="hljs-selector-tag">img</span>, <span class="hljs-selector-tag">p</span> {
  <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> solid <span class="hljs-number">#000000</span>;
}

<span class="hljs-comment">/* you can also limit the selection using selectors */</span>
<span class="hljs-selector-tag">p</span><span class="hljs-selector-class">.white-text</span>, <span class="hljs-selector-tag">div</span> &gt; <span class="hljs-selector-tag">p</span><span class="hljs-selector-class">.unique</span> {
  <span class="hljs-attribute">color</span>: white;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">24px</span>;
}
</code></pre>
<h2 id="heading-6-visited-link-styling-in-css">6. Visited link styling in CSS</h2>
<p>The default style of visited links that users have clicked on might not work great with your current site’s style. You can use CSS code to tweak how the links look before and after visitors have clicked on them.</p>
<p>You can then match these with your site’s overall style to create a unique experience.</p>
<p>Example snippet:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">a</span><span class="hljs-selector-pseudo">:link</span> {
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#ff0000</span>; <span class="hljs-comment">/* the unvisited link is red */</span>
}
<span class="hljs-selector-tag">a</span><span class="hljs-selector-pseudo">:visited</span> {
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#ee82ee</span>; <span class="hljs-comment">/* the visited link turns violet */</span>
}
</code></pre>
<h2 id="heading-7-hovering-effect-delays-in-css">7. Hovering effect delays in CSS</h2>
<p>The <code>:hover</code> selector is a CSS pseudo-class which allows you to create a hovering effect. However, you can further stylise this by adding a <code>transition</code> element to delay the hovering effect.</p>
<p>While it looks neat, it also creates a sense of movement in the users’ eyes, further drawing attention to the element.</p>
<p>Example snippet:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.entry</span> <span class="hljs-selector-tag">h2</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">48px</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#000000</span>;
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">750</span>;
}

<span class="hljs-comment">/* Next, add a delay to the hover effect */</span>
<span class="hljs-selector-class">.entry</span> <span class="hljs-selector-tag">h2</span><span class="hljs-selector-pseudo">:hover</span>{
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#f00</span>;
  <span class="hljs-attribute">transition</span>: all <span class="hljs-number">0.5s</span> ease;
}
</code></pre>
<h2 id="heading-8-how-to-disable-text-wrapping-and-add-ellipsis-in-css">8. How to disable text wrapping and add ellipsis in CSS</h2>
<p>If you’re tight on space for your text, you might need to cut it short to fit other elements. Sure, you can manually tweak each of the text elements, but that takes time and some trial and error. </p>
<p>What you can do instead is combine <code>overflow</code>, <code>white-space</code>, and <code>text-overflow</code> to create a natural break in the text that’s easy on the eyes. </p>
<p>The following example sets the limit on the text width, hides the overflowing part, disables the text wrapping, and adds an ellipsis (...) to indicate there’s more text for the users.</p>
<p>Example snippet:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.product-description</span> {
<span class="hljs-attribute">max-width</span>: <span class="hljs-number">150px</span>;
  <span class="hljs-attribute">overflow</span>: hidden;
  <span class="hljs-attribute">white-space</span>: nowrap;
  <span class="hljs-attribute">text-overflow</span>: ellipsis;
}
</code></pre>
<h2 id="heading-9-initial-letter-stylizing-in-css">9. Initial letter stylizing in CSS</h2>
<p>The <a target="_blank" href="http://www.magazinedesigning.com/drop-caps-and-initial-letters/">stylized initial letter or drop caps</a> have been used in book and magazine design for a long time. It works by grabbing the readers’ attention and getting them interested in reading the first line.</p>
<p>While you may think that this style has aged, you can also design it to look modern and still capitalize on the psychological effect it creates for your visitors. Furthermore, drop caps option is also written into the CSS language, so you can effortlessly use it and give your paragraphs a new look.</p>
<p>Example snippet:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">p</span><span class="hljs-selector-pseudo">:first-letter</span> {
  <span class="hljs-attribute">display</span>: block;
  <span class="hljs-attribute">float</span>: left;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">5px</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#000000</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">60px</span>;
}
</code></pre>
<h2 id="heading-10-how-to-reset-css-styles">10. How to reset CSS styles</h2>
<p>Last but not least, you might need to override all the default styling attributes across different browsers for your design to work flawlessly. </p>
<p>Each browser has its own style sheet, with built-in default styles, and this can sometimes be a problem when you’re trying to make your website look consistent on all browsers. </p>
<p>You can use a comprehensive CSS reset from <a target="_blank" href="https://meyerweb.com/eric/tools/css/reset/">Eric Meyer</a> which covers almost all bases. However, you can also achieve a minimal reset result, which you can borrow from <a target="_blank" href="https://perishablepress.com/a-killer-collection-of-global-css-reset-styles/">Jeff Starr</a>:</p>
<pre><code class="lang-css">* {
  <span class="hljs-attribute">vertical-align</span>: baseline;
  <span class="hljs-attribute">font-weight</span>: inherit;
  <span class="hljs-attribute">font-family</span>: inherit;
  <span class="hljs-attribute">font-style</span>: inherit;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">outline</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
}
</code></pre>
<p>And there you have it, ten hacks to make your CSS code look neater, decrease your coding time, and add visitor-friendly elements.</p>
<h3 id="heading-thanks-for-reading">Thanks for reading!</h3>
<p>I’m a writer passionate about digital marketing, web development, and cybersecurity. You can reach me on <a target="_blank" href="https://www.linkedin.com/in/gert-svaiko/">LinkedIn here</a>.</p>
<p>You might also enjoy some other articles I have written:</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/javascript-hacks/">10 JavaScript Hacks Every Web Developer Should Know</a></li>
<li><a target="_blank" href="https://www.smashingmagazine.com/2020/12/progressive-web-apps/">How To Optimize Progressive Web Apps: Going Beyond The Basics</a></li>
<li><a target="_blank" href="https://www.tripwire.com/state-of-security/featured/most-common-website-security-attacks-and-how-to-protect-yourself/">The 10 Most Common Website Security Attacks (and How to Protect Yourself)</a></li>
</ul>
<p><em><a target="_blank" href="https://www.hippopx.com/en/code-coder-coding-computer-conceptual-css-data-355989">Image Credit</a></em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Hacks for Creating JavaScript Arrays ]]>
                </title>
                <description>
                    <![CDATA[ By Glad Chinda Insightful tips for creating and cloning arrays in JavaScript. _Original Photo by [Unsplash](https://unsplash.com/photos/FXFz-sW0uwo?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" rel="noopener" target="_blank" ti... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/https-medium-com-gladchinda-hacks-for-creating-javascript-arrays-a1b80cb372b/</link>
                <guid isPermaLink="false">66c3570d7ef110ecbf367aff</guid>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ hacks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 18 Jul 2018 22:59:31 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*Ikt9LNJUhCX7QxbjnwKstA.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Glad Chinda</p>
<h4 id="heading-insightful-tips-for-creating-and-cloning-arrays-in-javascript">Insightful tips for creating and cloning arrays in JavaScript.</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/IH842JnVoctZM6QoKOfXQe8luuYHXHjMuNxf" alt="Image" width="800" height="425" loading="lazy">
_Original Photo by [Unsplash](https://unsplash.com/photos/FXFz-sW0uwo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" rel="noopener" target="_blank" title=""&gt;Markus Spiske on &lt;a href="https://unsplash.com/search/photos/code?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" rel="noopener" target="<em>blank" title=")</em></p>
<p>A very important aspect of every programming language is the data types and structures available in the language. Most programming languages provide data types for representing and working with complex data. If you have worked with languages like Python or Ruby, you should have seen data types like <strong>lists</strong>, <strong>sets</strong>, <strong>tuples</strong>, <strong>hashes</strong>, <strong>dicts</strong>, and so on.</p>
<p>In JavaScript, there are not so many complex data types — you simply have <strong>arrays</strong> and <strong>objects</strong>. However, in ES6, a couple of data types and structures were added to the language, such as <strong>symbols</strong>, <strong>sets</strong>, and <strong>maps</strong>.</p>
<blockquote>
<p><em>Arrays in JavaScript are high-level list-like objects with</em> a length property and <em>integer properties as indexes.</em></p>
</blockquote>
<p>In this article, I share a couple of hacks for creating new JavaScript arrays or cloning already existing ones.</p>
<h3 id="heading-creating-arrays-the-array-constructor">Creating Arrays: The Array Constructor</h3>
<p>The most popular method for creating arrays is using the <strong>array literal</strong> syntax, which is very straightforward. However, when you want to dynamically create arrays, the array literal syntax may not always be the best method. An alternative method is using the <code>Array</code> constructor.</p>
<p>Here is a simple code snippet showing the use of the <code>Array</code> constructor.</p>


<p>From the previous snippet, we can see that the <code>Array</code> constructor creates arrays differently depending on the arguments it receives.</p>
<h3 id="heading-new-arrays-with-defined-length">New Arrays: With Defined Length</h3>
<p>Let’s look more closely at what happens when creating a new <code>Array</code> of a given length. The constructor just sets the <code>length</code> property of the array to the given length, without setting the keys.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/HuAR3m0WmxP390Ezk4Ufyam-9vlyDzwNvEzi" alt="Image" width="800" height="296" loading="lazy"></p>
<p>From the above snippet, you may be tempted to think that each key in the array was set to a value of <code>undefined</code>. But the reality is that those keys were never set (they don’t exist).</p>
<p>The following illustration makes it clearer:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/wtfHBQo1MBofKp-EVs-IB6qqq07cfM18rK8I" alt="Image" width="800" height="307" loading="lazy"></p>
<p>This makes it useless to attempt to use any of the array iteration methods such as <code>map()</code>, <code>filter()</code> or <code>reduce()</code> to manipulate the array. Let’s say we want to fill each index in the array with the number <code>5</code> as a value. We will attempt the following:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1OHTGXHuG93TuWcOpzRVtUNjoB-BFP3Pykq5" alt="Image" width="800" height="327" loading="lazy"></p>
<p>We can see that <code>map()</code> didn’t work here, because the index properties don’t exist on the array — only the <code>length</code> property exists.</p>
<p>Let’s see different ways we can fix this issue.</p>
<h4 id="heading-1-using-arrayprototypefill">1. Using Array.prototype.fill()</h4>
<p>The <code>**fill()**</code> method fills all the elements of an array from a start index to an end index with a static value. The end index is not included. You can learn more about <code>fill()</code> <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill">here</a>.</p>
<p><strong>Note that <code>fill()</code> will only work in browsers with ES6 support.</strong></p>
<p>Here is a simple illustration:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/w3CWlvnWqG5VEy6qupnAYvTqECGhPdj3P9Wu" alt="Image" width="800" height="404" loading="lazy"></p>
<p>Here, we have been able to fill all the elements of our created array with <code>5</code>. You can set any static value for different indexes of the array using the <code>fill()</code> method.</p>
<h4 id="heading-2-using-arrayfrom">2. Using Array.from()</h4>
<p>The <code>**Array.from()**</code> method creates a new, shallow-copied <code>Array</code> instance from an array-like or iterable object. You can learn more about <code>Array.from()</code> <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from">here</a>.</p>
<p><strong>Note that <code>Array.from()</code> will only work in browsers with ES6 support.</strong></p>
<p>Here is a simple illustration:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/XfZGhDWQWU1VwxliMKIjYgHuwYvkfvPSBkVT" alt="Image" width="800" height="377" loading="lazy"></p>
<p>Here, we now have true <code>undefined</code> values set for each element of the array using <code>Array.from()</code>. This means we can now go ahead and use methods like <code>.map()</code> and <code>.filter()</code> on the array, since the index properties now exist.</p>
<p>One more thing worth noting about <code>Array.from()</code> is that it can take a second argument, which is a <strong>map function.</strong> It will be called on every element of the array. This makes it redundant calling <code>.map()</code> after <code>Array.from()</code>.</p>
<p>Here is a simple example:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/UgaAHFIo4xzuw4cc4bI1iaxaPzGHKkTCbjYK" alt="Image" width="800" height="267" loading="lazy"></p>
<h4 id="heading-3-using-the-spread-operator">3. Using the Spread Operator</h4>
<p>The <strong>spread operator</strong> (<code>...</code>), added in ES6, can be used to spread the elements of the array, setting the missing elements to a value of <code>undefined</code>. This will produce the same result as simply calling <code>Array.from()</code> with just the array as the only argument.</p>
<p>Here is a simple illustration of using the spread operator:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/gZrwaPsFq15WkPf2BnuAb2wA54JdIEXx7VNv" alt="Image" width="800" height="377" loading="lazy"></p>
<p>You can go ahead and use methods like <code>.map()</code> and <code>.filter()</code> on the array, since the index properties now exist.</p>
<h3 id="heading-using-arrayof">Using Array.of()</h3>
<p>Just like we saw with creating new arrays using the <code>Array</code> constructor or function, <code>**Array.of()**</code> behaves in a very similar fashion. In fact, the only difference between <code>Array.of()</code> and <code>Array</code> is in how they handle a single integer argument passed to them.</p>
<p>While <code>**Array.of(5)**</code> creates a new array with a single element, <code>5</code>, and a length property of <code>1</code>, <code>**Array(5)**</code> creates a new empty array with 5 empty slots and a length property of <code>5</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> array1 = <span class="hljs-built_in">Array</span>.of(<span class="hljs-number">5</span>); <span class="hljs-comment">// [5]</span>
<span class="hljs-keyword">var</span> array2 = <span class="hljs-built_in">Array</span>(<span class="hljs-number">5</span>); <span class="hljs-comment">// Array(5) {length: 5}</span>
</code></pre>
<p>Besides this major difference, <code>Array.of()</code> behaves just like the <code>Array</code> constructor. You can learn more about <code>Array.of()</code> <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of">here</a>.</p>
<p><strong>Note that <code>Array.of()</code> will only work in browsers with ES6 support.</strong></p>
<h3 id="heading-converting-to-arrays-array-likes-and-iterables">Converting to Arrays: Array-likes and Iterables</h3>
<p>If you have been writing JavaScript functions long enough, you should already know about the <code>arguments</code> object — which is an <strong>array-like</strong> object available in every function to hold the list of arguments the function received. Although the <code>arguments</code> object looks much like an array, it does not have access to the <code>Array.prototype</code> methods.</p>
<p>Prior to ES6, you would usually see a code snippet like the following when trying to convert the <code>arguments</code> object to an array:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/NaMaYAla-PzcPacVZGr3E03twovKgKTuRVwm" alt="Image" width="800" height="350" loading="lazy"></p>
<p>With <code>Array.from()</code> or the spread operator, you can conveniently convert any array-like object into an array. Hence, instead of doing this:</p>
<pre><code><span class="hljs-keyword">var</span> args = <span class="hljs-built_in">Array</span>.prototype.slice.call(<span class="hljs-built_in">arguments</span>);
</code></pre><p>you can do either of these:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Using Array.from()</span>
<span class="hljs-keyword">var</span> args = <span class="hljs-built_in">Array</span>.from(<span class="hljs-built_in">arguments</span>);

<span class="hljs-comment">// Using the Spread operator</span>
<span class="hljs-keyword">var</span> args = [...arguments];
</code></pre>
<p>These also apply to <strong>iterables</strong> as shown in the following illustration:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/87TEnXS9-qV7Lak1XBBcEYiQVvh96FqXDJXc" alt="Image" width="800" height="269" loading="lazy"></p>
<h3 id="heading-case-study-range-function">Case Study: Range Function</h3>
<p>As a case study before we proceed, we will create a simple <code>**range()**</code> function to implement the new <strong>array hack</strong> we just learned. The function has the following signature:</p>
<pre><code class="lang-js">range(start: number, <span class="hljs-attr">end</span>: number, <span class="hljs-attr">step</span>: number) =&gt; <span class="hljs-built_in">Array</span>&lt;number&gt;
</code></pre>
<p>Here is the code snippet:</p>


<p>In this code snippet, we used <code>Array.from()</code> to create the new range array of dynamic length and then populate it sequentially incremented numbers by providing a mapping function.</p>
<p><strong>Note that the above code snippet will not work for browsers without ES6 support except if you use polyfills.</strong></p>
<p>Here are some results from calling the <code>**range()**</code> function defined in the above code snippet:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/zFBQwh8KfkoDDWXcZDl8YnDe7e9jBEsocdCa" alt="Image" width="800" height="675" loading="lazy"></p>
<p>You can get a live code demo by running the following pen on <strong>Codepen</strong>:</p>
<div class="embed-wrapper"><iframe height="500" width="500" style="width:100%" src="//codepen.io/gladchinda/embed/QxeXzm/?height=265&amp;theme-id=0&amp;default-tab=js,result" title="Embedded content" loading="lazy">
  See the Pen <a href="https://codepen.io/gladchinda/pen/QxeXzm/">QxeXzm</a> by Glad Chinda
  (<a href="https://codepen.io/gladchinda">@gladchinda</a>) on <a href="https://codepen.io">CodePen</a>.
</iframe></div>

<h3 id="heading-cloning-arrays-the-challenge">Cloning Arrays: The Challenge</h3>
<p>In JavaScript, arrays and objects are reference types. This means that when a variable is assigned an array or object, what gets assigned to the variable is a reference to the location in memory where the array or object was stored.</p>
<p>Arrays, just like every other object in JavaScript, are reference types. <strong>This means that arrays are copied by reference and not by value.</strong></p>
<p>Storing reference types this way has the following consequences:</p>
<h4 id="heading-1-similar-arrays-are-not-equal"><strong>1. Similar arrays are not equal.</strong></h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/brYlg3Dp3gVRqGqHGkMBR2XR7eLvWQK8xymc" alt="Image" width="800" height="161" loading="lazy"></p>
<p>Here, we see that although <code>array1</code> and <code>array2</code> contain seemingly the same array specifications, they are not equal. This is because the reference to each of the arrays points to a different location in memory.</p>
<h4 id="heading-2-arrays-are-copied-by-reference-and-not-by-value"><strong>2. Arrays are copied by reference and not by value.</strong></h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/PZF-lU5f4C-OWkNLeF-q4g9T2anP6k88PPr1" alt="Image" width="800" height="296" loading="lazy"></p>
<p>Here, we attempt to copy <code>array1</code> to <code>array2</code>, but what we are basically doing is pointing <code>array2</code> to the same location in memory that <code>array1</code> points to. Hence, both <code>array1</code> and <code>array2</code> point to the same location in memory and are equal.</p>
<p>The implication of this is that when we make a change to <code>array2</code> by removing the last item, the last item of <code>array1</code> also gets removed. This is because the change was actually made to the array stored in memory, whereas <code>array1</code> and <code>array2</code> are just pointers to that same location in memory where the array is stored.</p>
<h3 id="heading-cloning-arrays-the-hacks">Cloning Arrays: The Hacks</h3>
<h4 id="heading-1-using-arrayprototypeslice"><strong>1. Using Array.prototype.slice()</strong></h4>
<p>The <code>**slice()**</code> method creates a shallow copy of a portion of an array without modifying the array. You can learn more about <code>slice()</code> <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice">here</a>.</p>
<p>The trick is to call <code>slice()</code> either with<code>0</code> as the only argument or without any arguments at all:</p>
<pre><code class="lang-js"><span class="hljs-comment">// with O as only argument</span>
array.slice(<span class="hljs-number">0</span>);

<span class="hljs-comment">// without argument</span>
array.slice();
</code></pre>
<p>Here is a simple illustration of cloning an array with <code>slice()</code>:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/-XUoysUS92IrVW9lYY6EkJHXv8vKw0yahdaW" alt="Image" width="800" height="296" loading="lazy"></p>
<p>Here, you can see that <code>array2</code> is a clone of <code>array1</code> with the same items and length. However, they point to different locations in memory, and as a result are not equal. You also notice that when we make a change to <code>array2</code> by removing the last item, <code>array1</code> remains unchanged.</p>
<h4 id="heading-2-using-arrayprototypeconcat"><strong>2. Using Array.prototype.concat()</strong></h4>
<p>The <code>**concat()**</code> method is used to merge two or more arrays, resulting in a new array, while the original arrays are left unchanged. You can learn more about <code>concat()</code> <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat">here</a>.</p>
<p>The trick is to call <code>concat()</code> either with an empty array(<code>[]</code>) as argument or without any arguments at all:</p>
<pre><code class="lang-js"><span class="hljs-comment">// with an empty array</span>
array.concat([]);

<span class="hljs-comment">// without argument</span>
array.concat();
</code></pre>
<p>Cloning an array with <code>concat()</code> is quite similar to using <code>slice()</code>. Here is a simple illustration of cloning an array with <code>concat()</code>:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/OXjY30kwODk5622BQraHtZfHxN5d5gewTeZj" alt="Image" width="800" height="296" loading="lazy"></p>
<h4 id="heading-3-using-arrayfrom">3. Using Array.from()</h4>
<p>Like we saw earlier, <code>**Array.from()**</code> can be used to create a new array which is a shallow-copy of the original array. Here is a simple illustration:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/kS-1uaQbt9K6zFk4PZWfmnLXHADDnHaVqELf" alt="Image" width="800" height="296" loading="lazy"></p>
<h4 id="heading-4-using-array-destructuring">4. Using Array Destructuring</h4>
<p>With ES6, we have some more powerful tools in our toolbox such as <strong>destructuring</strong>, <strong>spread</strong> <strong>operator</strong>, <strong>arrow functions</strong>, and so on. Destructuring is a very powerful tool for extracting data from complex types like arrays and objects.</p>
<p>The trick is to use a technique called <strong>rest parameters,</strong> which involves a combination of array destructuring and the spread operator as shown in the following snippet:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> [...arrayClone] = originalArray;
</code></pre>
<p>The above snippet creates a variable named <code>arrayClone</code> which is a clone of the <code>originalArray</code>. Here is a simple illustration of cloning an array using array destructuring:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/aohdaDoLpdH1XJ8Thk5U4JE7u0g89qsaTUcI" alt="Image" width="800" height="296" loading="lazy"></p>
<h1 id="heading-cloning-shallow-versus-deep">Cloning: Shallow versus Deep</h1>
<p>All the array cloning techniques we’ve explored so far produce a <strong><em>shallow copy</em></strong> of the array. This won’t be an issue if the array contains only primitive values. However, if the array contains nested object references, those references will remain intact even when the array is cloned.</p>
<p>Here is a very simple demonstration of this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/06/image.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Notice that modifying the nested array in <code>array1</code> also modified the nested array in <code>array2</code> and vice-versa.</p>
<p>The solution to this problem is to create a <strong><em>deep copy</em></strong> of the array and there are a couple of ways to do this.</p>
<h2 id="heading-1-the-json-technique">1. The JSON technique</h2>
<p>The easiest way to create a deep copy of an array is by using a combination of <code>[**JSON.stringify()**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)</code> and <code>[**JSON.parse()**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)</code>.</p>
<p><code>JSON.stringify()</code> converts a JavaScript value to a valid JSON string, while <code>JSON.parse()</code> converts a JSON string to a corresponding JavaScript value or object.</p>
<p>Here is a simple example:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/06/image-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<blockquote>
<p>The JSON technique has some flaws especially when values other than strings, numbers and booleans are involved.</p>
</blockquote>
<p>These flaws in the JSON technique can be majorly attributed to the manner in which the <code>JSON.stringify()</code> method converts values to JSON string.</p>
<p>Here is a simple demonstration of this flaw in trying to <code>**JSON.stringify()**</code> a value containing nested function.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/06/image-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-2-deep-copy-helper">2. Deep Copy Helper</h2>
<p>A viable alternative to the JSON technique will be to implement your own <strong><em>deep copy helper function</em></strong> for cloning reference types whether they be arrays or objects.</p>
<p>Here is a very simple and minimalistic deep copy function called <code>**deepClone**</code>:</p>


<p>Now this is not the best of deep copy functions out there, like you will soon see with some JavaScript libraries — however, it performs deep copying to a pretty good extent.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/06/image-3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-3-using-javascript-libraries">3. Using JavaScript Libraries</h2>
<p>The deep copy helper function we just defined is not robust enough in cloning all the kinds of JavaScript data that may be nested within complex objects or arrays.</p>
<p>JavaScript libraries like <a target="_blank" href="https://lodash.com/"><strong>Lodash</strong></a> and <a target="_blank" href="https://jquery.com/"><strong>jQuery</strong></a> provide more robust deep copy utility functions with support for different kinds of JavaScript data.</p>
<p>Here is an example that uses <code>**_.cloneDeep()**</code> from the Lodash library:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/06/image-4.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Here is the same example but using <code>**$.extend()**</code> from the jQuery library:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/06/image-5.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>In this article, we have been able to explore several techniques for dynamically creating new arrays and cloning already existing ones, including converting array-like objects and iterables to arrays.</p>
<p>We have also seen how some of the new features and enhancements introduced in ES6 can enable us to effectively perform certain manipulations on arrays.</p>
<p>We used features like destructuring and the spread operator for cloning and spreading arrays. You can learn more about destructuring from <a target="_blank" href="https://codeburst.io/es6-destructuring-the-complete-guide-7f842d08b98f">this article</a>.</p>
<h4 id="heading-clap-amp-follow">Clap &amp; Follow</h4>
<p>If you found this article insightful, you are free to give some rounds of applause if you don’t mind.</p>
<p>You can also follow me on Medium (<a target="_blank" href="https://www.freecodecamp.org/news/https-medium-com-gladchinda-hacks-for-creating-javascript-arrays-a1b80cb372b/undefined">Glad Chinda</a>) for more insightful articles you may find helpful. You can also follow me on Twitter (<a target="_blank" href="https://twitter.com/@gladchinda">@gladchinda</a>).</p>
<p><strong><em>Happy hacking…</em></strong></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
