avatarYang Zhou

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

11140

Abstract

level deep), the shallow copy cannot really copy them, and editing the array <code>b</code>’s inner array will also change <code>a</code>’s:</p><div id="8127"><pre><span class="hljs-keyword">let</span> a = [<span class="hljs-number">1</span>, [<span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>], <span class="hljs-number">3</span>] <span class="hljs-keyword">let</span> b = [].<span class="hljs-title function_">concat</span>(a) b[<span class="hljs-number">1</span>].<span class="hljs-title function_">push</span>(<span class="hljs-number">8</span>) <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a, b) <span class="hljs-comment">// [ 1, [ 2, 2, 2, 8 ], 3 ] [ 1, [ 2, 2, 2, 8 ], 3 ]</span></pre></div><h1 id="7f3c">4. Use JSON Tricks for Deep Copy</h1><p id="1688">To implement deep copy, a popular trick is to use <code>JSON.stringify()</code> and <code>JSON.parse()</code> together.</p><p id="604c">The idea is to serialize the object (or array) into a JSON-formatted string and then parse it back into a new object. This process effectively and elegantly creates a deep copy of the original array or object:</p><div id="6403"><pre><span class="hljs-keyword">let</span> a = [<span class="hljs-number">1</span>, [<span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>], <span class="hljs-number">3</span>] <span class="hljs-keyword">let</span> b = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(a)) b[<span class="hljs-number">1</span>].<span class="hljs-title function_">push</span>(<span class="hljs-number">8</span>) <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a, b) <span class="hljs-comment">// [ 1, [ 2, 2, 2 ], 3 ] [ 1, [ 2, 2, 2, 8 ], 3 ]</span></pre></div><p id="833e">The JSON-based trick is useful in most simple cases. However, we need to know that to make this method effective, the object must be <i>JSON serializable.</i></p><p id="f8dc">Let’s see a counterexample:</p><div id="5b3f"><pre><span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">func</span>: <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">"hello world!"</span>); } }

<span class="hljs-keyword">const</span> cp_obj=<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(obj))

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(cp_obj[<span class="hljs-string">'func'</span>]) <span class="hljs-comment">// undefined</span></pre></div><p id="a1a0">The value of the <code>obj['func']</code> is a function. It cannot be copied through the JSON trick anymore.</p><p id="2981">In this case, we can harness a famous third-party JS library named <code>lodash</code>:</p><div id="88d9"><pre><span class="hljs-keyword">const</span> _ = <span class="hljs-built_in">require</span>(<span class="hljs-string">'lodash'</span>); <span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">func</span>: <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">"hello world!"</span>); } }

<span class="hljs-keyword">const</span> cp_obj=_.<span class="hljs-title function_">cloneDeep</span>(obj)

cp_obj<span class="hljs-string">'func'</span> <span class="hljs-comment">// hello world!</span></pre></div><p id="de42">As demonstrated above, the <code>cloneDeep</code> method from <code>lodash</code> perfectly cloned the function inside the <code>obj</code> and it can be executed successfully on the new <code>cp_obj</code>.</p><h1 id="e2ca">5. Implement For Loops Skillfully</h1><p id="e1fb">If you are still using the C/C++ style for loops in JavaScript, you definitely need to upgrade your skill.</p><p id="f0de">Of course, the following code is correct, but it’s not “JavaScript” enough.</p><div id="bf35"><pre><span class="hljs-keyword">const</span> arr = [<span class="hljs-string">'Y'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'n'</span>, <span class="hljs-string">'g'</span>] <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < arr.<span class="hljs-property">length</span>; i++) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(arr[i]) } <span class="hljs-comment">// Y</span> <span class="hljs-comment">// a</span> <span class="hljs-comment">// n</span> <span class="hljs-comment">// g</span></pre></div><p id="57b6">The idiomatic ways to write the above code in JavaScript are as follows:</p><h2 id="0b63">Use the forEach() method</h2><p id="f3a0">The forEach method is ideal for iterating the elements of an array:</p><div id="4ba2"><pre><span class="hljs-keyword">const</span> author = [ <span class="hljs-string">'Y'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'n'</span>, <span class="hljs-string">'g'</span> ]; author.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">c</span>)=></span>{<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(c)}) <span class="hljs-comment">// Y</span> <span class="hljs-comment">// a</span> <span class="hljs-comment">// n</span> <span class="hljs-comment">// g</span></pre></div><h2 id="7f04">Use the map() function</h2><p id="bc18">If you read open-source JavaScript programs, you probably will meet the <code>map()</code> function. It’s one of the most popular methods in JavaScript:</p><div id="a0fc"><pre><span class="hljs-keyword">const</span> author = [ <span class="hljs-string">'Y'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'n'</span>, <span class="hljs-string">'g'</span> ]; author.<span class="hljs-title function_">map</span>(<span class="hljs-function">(<span class="hljs-params">c</span>)=></span>{<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(c)}) <span class="hljs-comment">// Y</span> <span class="hljs-comment">// a</span> <span class="hljs-comment">// n</span> <span class="hljs-comment">// g</span></pre></div><p id="8597">The behavior of the <code>map()</code> function is mostly similar with <code>forEach()</code>, but there is a significant difference:</p><p id="31d0">The <code>map()</code> method returns a new array with the same length as the original array, where each element is the result of the function call on the corresponding element. The original array remains unchanged. The <code>forEach()</code> method doesn’t return anything.</p><p id="f5e0">The following code illustrates how to get a new array using the <code>map()</code> function:</p><div id="5f0c"><pre><span class="hljs-keyword">const</span> author = [<span class="hljs-string">'Y'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'n'</span>, <span class="hljs-string">'g'</span>]; <span class="hljs-keyword">const</span> cute_author = author.<span class="hljs-title function_">map</span>(<span class="hljs-function">(<span class="hljs-params">c</span>) =></span> c + <span class="hljs-string">':)'</span>) <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(cute_author) <span class="hljs-comment">// [ 'Y:)', 'a:)', 'n:)', 'g:)' ]</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(author) <span class="hljs-comment">// [ 'Y', 'a', 'n', 'g' ]</span></pre></div><p id="2af4">However, we cannot get the new array with the <code>forEach()</code> function:</p><div id="4153"><pre><span class="hljs-keyword">const</span> author = [<span class="hljs-string">'Y'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'n'</span>, <span class="hljs-string">'g'</span>]; <span class="hljs-keyword">const</span> cute_author = author.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">c</span>) =></span> c + <span class="hljs-string">':)'</span>) <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(cute_author) <span class="hljs-comment">// undefined</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(author) <span class="hljs-comment">// [ 'Y', 'a', 'n', 'g' ]</span></pre></div><h2 id="c518">Use the for…of… structure</h2><p id="a6b1">ES6 is a milestone for JavaScript. Many good features were introduced by this version. The “for…of…” method is one of them.</p><div id="289f"><pre><span class="hljs-keyword">const</span> author = [ <span class="hljs-string">'Y'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'n'</span>, <span class="hljs-string">'g'</span> ]; <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> char <span class="hljs-keyword">of</span> author){ <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(char); } <span class="hljs-comment">// Y</span> <span class="hljs-comment">// a</span> <span class="hljs-comment">// n</span> <span class="hljs-comment">// g</span></pre></div><h2 id="8a4a">Use the for…in… structure</h2><p id="7b0a">The “for…in…” syntax is also able to implement the same thing as we did. But we should be careful about the difference between “for…in…” and “for…of…”. The following code snippet explains it:</p><div id="f587"><pre><span class="hljs-keyword">const</span> author = [ <span class="hljs-string">'Y'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'n'</span>, <span class="hljs-string">'g'</span> ]; <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> idx <span class="hljs-keyword">in</span> author){ <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(author[idx]); } <span class="hljs-comment">// Y</span> <span class="hljs-comment">// a</span> <span class="hljs-comment">// n</span> <span class="hljs-comment">// g</span></pre></div><h1 id="b5e5">6. The Fastest Way To Remove Duplicate Values of an Array</h1><p id="f532">ES6 introduced a new data structure for JavaScrip — set. A set is a collection of items that are unique.</p><p id="f7ec">Thanks to the feature of sets, it makes removing duplicate values of an array much simpler.</p><div id="6074"><pre><span class="hljs-keyword">const</sp

Options

an> a = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-number">6</span>, <span class="hljs-number">6</span>, <span class="hljs-number">6</span>, <span class="hljs-number">9</span>] <span class="hljs-keyword">const</span> unique_a = [...<span class="hljs-keyword">new</span> <span class="hljs-title class_">Set</span>(a)] <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(unique_a) <span class="hljs-comment">// [ 1, 2, 6, 9 ]</span></pre></div><p id="59b0">As the above program shows, we can leverage the usage of the spread operator and <code>Set()</code> method to get unique elements of an array conveniently.</p><h1 id="e323">7. Reverse a String in One Line of Code</h1><p id="da41">To reverse a string in JavaScript, we don’t need to write a for loop.</p><p id="4188">There are 3 steps to do this operation:</p><ol><li>Split the string into an array</li><li>Reverse the array</li><li>Convert the array into a string</li></ol><p id="ad18">These 3 steps need to harness 3 different built-in methods as follows:</p><div id="09a9"><pre><span class="hljs-keyword">const</span> author = <span class="hljs-string">"Yang Zhou"</span>; <span class="hljs-keyword">const</span> reversedAuthor = author.<span class="hljs-title function_">split</span>(<span class="hljs-string">""</span>).<span class="hljs-title function_">reverse</span>().<span class="hljs-title function_">join</span>(<span class="hljs-string">""</span>); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(reversedAuthor); <span class="hljs-comment">// uohZ gnaY</span></pre></div><p id="a199">It’s a decent one-liner, but to be honest, the JS way to reverse a string is not as elegant as Python. Due to its beautiful <a href="https://readmedium.com/5-python-slicing-tricks-that-will-make-your-code-more-elegant-bd5e27c73f7">slicing syntax</a>, Python can do the same thing much neater:</p><div id="247b"><pre>author = <span class="hljs-string">'Yang Zhou'</span> reversed_author = author[::-<span class="hljs-number">1</span>] <span class="hljs-built_in">print</span>(reversed_author) <span class="hljs-comment"># uohZ gnaY</span></pre></div><p id="c753">By the way, an easy way to check if a JavaScript string is a palindrome is by comparing the string to its reversed version:</p><div id="afb6"><pre><span class="hljs-keyword">const</span> author = <span class="hljs-string">'YangnaY'</span> <span class="hljs-keyword">const</span> isPalindrome = author.<span class="hljs-title function_">split</span>(<span class="hljs-string">""</span>).<span class="hljs-title function_">reverse</span>().<span class="hljs-title function_">join</span>(<span class="hljs-string">""</span>) === author <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(isPalindrome) <span class="hljs-comment">// true</span></pre></div><h1 id="39cc">8. Count Elements in an Array Quickly</h1><p id="5474">How to count every element in a JavaScript array?</p><p id="c9b2">Using a for loop to go through the items one by one and count them in the process?</p><p id="5b43">It’s a solution, but not an elegant solution at all. I would say <code>lodash</code> is a super useful JS library:</p><div id="49ab"><pre><span class="hljs-keyword">const</span> _ = <span class="hljs-built_in">require</span>(<span class="hljs-string">'lodash'</span>); <span class="hljs-keyword">const</span> author = [<span class="hljs-string">'Y'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'n'</span>, <span class="hljs-string">'n'</span>, <span class="hljs-string">'g'</span>, <span class="hljs-string">'g'</span>, <span class="hljs-string">'g'</span>, <span class="hljs-string">'g'</span>] <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(_.<span class="hljs-title function_">countBy</span>(author)) <span class="hljs-comment">// { Y: 1, a: 3, n: 2, g: 4 }</span></pre></div><p id="3030">If you prefer to not use a third-party library, it’s not hard to implement a similar function by yourself:</p><div id="fa17"><pre><span class="hljs-keyword">const</span> <span class="hljs-title function_">countBy</span> = (<span class="hljs-params">arr</span>) => { <span class="hljs-keyword">let</span> count = {}; arr.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">e</span>) =></span> { count[e] = (count[e] || <span class="hljs-number">0</span>) + <span class="hljs-number">1</span>; }); <span class="hljs-keyword">return</span> count; }

<span class="hljs-keyword">const</span> author = [<span class="hljs-string">'Y'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'n'</span>, <span class="hljs-string">'n'</span>, <span class="hljs-string">'g'</span>, <span class="hljs-string">'g'</span>, <span class="hljs-string">'g'</span>, <span class="hljs-string">'g'</span>] <span class="hljs-keyword">const</span> charCount = <span class="hljs-title function_">countBy</span>(author); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(charCount); <span class="hljs-comment">// { Y: 1, a: 3, n: 2, g: 4 }</span></pre></div><p id="1d8c">If you merely need to count one specific item, the <code>filter()</code> method is a good choice:</p><div id="c212"><pre><span class="hljs-keyword">const</span> author = [<span class="hljs-string">'Y'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'n'</span>, <span class="hljs-string">'n'</span>, <span class="hljs-string">'g'</span>, <span class="hljs-string">'g'</span>, <span class="hljs-string">'g'</span>, <span class="hljs-string">'g'</span>]

<span class="hljs-comment">// Filter all elements equal to 'a' and return the length (count)</span> <span class="hljs-keyword">const</span> countOfa = author.<span class="hljs-title function_">filter</span>(<span class="hljs-function"><span class="hljs-params">x</span> =></span> x === <span class="hljs-string">'a'</span>).<span class="hljs-property">length</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(countOfa) <span class="hljs-comment">// 3</span></pre></div><h1 id="8d84">9. Simplify Your Code with Comma Operator</h1><p id="e774">Commas are more powerful in JavaScript because of the syntax of comma operators.</p><p id="7375">The comma (<code>,</code>) operator evaluates each expression (from left to right) and returns the value of the last one. It will be super helpful to simplify your code if you can leverage its power skillfully.</p><p id="8f9f">For instance, the following program demonstrates the utilization of the comma operator to accomplish two distinct purposes with a single line of code:</p><div id="a29d"><pre><span class="hljs-keyword">let</span> sum = <span class="hljs-number">0</span>; <span class="hljs-keyword">const</span> squares = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>].<span class="hljs-title function_">map</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> (sum += x, x * x)); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(squares); <span class="hljs-comment">// [1, 4, 9, 16, 25]</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(sum); <span class="hljs-comment">// 15</span></pre></div><p id="f184">Given that the comma operator always returns the result of the last expression, we can leverage this feature to avoid writing many <code>return</code> keywords.</p><p id="fab3">For example, the <code>get_author()</code> function of the following code returns the <code>arr</code> after changing it:</p><div id="74e7"><pre><span class="hljs-keyword">const</span> <span class="hljs-title function_">get_author</span> = arr => { arr.<span class="hljs-title function_">push</span>(<span class="hljs-string">'g'</span>) <span class="hljs-keyword">return</span> arr } <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">get_author</span>([<span class="hljs-string">'Y'</span>,<span class="hljs-string">'a'</span>,<span class="hljs-string">'n'</span>])) <span class="hljs-comment">// [ 'Y', 'a', 'n', 'g' ]</span></pre></div><p id="187e">This is the best scenario to let the comma operator show off:</p><div id="0db1"><pre><span class="hljs-keyword">const</span> <span class="hljs-title function_">get_author</span> = arr => (arr.<span class="hljs-title function_">push</span>(<span class="hljs-string">'g'</span>), arr) <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">get_author</span>([<span class="hljs-string">'Y'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'n'</span>])) <span class="hljs-comment">// [ 'Y', 'a', 'n', 'g' ]</span></pre></div><p id="db7a">Thanks for reading ❤️. Which one is your favourite trick?</p><p id="029e"><b><i>If you are new here, feel free to take a glimpse into my 10-year love-hate relationship with programming:</i></b></p><div id="c911" class="link-block"> <a href="https://readmedium.com/my-first-10-years-of-programming-3cddf46b8b31"> <div> <div> <h2>My First 10 Years of Programming</h2> <div><h3>And how my life has been changed so much</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*cSBoMEX4ng12lkABRdBLYQ.jpeg)"></div> </div> </div> </a> </div><h1 id="7152">In Plain English</h1><p id="6857"><i>Thank you for being a part of our community! Before you go:</i></p><ul><li><i>Be sure to <b>clap</b> and <b>follow</b> the writer! 👏</i></li><li><i>You can find even more content at <a href="https://plainenglish.io/"><b>PlainEnglish.io</b></a><b> 🚀</b></i></li><li><i>Sign up for our <a href="http://newsletter.plainenglish.io/"><b>free weekly newsletter</b></a>. 🗞️</i></li><li><i>Follow us on <a href="https://twitter.com/inPlainEngHQ"><b>Twitter</b></a></i>, <a href="https://www.linkedin.com/company/inplainenglish/"><b><i>LinkedIn</i></b></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><b><i>YouTube</i></b></a>, and <a href="https://discord.gg/GtDtUAvyhW"><b><i>Discord</i></b></a><b><i>.</i></b></li></ul></article></body>

JavaScript

9 JavaScript Tricks That Make Your Code Fantastic

The elegance of JavaScript goes beyond what you can imagine

Image from Wallhaven

JavaScript, with the original purpose of inventing it, was a simple language to add some functionalities to a website. Surprisingly, nowadays, it is everywhere and far more complex.

As web applications are becoming more and more complicated, JavaScript is evolving so fast as well. It’s not as easy as the old days to write neat, readable, and maintainable JavaScript programs anymore.

This article will summarize 9 practical JavaScript tips and tricks to help you write better front-end code and feel the beauty of this elegant programming language.

Talk is cheap, let’s check out the code.

1. Break Nested Loops in a JavaScript Way

Many programming languages have the break keyword for breaking out of a loop.

However, this keyword is merely for going out of the current loop. If you have to break from a nested loop, it could be hard to keep your code neat.

For example, how can you implement the following code?

for (let i in arr1) {
    for (let j in arr2) {
        for (let k in arr3) {
            if (k === j - 4) {
                // need to break out of the second loop
            }
            if (k === i - 3) {
                // need to break out of the outermost loop
            }
        }
    }
}

In other languages, you probably need to declare boolean variables as “flags” for the outer loops, and check the breaking “flags” whenever entering the corresponding loops. This method works, but makes your code a little messy if there are many boolean flags.

JavaScript provides a syntax-level solution for this scenario — label.

You can use a label to identify a loop, and later refer to the label to break the corresponding loop.

Therefore, the JavaScript way to implement the above code is as follows:

loop1:
    for (let i in arr1) {
        loop2:
            for (let j in arr2) {
                for (let k in arr3) {
                    if (k === j - 4) {
                        break loop2
                    }
                    if (k === i - 3) {
                        break loop1
                    }
                }
            }
    }

The loop1 and loop2 are labels for these two outer loops, so it’s effortless to break the matching loop using its label. No need to declare other variables as “flags”.

2. Leverage Spread Operators for Destructuring Assignments

Spread Operators are the key to tidy JavaScript programs.

let leaders = {
    me: "Yang",
    T: "Elon",
    A: "Tim",
    MS: "Bill"
}
let {me, ...others} = leaders

console.log(me)
// "Yang"
console.log(others)
// {T: "Elon", A: "Tim", MS: "Bill"}

As the above example shows, we used a spread operator, which is as simple as three dots, to assign the value of leaders["me"] into a variable named me, and the other key-value pairs into an array others.

In React, this trick is commonly used for receiving multiple values from the props when building a UI component.

3. Several Ways To Shallow Copy Objects or Arrays

As we know, non-primitive data types such as objects and arrays are passed by reference in JavaScript.

Therefore, as the following example, changing the “new” array will change the original array as well:

let a = [1, 2, 3]
let b = a
b.push(8)
console.log(a, b)
// [ 1, 2, 3, 8 ] [ 1, 2, 3, 8 ]

To really copy the array a to a new array b, there are at least 4 ways in JavaScript.

Use the slice() method

The slice() method is to extract a part of an array. Given that it returns the extracted part in a new array, we can just extract the whole array and get the returned one as the copy:

let a = [1, 2, 3]
let b = a.slice()
b.push(8)
console.log(a, b)
// [ 1, 2, 3 ] [ 1, 2, 3, 8 ]

Use spread operator

The spread operators are not only good at destructuring assignments, but also able to unpack items from arrays or objects:

let a = [1, 2, 3]
let b = [...a]
b.push(8)
console.log(a, b)
// [ 1, 2, 3 ] [ 1, 2, 3, 8 ]

Using the built-in Array.from() method

In fact, there is a dedicated designed method to do the copy — Array.from():

let a = [1, 2, 3]
let b = Array.from(a)
b.push(8)
console.log(a, b)
// [ 1, 2, 3 ] [ 1, 2, 3, 8 ]

Using concat() method

The concat() method is used to merge two or more arrays. Since this method returns a new array without changing the existing arrays, we can harness it for copying as well:

let a = [1, 2, 3]
let b = [].concat(a)
b.push(8)
console.log(a, b)
// [ 1, 2, 3 ] [ 1, 2, 3, 8 ]

For objects, the three dots will work perfectly as well:

let leader = {
    name:'Yang',
    age:'30'
}
let fake_leader = {...leader}
fake_leader['skill']='coding'
console.log(leader,fake_leader)
// { name: 'Yang', age: '30' } { name: 'Yang', age: '30', skill: 'coding' }

Another way is to use the built-in Object.assign() method:

let leader = {
    name:'Yang',
    age:'30'
}
let fake_leader = Object.assign({},leader)
fake_leader['skill']='coding'
console.log(leader,fake_leader)
// { name: 'Yang', age: '30' } { name: 'Yang', age: '30', skill: 'coding' }

This type of copy is actually called shallow copy, which means it’s only one level deep. It only copies the references of the elements, not the elements themselves. Therefore, if the elements are objects or arrays, the copied array will still reference the same objects or arrays.

For instance, if the array a contains an inner array (two-level deep), the shallow copy cannot really copy them, and editing the array b’s inner array will also change a’s:

let a = [1, [2, 2, 2], 3]
let b = [].concat(a)
b[1].push(8)
console.log(a, b)
// [ 1, [ 2, 2, 2, 8 ], 3 ] [ 1, [ 2, 2, 2, 8 ], 3 ]

4. Use JSON Tricks for Deep Copy

To implement deep copy, a popular trick is to use JSON.stringify() and JSON.parse() together.

The idea is to serialize the object (or array) into a JSON-formatted string and then parse it back into a new object. This process effectively and elegantly creates a deep copy of the original array or object:

let a = [1, [2, 2, 2], 3]
let b = JSON.parse(JSON.stringify(a))
b[1].push(8)
console.log(a, b)
// [ 1, [ 2, 2, 2 ], 3 ] [ 1, [ 2, 2, 2, 8 ], 3 ]

The JSON-based trick is useful in most simple cases. However, we need to know that to make this method effective, the object must be JSON serializable.

Let’s see a counterexample:

const obj = {
    func: function() {
        console.log("hello world!");
    }
}

const cp_obj=JSON.parse(JSON.stringify(obj))

console.log(cp_obj['func'])
// undefined

The value of the obj['func'] is a function. It cannot be copied through the JSON trick anymore.

In this case, we can harness a famous third-party JS library named lodash:

const _ = require('lodash');
const obj = {
    func: function() {
        console.log("hello world!");
    }
}

const cp_obj=_.cloneDeep(obj)

cp_obj['func']()
// hello world!

As demonstrated above, the cloneDeep method from lodash perfectly cloned the function inside the obj and it can be executed successfully on the new cp_obj.

5. Implement For Loops Skillfully

If you are still using the C/C++ style for loops in JavaScript, you definitely need to upgrade your skill.

Of course, the following code is correct, but it’s not “JavaScript” enough.

const arr = ['Y', 'a', 'n', 'g']
for (let i = 0; i < arr.length; i++) {
    console.log(arr[i])
}
// Y
// a
// n
// g

The idiomatic ways to write the above code in JavaScript are as follows:

Use the forEach() method

The forEach method is ideal for iterating the elements of an array:

const author = [ 'Y', 'a', 'n', 'g' ];
author.forEach((c)=>{console.log(c)})
// Y
// a
// n
// g

Use the map() function

If you read open-source JavaScript programs, you probably will meet the map() function. It’s one of the most popular methods in JavaScript:

const author = [ 'Y', 'a', 'n', 'g' ];
author.map((c)=>{console.log(c)})
// Y
// a
// n
// g

The behavior of the map() function is mostly similar with forEach(), but there is a significant difference:

The map() method returns a new array with the same length as the original array, where each element is the result of the function call on the corresponding element. The original array remains unchanged. The forEach() method doesn’t return anything.

The following code illustrates how to get a new array using the map() function:

const author = ['Y', 'a', 'n', 'g'];
const cute_author = author.map((c) => c + ':)')
console.log(cute_author)
// [ 'Y:)', 'a:)', 'n:)', 'g:)' ]
console.log(author)
// [ 'Y', 'a', 'n', 'g' ]

However, we cannot get the new array with the forEach() function:

const author = ['Y', 'a', 'n', 'g'];
const cute_author = author.forEach((c) => c + ':)')
console.log(cute_author)
// undefined
console.log(author)
// [ 'Y', 'a', 'n', 'g' ]

Use the for…of… structure

ES6 is a milestone for JavaScript. Many good features were introduced by this version. The “for…of…” method is one of them.

const author = [ 'Y', 'a', 'n', 'g' ];
for (let char of author){
    console.log(char);
}
// Y
// a
// n
// g

Use the for…in… structure

The “for…in…” syntax is also able to implement the same thing as we did. But we should be careful about the difference between “for…in…” and “for…of…”. The following code snippet explains it:

const author = [ 'Y', 'a', 'n', 'g' ];
for (let idx in author){
    console.log(author[idx]);
}
// Y
// a
// n
// g

6. The Fastest Way To Remove Duplicate Values of an Array

ES6 introduced a new data structure for JavaScrip — set. A set is a collection of items that are unique.

Thanks to the feature of sets, it makes removing duplicate values of an array much simpler.

const a = [1, 2, 1, 6, 6, 6, 9]
const unique_a = [...new Set(a)]
console.log(unique_a)
// [ 1, 2, 6, 9 ]

As the above program shows, we can leverage the usage of the spread operator and Set() method to get unique elements of an array conveniently.

7. Reverse a String in One Line of Code

To reverse a string in JavaScript, we don’t need to write a for loop.

There are 3 steps to do this operation:

  1. Split the string into an array
  2. Reverse the array
  3. Convert the array into a string

These 3 steps need to harness 3 different built-in methods as follows:

const author = "Yang Zhou";
const reversedAuthor = author.split("").reverse().join("");
console.log(reversedAuthor);
// uohZ gnaY

It’s a decent one-liner, but to be honest, the JS way to reverse a string is not as elegant as Python. Due to its beautiful slicing syntax, Python can do the same thing much neater:

author = 'Yang Zhou'
reversed_author = author[::-1]
print(reversed_author)
# uohZ gnaY

By the way, an easy way to check if a JavaScript string is a palindrome is by comparing the string to its reversed version:

const author = 'YangnaY'
const isPalindrome = author.split("").reverse().join("") === author
console.log(isPalindrome)
// true

8. Count Elements in an Array Quickly

How to count every element in a JavaScript array?

Using a for loop to go through the items one by one and count them in the process?

It’s a solution, but not an elegant solution at all. I would say lodash is a super useful JS library:

const _ = require('lodash');
const author = ['Y', 'a', 'a', 'a', 'n', 'n', 'g', 'g', 'g', 'g']
console.log(_.countBy(author))
// { Y: 1, a: 3, n: 2, g: 4 }

If you prefer to not use a third-party library, it’s not hard to implement a similar function by yourself:

const countBy = (arr) => {
    let count = {};
    arr.forEach((e) => {
        count[e] = (count[e] || 0) + 1;
    });
    return count;
}

const author = ['Y', 'a', 'a', 'a', 'n', 'n', 'g', 'g', 'g', 'g']
const charCount = countBy(author);
console.log(charCount);
// { Y: 1, a: 3, n: 2, g: 4 }

If you merely need to count one specific item, the filter() method is a good choice:

const author = ['Y', 'a', 'a', 'a', 'n', 'n', 'g', 'g', 'g', 'g']

// Filter all elements equal to 'a' and return the length (count)
const countOfa = author.filter(x => x === 'a').length
console.log(countOfa)
// 3

9. Simplify Your Code with Comma Operator

Commas are more powerful in JavaScript because of the syntax of comma operators.

The comma (,) operator evaluates each expression (from left to right) and returns the value of the last one. It will be super helpful to simplify your code if you can leverage its power skillfully.

For instance, the following program demonstrates the utilization of the comma operator to accomplish two distinct purposes with a single line of code:

let sum = 0;
const squares = [1, 2, 3, 4, 5].map((x) => (sum += x, x * x));
console.log(squares);
// [1, 4, 9, 16, 25]
console.log(sum);
// 15

Given that the comma operator always returns the result of the last expression, we can leverage this feature to avoid writing many return keywords.

For example, the get_author() function of the following code returns the arr after changing it:

const get_author = arr => {
    arr.push('g')
    return arr
}
console.log(get_author(['Y','a','n']))
// [ 'Y', 'a', 'n', 'g' ]

This is the best scenario to let the comma operator show off:

const get_author = arr => (arr.push('g'), arr)
console.log(get_author(['Y', 'a', 'n']))
// [ 'Y', 'a', 'n', 'g' ]

Thanks for reading ❤️. Which one is your favourite trick?

If you are new here, feel free to take a glimpse into my 10-year love-hate relationship with programming:

In Plain English

Thank you for being a part of our community! Before you go:

JavaScript
Programming
Technology
Software Development
Coding
Recommended from ReadMedium