<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Reza Lavarian</title>
    <description>The latest articles on DEV Community by Reza Lavarian (@lavary).</description>
    <link>https://dev.to/lavary</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F789111%2Fced64cbd-afe9-4f24-b694-1916f83722de.jpg</url>
      <title>DEV Community: Reza Lavarian</title>
      <link>https://dev.to/lavary</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/lavary"/>
    <language>en</language>
    <item>
      <title>JavaScript list (array) comprehension explained with examples</title>
      <dc:creator>Reza Lavarian</dc:creator>
      <pubDate>Sat, 13 May 2023 18:37:13 +0000</pubDate>
      <link>https://dev.to/lavary/javascript-list-array-comprehension-explained-with-examples-29jo</link>
      <guid>https://dev.to/lavary/javascript-list-array-comprehension-explained-with-examples-29jo</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;✋ &lt;strong&gt;Update:&lt;/strong&gt; This post was originally published on my blog &lt;a href="https://www.decodingweb.dev"&gt;decodingweb.dev&lt;/a&gt;, where you can read the &lt;a href="https://www.decodingweb.dev/javascript-list-comprehension"&gt;latest version&lt;/a&gt; for a 💯 user experience. &lt;em&gt;~reza&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://brilliant.org/wiki/list-comprehension"&gt;List comprehension&lt;/a&gt; is a programming technique to create a new list based on an existing list. This quick guide explores three approaches to JavaScript list comprehension (a.k.a array comprehension).&lt;/p&gt;

&lt;p&gt;Programmers use list or array comprehension for two reasons:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;To create a subset of a broad list (based on a set of conditions)&lt;/li&gt;
&lt;li&gt;To transform list items into new values and store them as a new list.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;List comprehension is usually available as a language construct in many programming languages like Python or Perl. However, JavaScript has its own way of array comprehension.&lt;/p&gt;

&lt;p&gt;For instance, if you have a list of email addresses and need to filter out Gmail accounts, here’s how you’d do it in Python:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;emails&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="c1"&gt;# ...
&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="n"&gt;gmail_accounts&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;email&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;emails&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;endswith&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;'gmail.com'&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In JavaScript, however, there's no list (in this case, an array) comprehension construct, but there are ways to do that, thanks to &lt;code&gt;Array.prototype.map()&lt;/code&gt;, &lt;code&gt;Array.prototype.filter()&lt;/code&gt;, and the spread operator (&lt;code&gt;...&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;Let's see how.&lt;/p&gt;

&lt;h2&gt;
  
  
  List (array) comprehension in JavaScript
&lt;/h2&gt;

&lt;p&gt;Based on your use cases, there are several approaches to list comprehension in JavaScript:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;u&gt;Using Array.prototype.map()&lt;/u&gt;&lt;/li&gt;
&lt;li&gt;&lt;u&gt;Using Array.prototype.filter()&lt;/u&gt;&lt;/li&gt;
&lt;li&gt;&lt;u&gt;Using the for...of statement&lt;/u&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  1. Using Array.prototype.map()
&lt;/h2&gt;

&lt;p&gt;If you want to transform every item in an array and return it as a new array, the &lt;code&gt;Array.prototype.map()&lt;/code&gt; method is what you need.&lt;/p&gt;

&lt;p&gt;Let's see some examples.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example #1:&lt;/strong&gt; Imagine we have a list of decimal values (e.g., prices) but only want the integer part (without the fraction part.)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;prices&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mf"&gt;12.5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;45.34&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;12.5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;9.5&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;pricesAsInt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;prices&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;price&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;Math&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;trunc&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;price&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;pricesAsInt&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;// output: (4) [12, 45, 12, 9]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, we called the &lt;code&gt;map()&lt;/code&gt; method with an arrow function, which returns an integer (by using &lt;code&gt;Math.trunc()&lt;/code&gt;)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example #2:&lt;/strong&gt; Sometimes you have an array of objects and want to create a list of &lt;code&gt;x&lt;/code&gt; from each object. Consider the following variable:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;persons&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
  &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;238&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;Alice&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
  &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;874&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;Bob&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
  &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;421&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;Charlie&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Imagine you want to generate an array of names from the above data structure. Here's how you'd do it with the &lt;code&gt;map()&lt;/code&gt; method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;names&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;persons&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;p&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;names&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;// output: (3) ['Alice', 'Bob', 'Charlie']&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, we pass the short arrow function &lt;code&gt;p =&amp;gt; p.name&lt;/code&gt; to the &lt;code&gt;map()&lt;/code&gt; method. The variable &lt;code&gt;p&lt;/code&gt; refers to an object on each iteration.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example #3:&lt;/strong&gt; Considering the &lt;code&gt;persons&lt;/code&gt; array, imagine you need to add a new entry (&lt;code&gt;active: true&lt;/code&gt;) to each object.&lt;/p&gt;

&lt;p&gt;Here's one way of doing it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;activePersons&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;persons&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;p&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;active&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;p&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you want an elegant single-line statement:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;activePersons&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;persons&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;p&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="nx"&gt;p&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;active&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt; &lt;span class="p"&gt;}))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since we're using an arrow function without the curly braces, we wrapped the return value in a pair of parentheses. Otherwise, it would be mistaken for a function boundary by the parser. We used the spread operator (&lt;code&gt;...p&lt;/code&gt;) to pack the existing entries alongside &lt;code&gt;active: true&lt;/code&gt; as the new object.&lt;/p&gt;

&lt;p&gt;As a rule of thumb, use the &lt;code&gt;map()&lt;/code&gt; method whenever you want to transform list items without filtering them.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Using Array.prototype.filter()
&lt;/h2&gt;

&lt;p&gt;If you want to create a subset of the original list. That's where the &lt;code&gt;Array.prototype.filter()&lt;/code&gt; method comes in handy.&lt;/p&gt;

&lt;p&gt;Let's see some examples.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example #1:&lt;/strong&gt; Imagine you have a list of emails but want to filter only Gmail accounts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;emailAddresses&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
&lt;span class="c1"&gt;// ...&lt;/span&gt;
&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;gmailAccounts&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;emailAddress&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;filter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;endsWidth&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;gmail.com&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The filter method accepts a callback function, which is run against every item in the array; If the callback function returns &lt;code&gt;true&lt;/code&gt;, the item will be included in the new subset array.&lt;/p&gt;

&lt;p&gt;In the above example, if the current item ends with &lt;code&gt;gmail.com&lt;/code&gt;, the callback returns &lt;code&gt;true&lt;/code&gt;, and the item is included in the final result.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example #2:&lt;/strong&gt; You can use the &lt;code&gt;filter()&lt;/code&gt; method in conjunction with &lt;code&gt;map()&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;For instance, after filtering the Gmail accounts, if you want to store them as objects in an array, you can do it like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;gmailAccounts&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;emailAddress&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;filter&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;endsWidth&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;gmail.com&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;i&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;email&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;i&lt;/span&gt; &lt;span class="p"&gt;}))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As simple as that.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Using the for...of statement
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;for...of&lt;/code&gt; statement allows you to iterate over a series of values from an iterable object (e.g., Array, String, TypedArray, Map, Set, NodeList, etc.). &lt;/p&gt;

&lt;p&gt;If you want to reimplement the Gmail accounts example with the &lt;code&gt;for...of&lt;/code&gt; statement, you could do it like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;emailAddresses&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;gmailAccounts&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;

&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;email&lt;/span&gt; &lt;span class="k"&gt;of&lt;/span&gt; &lt;span class="nx"&gt;emails&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;email&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;endsWith&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;gmail.com&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="nx"&gt;gmailAccounts&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;push&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;email&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, we iterate over the items and skip any email address not ending with &lt;code&gt;gmail.com&lt;/code&gt;. Otherwise, we push it to the &lt;code&gt;gmailAccounts&lt;/code&gt; array.&lt;/p&gt;

&lt;p&gt;You could also use the &lt;code&gt;Array.prototype.forEach()&lt;/code&gt; method to create a new list in the same way as the &lt;code&gt;for...of&lt;/code&gt; statement.&lt;/p&gt;

&lt;p&gt;Alright, I think it does it! I hope you found this quick guide helpful.&lt;/p&gt;

&lt;p&gt;Thanks for reading.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>How to fix “ValueError: I/O operation on closed file” in Python</title>
      <dc:creator>Reza Lavarian</dc:creator>
      <pubDate>Thu, 11 May 2023 16:28:11 +0000</pubDate>
      <link>https://dev.to/lavary/how-to-fix-valueerror-io-operation-on-closed-file-in-python-149p</link>
      <guid>https://dev.to/lavary/how-to-fix-valueerror-io-operation-on-closed-file-in-python-149p</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;✋ &lt;strong&gt;Update:&lt;/strong&gt; This post was originally published on my blog &lt;a href="https://www.decodingweb.dev"&gt;decodingweb.dev&lt;/a&gt;, where you can read the &lt;a href="https://www.decodingweb.dev/python-valueerror-io-operation-on-closed-file-fix"&gt;latest version&lt;/a&gt; for a 💯 user experience. &lt;em&gt;~reza&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The Python error “ValueError: I/O operation on closed file” happens when you try to do I/O operations (read, write, etc.) on a file that’s already been closed.&lt;/p&gt;

&lt;p&gt;Here’s what the error looks like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Traceback (most recent call last):
 File "/dwd/app.py", line 2, in 
  for line in file:
ValueError: I/O operation on closed file.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This quick guide explains why this error happens and how to fix it quickly.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to fix it?
&lt;/h2&gt;

&lt;p&gt;This error usually happens for two reasons:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;u&gt;Incorrect indentation&lt;/u&gt;&lt;/li&gt;
&lt;li&gt;&lt;u&gt;Closing the file prematurely&lt;/u&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Incorrect indentation
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://www.decodingweb.dev/python-taberror-inconsistent-use-of-tabs-and-spaces-in-indentation-fix"&gt;Incorrect indentation&lt;/a&gt; can cause the "ValueError: I/O operation on closed file" error when working with files in Python. Below are two scenarios leading to this error.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scenario #1: closing the file inside a loop:&lt;/strong&gt; Imagine you have a loop that reads data from a file.&lt;/p&gt;

&lt;p&gt;However, you unintentionally close the file at the same indentation level as the loop, making it part of the loop. &lt;/p&gt;

&lt;p&gt;As a result, when you try to read the second line of the file, you'll get the error because the file was closed in the first iteration.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nb"&gt;file&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;'data.txt'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;'r'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;line&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;file&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;line&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="c1"&gt;# file is closed here
&lt;/span&gt;    &lt;span class="nb"&gt;file&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;close&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, since &lt;code&gt;file.close()&lt;/code&gt; is indented within the loop (by mistake), the file is closed prematurely, causing the error.&lt;/p&gt;

&lt;p&gt;To fix this issue, move the &lt;code&gt;file.close()&lt;/code&gt; outside the loop, and you'll be good to go:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nb"&gt;file&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;'data.txt'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;'r'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;line&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;file&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;line&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;# Closing the file after the loop finishes
&lt;/span&gt;&lt;span class="nb"&gt;file&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;close&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Scenario #2: Using the &lt;code&gt;with&lt;/code&gt; statement:&lt;/strong&gt; As you probably know, when you open a file using the &lt;code&gt;with&lt;/code&gt; statement, you won't have to close the file at the end. Python automatically closes the file for you once the execution block finishes executing.&lt;/p&gt;

&lt;p&gt;That said, if you have an I/O operation outside the &lt;code&gt;with&lt;/code&gt; block, you'll run into the error since the file is closed. &lt;/p&gt;

&lt;p&gt;Imagine we're trying to read a CSV file using the &lt;code&gt;with open('...')&lt;/code&gt; syntax:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;csv&lt;/span&gt;

&lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;'users.csv'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;'r'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nb"&gt;file&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;csv_reader&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;csv&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;reader&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;file&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;row&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;csv_reader&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;row&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, we open a file using the &lt;code&gt;with&lt;/code&gt; statement, where we create a CSV reader object to iterate over lines and print each line.&lt;/p&gt;

&lt;p&gt;However, the &lt;code&gt;for&lt;/code&gt; loop is indented outside of the &lt;code&gt;with&lt;/code&gt; block, making it run after with statement closes the file.&lt;/p&gt;

&lt;p&gt;To fix this issue, ensure all I/O operations are part of the &lt;code&gt;with&lt;/code&gt; block:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;csv&lt;/span&gt;

&lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;'keywords.csv'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;r&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nb"&gt;file&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;csv_reader&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;csv&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;reader&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;file&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;line&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="n"&gt;csv_reader&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;line&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Closing the file prematurely
&lt;/h2&gt;

&lt;p&gt;Another common cause of this ValueError error is closing the file prematurely before performing any I/O operations. &lt;/p&gt;

&lt;p&gt;This might happen if you've copied a code from another source, like Stackoverflow or another file but forget to reorder the lines.&lt;/p&gt;

&lt;p&gt;Imagine you want to read data from a file and store it in a list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nb"&gt;file&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;'file.txt'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;'r'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;
&lt;span class="nb"&gt;file&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;close&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;line&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;file&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;line&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, &lt;code&gt;file.close()&lt;/code&gt; appears before we read the lines from the file.&lt;/p&gt;

&lt;p&gt;Placing &lt;code&gt;file.close()&lt;/code&gt; fixes the issue instantly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nb"&gt;file&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;'file.txt'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;'r'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;

&lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;line&lt;/span&gt; &lt;span class="ow"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;file&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;line&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="nb"&gt;file&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;close&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  You can also check if a file is closed
&lt;/h2&gt;

&lt;p&gt;To check whether a file is closed, you can use the &lt;code&gt;closed&lt;/code&gt; attribute of the respective file object. The closed attribute contains a boolean value indicating whether the file is open or closed. &lt;/p&gt;

&lt;p&gt;Here's an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="nb"&gt;file&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;open&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s"&gt;'example.txt'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;'r'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;file&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;closed&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# False
&lt;/span&gt;&lt;span class="nb"&gt;file&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;close&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;file&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;closed&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# True
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You might find this attribute helpful when debugging your code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Wrapping up
&lt;/h2&gt;

&lt;p&gt;The Python error "ValueError: I/O operation on closed file" typically occurs when a file is closed prematurely or due to incorrect indentation.&lt;/p&gt;

&lt;p&gt;It's a simple rule; Just ensure the code that closes the file is executed after the I/O operations.&lt;/p&gt;

&lt;p&gt;Alright, I think it does it! I hope you found this quick guide helpful.&lt;/p&gt;

&lt;p&gt;Thanks for reading.&lt;/p&gt;

</description>
      <category>python</category>
      <category>programming</category>
      <category>tutorial</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Four ways to check if a variable is a string in JavaScript (with examples)</title>
      <dc:creator>Reza Lavarian</dc:creator>
      <pubDate>Wed, 10 May 2023 16:48:32 +0000</pubDate>
      <link>https://dev.to/lavary/four-ways-to-check-if-a-variable-is-a-string-in-javascript-with-examples-3ilm</link>
      <guid>https://dev.to/lavary/four-ways-to-check-if-a-variable-is-a-string-in-javascript-with-examples-3ilm</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;✋ &lt;strong&gt;Update:&lt;/strong&gt; This post was originally published on my blog &lt;a href="https://www.decodingweb.dev"&gt;decodingweb.dev&lt;/a&gt;, where you can read the &lt;a href="https://www.decodingweb.dev/javascript-check-if-string"&gt;latest version&lt;/a&gt; for a 💯 user experience. &lt;em&gt;~reza&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;When working with strings in JavaScript, it’s important to check if a variable is a string before performing any string-related operations – specially when you get the value from an API . This quick guide explores four methods for checking if a variable is a string in JavaScript.&lt;/p&gt;

&lt;p&gt;JavaScript is a &lt;a href="https://www.decodingweb.dev/how-to-learn-a-programming-language#type-systems"&gt;dynamically typed&lt;/a&gt; language meaning the data type of a variable can change at runtime. That said, it’s essential to determine the data type of a variable before performing any operation on it, and string values are no exception.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to check if a variable is a string
&lt;/h2&gt;

&lt;p&gt;In this section, we’ll explore four common approaches to checking whether a value is a string in JavaScript:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;u&gt;Using typeof&lt;/u&gt;&lt;/li&gt;
&lt;li&gt;&lt;u&gt;Using Object.prototype.constructor.name&lt;/u&gt;&lt;/li&gt;
&lt;li&gt;&lt;u&gt;Using Object.prototype.toString.call(obj)&lt;/u&gt;&lt;/li&gt;
&lt;li&gt;&lt;u&gt;Using instanceof&lt;/u&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;1. Using typeof:&lt;/strong&gt; The &lt;code&gt;typeof&lt;/code&gt; operator is the go-to method when testing data types. It simply returns a string value representing the data type of its operand. For instance, &lt;code&gt;typeof "hello"&lt;/code&gt; returns &lt;code&gt;"string"&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;This is how you can use &lt;code&gt;typeof&lt;/code&gt; to test if a variable is a string:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;str&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;hello&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;typeof&lt;/span&gt; &lt;span class="nx"&gt;str&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;string&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;str is a string&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, the variable &lt;code&gt;str&lt;/code&gt; contains the string value &lt;code&gt;hello&lt;/code&gt;, and the value returned by &lt;code&gt;typeof&lt;/code&gt; confirms that.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;typeof&lt;/code&gt; operator only works with string literals, though. If your code, for some reason, contains string objects, you need to add more checks (more on this below).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Using Object.prototype.constructor.name:&lt;/strong&gt; Every JavaScript object has a constructor property that refers to the constructor function that created it (e.g., &lt;code&gt;str.constructor&lt;/code&gt;). &lt;/p&gt;

&lt;p&gt;This constructor has an attribute called &lt;code&gt;name&lt;/code&gt;, which returns the function name (as a string) that created the respective object. &lt;/p&gt;

&lt;p&gt;In the case of string values, the function name is &lt;code&gt;String&lt;/code&gt;. This work well with string literals as well as string objects:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;str&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;hello&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;str&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="kd"&gt;constructor&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;name&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;String&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;str is a string&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Using Object.prototype.toString.call(obj):&lt;/strong&gt;  This method can be considered a detailed version of &lt;code&gt;typeof&lt;/code&gt; because it returns the object type name when given an object.&lt;/p&gt;

&lt;p&gt;The returned value is usually in the form of &lt;code&gt;[object Type]&lt;/code&gt; where Type can be Array, String, Number, Function, etc.&lt;/p&gt;

&lt;p&gt;Let's try it out with a string:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;str&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;hello&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;Object&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;prototype&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;toString&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;call&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;str&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;[object String]&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;str is a string&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Just like &lt;code&gt;Object.prototype.constructor&lt;/code&gt;, you can use this approach for both string literals and objects.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Using instanceof:&lt;/strong&gt; This approach only works with string objects (e.g., &lt;code&gt;new String('test')&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;instanceof&lt;/code&gt; checks if its first operand is an instance of its second operand. Or more precisely, it checks if an object's &lt;em&gt;prototype chain&lt;/em&gt; includes the prototype property of a constructor.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;test&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="k"&gt;instanceof&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;// Output true&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Please note there is a difference between primitive strings (a.k.a string literals) and String objects.&lt;/p&gt;

&lt;p&gt;A string literal (wrapped in single/double quotation marks) is a primitive value. String values created via calling the &lt;code&gt;String&lt;/code&gt; function &lt;strong&gt;without&lt;/strong&gt; using the new keyword are primitive strings too.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;test&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;test&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;c&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;test&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;// Output: true&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="nx"&gt;c&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;// Output: false&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;b&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="nx"&gt;c&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;// Output: false&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That said, &lt;code&gt;instanceof&lt;/code&gt; doesn't work with string literals.&lt;/p&gt;

&lt;p&gt;Defining a string value by using the &lt;code&gt;String&lt;/code&gt; as a constructor (&lt;code&gt;new String('text')&lt;/code&gt;) is discouraged by many developers, as it's almost useless. You should rarely find yourself using String as a constructor.&lt;/p&gt;

&lt;p&gt;Then, why should I even consider this approach? You may ask.&lt;/p&gt;

&lt;p&gt;Well, there's one scenario you might want to use &lt;code&gt;instanceof&lt;/code&gt; to check strings in JavaScript, and that's when you need to create a universal utility function that works with all string types - no matter how they are defined:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;isString&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;value&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;typeof&lt;/span&gt; &lt;span class="nx"&gt;value&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;string&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="nx"&gt;value&lt;/span&gt; &lt;span class="k"&gt;instanceof&lt;/span&gt; &lt;span class="nb"&gt;String&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can use &lt;code&gt;constructor.name&lt;/code&gt;, or &lt;code&gt;toString.call(obj)&lt;/code&gt; to achieve the same result.&lt;/p&gt;

&lt;h2&gt;
  
  
  Wrapping up
&lt;/h2&gt;

&lt;p&gt;In this article, we have discussed four different approaches to checking if a variable is a string in JavaScript. The most common approach is to use &lt;code&gt;typeof&lt;/code&gt; to test if the value is string. And if your code contains both string literals and objects, you can use &lt;code&gt;typeof&lt;/code&gt; in conjunction with &lt;code&gt;instanceof&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Alternatively, you can use &lt;code&gt;constructor.name&lt;/code&gt;, or &lt;code&gt;toString.call(obj)&lt;/code&gt; to get the class constructor name that created the string value.&lt;/p&gt;

&lt;p&gt;Alright! I think it does it for today! I hope you found this quick guide helpful.&lt;/p&gt;

&lt;p&gt;Thanks for reading.&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>tutorial</category>
      <category>programming</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Python __new__() method explained with examples</title>
      <dc:creator>Reza Lavarian</dc:creator>
      <pubDate>Mon, 08 May 2023 17:24:43 +0000</pubDate>
      <link>https://dev.to/lavary/python-new-method-explained-with-examples-10i7</link>
      <guid>https://dev.to/lavary/python-new-method-explained-with-examples-10i7</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;✋ &lt;strong&gt;Update:&lt;/strong&gt; This post was originally published on my blog &lt;a href="https://www.decodingweb.dev"&gt;decodingweb.dev&lt;/a&gt;, where you can read the &lt;a href="https://www.decodingweb.dev/python-new-magic-method"&gt;latest version&lt;/a&gt; for a 💯 user experience. &lt;em&gt;~reza&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Python &lt;code&gt;__new__()&lt;/code&gt; method is static method (a.k.a magic or dunder method) that gives the programmer more control over how a specific class (cls) is instantiated.&lt;/p&gt;

&lt;p&gt;This quick guide explains the &lt;code&gt;__new__()&lt;/code&gt; method and how and when to use it.&lt;/p&gt;

&lt;h2&gt;
  
  
  How does the Python &lt;code&gt;__new__()&lt;/code&gt; method work?
&lt;/h2&gt;

&lt;p&gt;Python calls the &lt;code&gt;__new__()&lt;/code&gt; method every time you instantiate a class. It does the instantiation in two steps:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;First:&lt;/strong&gt; it invokes the &lt;code&gt;__new__()&lt;/code&gt; method of the class to create and return an instance (this instance is then passed to &lt;code&gt;__init__()&lt;/code&gt; as its first argument &lt;code&gt;self&lt;/code&gt;)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Next:&lt;/strong&gt; the &lt;code&gt;__init__()&lt;/code&gt; method is invoked to initialize the object state. Please note the &lt;code&gt;__init__()&lt;/code&gt; method can’t return anything (except for &lt;code&gt;None&lt;/code&gt;).&lt;/p&gt;

&lt;h2&gt;
  
  
  When to use the Python &lt;code&gt;__new__()&lt;/code&gt; method?
&lt;/h2&gt;

&lt;p&gt;Well, most of the time, you don’t need to! &lt;/p&gt;

&lt;p&gt;Python does it all for you. However, you might want to override this dunder method if you need more control over the instantiation process.&lt;/p&gt;

&lt;p&gt;Below are three [not-so-common] use cases of the &lt;code&gt;__new__()&lt;/code&gt; magic method:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;u&gt;Subclassing built-in types&lt;/u&gt;&lt;/li&gt;
&lt;li&gt;&lt;u&gt;Custom initialization logic&lt;/u&gt;&lt;/li&gt;
&lt;li&gt;&lt;u&gt;Singleton classes&lt;/u&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;1. Subclassing built-in types:&lt;/strong&gt; We create a subclass to create a new class based on a base class, which overrides some of its parent’s data/behavior.&lt;/p&gt;

&lt;p&gt;In Python, you can subclass immutable built-in types (e.g., &lt;code&gt;int&lt;/code&gt;, &lt;code&gt;float&lt;/code&gt;, and &lt;code&gt;str&lt;/code&gt;) to add custom behavior to a built-in data type.&lt;/p&gt;

&lt;p&gt;For instance, the &lt;code&gt;bool&lt;/code&gt; type is a subclass of the immutable &lt;code&gt;int&lt;/code&gt;.  In fact, &lt;code&gt;True&lt;/code&gt; and &lt;code&gt;False&lt;/code&gt; are integer numbers &lt;code&gt;1&lt;/code&gt; (for True) and &lt;code&gt;0&lt;/code&gt; (for False).&lt;/p&gt;

&lt;p&gt;Since the base class is &lt;code&gt;int&lt;/code&gt;, we can even do mathematical operations on boolean values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;gt;&amp;gt;&amp;gt; a = True
&amp;gt;&amp;gt;&amp;gt; b = False
&amp;gt;&amp;gt;&amp;gt; a + b
1
&amp;gt;&amp;gt;&amp;gt; a = True
&amp;gt;&amp;gt;&amp;gt; b = True
&amp;gt;&amp;gt;&amp;gt; a + b
2
&amp;gt;&amp;gt;&amp;gt; bool.__bases__
(,)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can also create our own subclass of int (or any other data type) thanks to the &lt;code&gt;__new__()&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;Imagine you need a data type that stores integers as positive numbers regardless of the given value (1, 3, -45, -50). At the same time, you want to have access to all the functionalities the built-in int type offers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PositiveInt&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__new__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cls&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;__new__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cls&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;abs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, our subclass &lt;code&gt;PositiveInt&lt;/code&gt; extends the standard &lt;code&gt;int&lt;/code&gt; class, but it implements its own &lt;code&gt;__new__()&lt;/code&gt; method to transform the given value into a positive number.&lt;/p&gt;

&lt;p&gt;Inside the &lt;code&gt;__new__()&lt;/code&gt; method, we call the &lt;code&gt;__new__()&lt;/code&gt; of the parent (&lt;code&gt;int&lt;/code&gt;) and pass it the absolute value (&lt;code&gt;abs(value)&lt;/code&gt;) of the given number.&lt;/p&gt;

&lt;p&gt;Let's try it out:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;PositiveInt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;34&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# output: 34
&lt;/span&gt;
&lt;span class="n"&gt;c&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;PositiveInt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;784&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# output: 784
&lt;/span&gt;
&lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;c&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# output: 818
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Done!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Custom initialization logic:&lt;/strong&gt; You can use the &lt;code&gt;__new__()&lt;/code&gt; method to create customized instantiation logic.&lt;/p&gt;

&lt;p&gt;Imagine, you need to limit the number of instances created for a specific class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Players&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;object&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
    &lt;span class="n"&gt;currentInstances&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
    &lt;span class="n"&gt;maxInstances&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;

   &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__new__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cls&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;cls&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;currentInstances&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="n"&gt;cls&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;maxInstances&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="nb"&gt;ValueError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sa"&gt;f&lt;/span&gt;&lt;span class="s"&gt;'You can only make &lt;/span&gt;&lt;span class="si"&gt;{&lt;/span&gt;&lt;span class="n"&gt;maxInstances&lt;/span&gt;&lt;span class="si"&gt;}&lt;/span&gt;&lt;span class="s"&gt; instances.'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="n"&gt;cls&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;currentInstances&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;super&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="n"&gt;__new__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cls&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="bp"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above class &lt;code&gt;Player&lt;/code&gt;, we have a variable named &lt;code&gt;currentInstances&lt;/code&gt; to store the current number of instances created.&lt;/p&gt;

&lt;p&gt;In the &lt;code&gt;__new__()&lt;/code&gt; method, we ensure &lt;code&gt;currentInstances&lt;/code&gt; never exceeds &lt;code&gt;maxInstances&lt;/code&gt;. If it does so, we throw an exception. And if not, we instantiate the class by calling the parent object &lt;code&gt;__new__()&lt;/code&gt; method and return the result.&lt;/p&gt;

&lt;p&gt;Finally, we increment &lt;code&gt;currentInstances&lt;/code&gt; by &lt;code&gt;1&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If we try to instantiate the &lt;code&gt;Player&lt;/code&gt; class 5 times, we'll get an exception on the fifth try.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ValueError: You can only make 4 instances
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Creating singleton classes:&lt;/strong&gt; Another [controversial] use case for the &lt;code&gt;__new__()&lt;/code&gt; method is to create Python singleton objects. &lt;/p&gt;

&lt;p&gt;Singleton classes should have only one instance. &lt;/p&gt;

&lt;p&gt;Technically, you can use the &lt;code&gt;__new__()&lt;/code&gt; method to ensure only one instance of a specific class is created and returns the existing instance to all subsequent constructor calls.&lt;/p&gt;

&lt;p&gt;Here's how we'd do it by using the &lt;code&gt;__new__()&lt;/code&gt; method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Singleton&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;_instance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="bp"&gt;None&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__new__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cls&lt;/span&gt;&lt;span class="p"&gt;):&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;cls&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_instance&lt;/span&gt; &lt;span class="ow"&gt;is&lt;/span&gt; &lt;span class="bp"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;cls&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_instance&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;super&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="n"&gt;__new__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cls&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;cls&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_instance&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, we define a class named Singleton with the attribute &lt;code&gt;_instance&lt;/code&gt;, initially set to &lt;code&gt;None&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;When you instantiate the class, the &lt;code&gt;__new__()&lt;/code&gt; method is invoked, checking whether the &lt;code&gt;_instance&lt;/code&gt; attribute is &lt;code&gt;None&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;If it is, it creates a new instance using the &lt;code&gt;super().__new__(cls)&lt;/code&gt; and assigns it to the &lt;code&gt;_instance&lt;/code&gt; attribute. If the _instance attribute already refers to an existing object, it returns it.&lt;/p&gt;

&lt;p&gt;This ensures that only one instance of our class can exist at any given time.&lt;/p&gt;

&lt;p&gt;While this works fine, it isn't the most Pythonic way of reusing objects. In fact, it's almost useless in Python!&lt;/p&gt;

&lt;p&gt;A more Pythonic approach would be to use The &lt;strong&gt;Global Object Pattern&lt;/strong&gt;. In Python, when you only need a single instance of a class, you probably don't need a class definition at all. You can place your data/functionality at a module level instead; Modules have their own namespaces and are singleton by design.&lt;/p&gt;

&lt;p&gt;On the other hand, every time you refer to a module, Python returns the same module object. This is why we make singleton classes. Something that Python provides out of the box.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Sometimes it's acceptable, though!&lt;/strong&gt; The one situation using the Singleton pattern sounds reasonable is when you're working with legacy code. &lt;/p&gt;

&lt;p&gt;Let's say, due to new requirements, you need to use a specific class as a single object across the code base. However, it’s not an option to update all the legacy code to use the global object approach.&lt;/p&gt;

&lt;p&gt;In that case, making the class singleton might be helpful to implement the requirement while keeping the old syntax.&lt;/p&gt;

&lt;p&gt;I haven't personally encountered any of the above use cases, but you might!&lt;/p&gt;

&lt;h2&gt;
  
  
  Wrapping up
&lt;/h2&gt;

&lt;p&gt;In conclusion, the &lt;code&gt;__new__()&lt;/code&gt; magic method provides lots of flexibility for controlling how a class is instantiated.&lt;/p&gt;

&lt;p&gt;With the help of the &lt;code&gt;__new__()&lt;/code&gt; method, you can subclass built-on types, create singleton objects, and create classes with customized instantiation/ initialization logic. &lt;/p&gt;

&lt;p&gt;I hope you found this quick guide helpful. Thanks for reading!&lt;/p&gt;

</description>
      <category>python</category>
      <category>programming</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Label htmlFor Property Explained</title>
      <dc:creator>Reza Lavarian</dc:creator>
      <pubDate>Mon, 06 Feb 2023 20:15:44 +0000</pubDate>
      <link>https://dev.to/lavary/label-htmlfor-property-explained-1pjd</link>
      <guid>https://dev.to/lavary/label-htmlfor-property-explained-1pjd</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;✋ &lt;strong&gt;Update:&lt;/strong&gt; This post was originally published on my blog &lt;a href="https://www.decodingweb.dev"&gt;decodingweb.dev&lt;/a&gt;, where you can read the &lt;a href="https://www.decodingweb.dev/label-htmlfor-property-explained"&gt;latest version&lt;/a&gt; for a 💯 user experience. &lt;em&gt;~reza&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We use the HTML &lt;code&gt;&amp;lt;label&amp;gt;&lt;/code&gt; element to caption form elements, such as a text box, checkbox, radio button, etc.&lt;/p&gt;

&lt;p&gt;To do so, all you need to do is to set the label’s for attribute with the ID string of its corresponding form element – this means your form element should already have an ID attribute.&lt;/p&gt;

&lt;p&gt;Something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight html"&gt;&lt;code&gt;&lt;span class="nt"&gt;&amp;lt;label&lt;/span&gt; &lt;span class="na"&gt;for=&lt;/span&gt;&lt;span class="s"&gt;"usernameId"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;Username: &lt;span class="nt"&gt;&amp;lt;label&amp;gt;&lt;/span&gt;
&lt;span class="nt"&gt;&amp;lt;input&lt;/span&gt; &lt;span class="na"&gt;type=&lt;/span&gt;&lt;span class="s"&gt;"text"&lt;/span&gt; &lt;span class="na"&gt;name=&lt;/span&gt;&lt;span class="s"&gt;"username"&lt;/span&gt; &lt;span class="na"&gt;id=&lt;/span&gt;&lt;span class="s"&gt;"usernameId"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Labelling form elements have multiple accessibility advantages:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;📢 Assistive technologies:&lt;/strong&gt; It makes the label and the form element programmatically related. For instance, a screen reader would read out the form element's label to visually-impaired users.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;📲 Accessibility and UX:&lt;/strong&gt; It also increases the &lt;em&gt;hit area&lt;/em&gt; when interacting with a form element (click or touch); For instance, when you click the label of a text box, it'll gain focus, so you can start typing. Or if it's a checkbox (or a radio button), it'll be checked - a pleasant experience on small-screen devices.&lt;/p&gt;

&lt;p&gt;Here's an example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight html"&gt;&lt;code&gt;&lt;span class="nt"&gt;&amp;lt;section&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;label&lt;/span&gt; &lt;span class="na"&gt;for=&lt;/span&gt;&lt;span class="s"&gt;"usernameControl"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;Username: &lt;span class="nt"&gt;&amp;lt;/label&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;input&lt;/span&gt; &lt;span class="na"&gt;type=&lt;/span&gt;&lt;span class="s"&gt;"text"&lt;/span&gt; &lt;span class="na"&gt;name=&lt;/span&gt;&lt;span class="s"&gt;"username"&lt;/span&gt; &lt;span class="na"&gt;id=&lt;/span&gt;&lt;span class="s"&gt;"usernameControl"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="nt"&gt;&amp;lt;/section&amp;gt;&lt;/span&gt;

&lt;span class="nt"&gt;&amp;lt;section&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;input&lt;/span&gt; &lt;span class="na"&gt;type=&lt;/span&gt;&lt;span class="s"&gt;"checkbox"&lt;/span&gt; &lt;span class="na"&gt;id=&lt;/span&gt;&lt;span class="s"&gt;"checkControl"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;label&lt;/span&gt; &lt;span class="na"&gt;for=&lt;/span&gt;&lt;span class="s"&gt;"checkControl"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;Click me&lt;span class="nt"&gt;&amp;lt;/label&amp;gt;&lt;/span&gt;
&lt;span class="nt"&gt;&amp;lt;/section&amp;gt;&lt;/span&gt;

&lt;span class="nt"&gt;&amp;lt;section&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;input&lt;/span&gt; &lt;span class="na"&gt;type=&lt;/span&gt;&lt;span class="s"&gt;"radio"&lt;/span&gt; &lt;span class="na"&gt;name=&lt;/span&gt;&lt;span class="s"&gt;"radioControl"&lt;/span&gt; &lt;span class="na"&gt;id=&lt;/span&gt;&lt;span class="s"&gt;"radioControl1"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;label&lt;/span&gt; &lt;span class="na"&gt;for=&lt;/span&gt;&lt;span class="s"&gt;"radioControl1"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;Option 1&lt;span class="nt"&gt;&amp;lt;/label&amp;gt;&lt;/span&gt;

    &lt;span class="nt"&gt;&amp;lt;input&lt;/span&gt; &lt;span class="na"&gt;type=&lt;/span&gt;&lt;span class="s"&gt;"radio"&lt;/span&gt; &lt;span class="na"&gt;name=&lt;/span&gt;&lt;span class="s"&gt;"radioControl"&lt;/span&gt; &lt;span class="na"&gt;id=&lt;/span&gt;&lt;span class="s"&gt;"radioControl2"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;label&lt;/span&gt; &lt;span class="na"&gt;for=&lt;/span&gt;&lt;span class="s"&gt;"radioControl2"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;Option 2&lt;span class="nt"&gt;&amp;lt;/label&amp;gt;&lt;/span&gt;

    &lt;span class="nt"&gt;&amp;lt;input&lt;/span&gt; &lt;span class="na"&gt;type=&lt;/span&gt;&lt;span class="s"&gt;"radio"&lt;/span&gt; &lt;span class="na"&gt;name=&lt;/span&gt;&lt;span class="s"&gt;"radioControl"&lt;/span&gt; &lt;span class="na"&gt;id=&lt;/span&gt;&lt;span class="s"&gt;"radioControl3"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="nt"&gt;&amp;lt;label&lt;/span&gt; &lt;span class="na"&gt;for=&lt;/span&gt;&lt;span class="s"&gt;"radioControl3"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;Option 3&lt;span class="nt"&gt;&amp;lt;/label&amp;gt;&lt;/span&gt;
&lt;span class="nt"&gt;&amp;lt;/section&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But sometimes you might need to manage (set or get) a label's &lt;code&gt;for&lt;/code&gt; property dynamically, from your JavaScript code.&lt;/p&gt;

&lt;p&gt;In this quick guide, I'll explain how you can programmatically manage the for attribute with the help of the Label &lt;code&gt;htmlFor&lt;/code&gt; property via JavaScript.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to use the Label htmlFor property
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;HTMLLabelElement.htmlFor&lt;/code&gt; lets you read the &lt;code&gt;for&lt;/code&gt; attribute's current value. It also allows you to set its value on the fly.&lt;/p&gt;

&lt;p&gt;Let's start with a quick example for those friends who need a short snippet for today. Then, we'll get to the details.&lt;/p&gt;

&lt;p&gt;Let's imagine we have the following form control:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight html"&gt;&lt;code&gt;&lt;span class="nt"&gt;&amp;lt;label&lt;/span&gt; &lt;span class="na"&gt;for=&lt;/span&gt;&lt;span class="s"&gt;"usernameId"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;Username: &lt;span class="nt"&gt;&amp;lt;label&amp;gt;&lt;/span&gt;
&lt;span class="nt"&gt;&amp;lt;input&lt;/span&gt; &lt;span class="na"&gt;type=&lt;/span&gt;&lt;span class="s"&gt;"text"&lt;/span&gt; &lt;span class="na"&gt;name=&lt;/span&gt;&lt;span class="s"&gt;"username"&lt;/span&gt; &lt;span class="na"&gt;id=&lt;/span&gt;&lt;span class="s"&gt;"usernameId"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To read the value of the &lt;code&gt;for&lt;/code&gt; attribute, you can access its &lt;code&gt;htmlFor&lt;/code&gt; property in the DOM like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Get the DOM element by Id&lt;/span&gt;
&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;label&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;querySelector&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;#usernameLabel&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;// Access the htmlFor property&lt;/span&gt;
&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;forValue&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;label&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;htmlFor&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And if you need to set the &lt;code&gt;for&lt;/code&gt; value programmatically at runtime:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Get the DOM element by Id&lt;/span&gt;
&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;labelElement&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;querySelector&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;#usernameLabel&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;// Set the for attribute value via htmlFor property&lt;/span&gt;
&lt;span class="nx"&gt;labelElement&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;htmlFor&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;someValue&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, &lt;code&gt;someValue&lt;/code&gt; is the ID string of the form control to which the label is associated.&lt;/p&gt;

&lt;p&gt;Please note when a label is implicitly associated with a form control - by placing the form element within the label tag - this property would return an empty value:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight html"&gt;&lt;code&gt;&lt;span class="nt"&gt;&amp;lt;label&amp;gt;&lt;/span&gt;
    Username: 
    &lt;span class="nt"&gt;&amp;lt;input&lt;/span&gt; &lt;span class="na"&gt;type=&lt;/span&gt;&lt;span class="s"&gt;"text"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="nt"&gt;&amp;lt;/label&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Can't we just use &lt;code&gt;setAttribute&lt;/code&gt;/&lt;code&gt;getAttribute&lt;/code&gt;?
&lt;/h2&gt;

&lt;p&gt;Since the &lt;code&gt;htmlFor&lt;/code&gt; property reflects the value of the for attribute, technically, it's possible to use &lt;code&gt;setAttribute()&lt;/code&gt; to set the for attribute of a label.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;labelElement&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;querySelector&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;#usernameLabel&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;forValue&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;labelElement&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;setAttribute&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;for&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;someValue&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, Mozilla recommends using &lt;code&gt;htmlFor&lt;/code&gt; whenever you need to set the &lt;code&gt;for&lt;/code&gt; attribute programmatically.&lt;/p&gt;

&lt;p&gt;Label htmlFor property is well-supported across most web &lt;/p&gt;

&lt;h2&gt;
  
  
  Wrapping up
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;for&lt;/code&gt; attribute helps you add interactive behavior to a web page without writing a single line of JavaScript. For instance, to create custom checkbox/radio button elements or even trigger a popup or a sliding menu. However, if you need more control over your labels from javaScript code, label's &lt;code&gt;htmlFor&lt;/code&gt; is the property you'll need.&lt;/p&gt;

&lt;p&gt;I hope this quick guide can provide an answer to your question.&lt;/p&gt;

&lt;p&gt;Thanks for reading.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
    <item>
      <title>About “ReferenceError: document is not defined” in JavaScript</title>
      <dc:creator>Reza Lavarian</dc:creator>
      <pubDate>Mon, 06 Feb 2023 20:06:08 +0000</pubDate>
      <link>https://dev.to/lavary/about-referenceerror-document-is-not-defined-in-javascript-1h3g</link>
      <guid>https://dev.to/lavary/about-referenceerror-document-is-not-defined-in-javascript-1h3g</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;✋ &lt;strong&gt;Update:&lt;/strong&gt; This post was originally published on my blog &lt;a href="https://www.decodingweb.dev"&gt;decodingweb.dev&lt;/a&gt;, where you can read the &lt;a href="https://www.decodingweb.dev/how-to-solve-referenceerror-document-is-not-defined"&gt;latest version&lt;/a&gt; for a 💯 user experience. &lt;em&gt;~reza&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This guide explains why ReferenceError: document is not defined occurs and how you can fix it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let element = document.querySelector('#usernameLabel')
              ^
ReferenceError: document is not defined
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The most common reason for "document is not defined" error is that your JavaScript code is trying to access the &lt;code&gt;document&lt;/code&gt; object in a non-browser environment, such as Node.js.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A quick intro to the document object:&lt;/strong&gt;&lt;br&gt;
Whenever you access a web page via the web browser, the browser's renderer fetches and parses the HTML code (along with the assets) and stores its elements (headings, paragraphs, images, form elements, etc.) into an internal data structure called &lt;strong&gt;DOM&lt;/strong&gt; (Document Object Model). &lt;/p&gt;

&lt;p&gt;DOM is then turned into &lt;strong&gt;&lt;em&gt;Render Tree&lt;/em&gt;&lt;/strong&gt; (consisting of visible elements and their styles), and through a complicated process, the code is turned into pixels - what you see as a user. &lt;/p&gt;

&lt;p&gt;Additionally, the web browser exposes an interface to the DOM tree called &lt;strong&gt;DOM API&lt;/strong&gt;. The DOM API lets you modify the page programmatically via JavaScript to do things like:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Set the page title on the fly&lt;/li&gt;
&lt;li&gt;Add/remove HTML element(s)&lt;/li&gt;
&lt;li&gt;Manage CSS styles&lt;/li&gt;
&lt;li&gt;Add/remove CSS classes&lt;/li&gt;
&lt;li&gt;and a lot more!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;And the entry point to this powerful API is the &lt;code&gt;document&lt;/code&gt; object. &lt;/p&gt;
&lt;h2&gt;
  
  
  What causes ReferenceError: document is not defined
&lt;/h2&gt;

&lt;p&gt;The first thing to know is that the DOM API is a &lt;a href="https://www.decodingweb.dev/front-end-skills-to-get-you-started#web-apis"&gt;web browser component&lt;/a&gt; and not a part of JavaScript. JavaScript only enables you access this object (like any other object).&lt;/p&gt;

&lt;p&gt;Here are the possible scenarios that "ReferenceError: document is not defined" error might happen:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;u&gt;A reference to the &lt;code&gt;document&lt;/code&gt; object in Node.js&lt;/u&gt;&lt;/li&gt;
&lt;li&gt;&lt;u&gt;Server-side Rendering (SSR)&lt;/u&gt;&lt;/li&gt;
&lt;li&gt;&lt;u&gt;Casing might be off.&lt;/u&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let's see how we can fix them.&lt;/p&gt;
&lt;h2&gt;
  
  
  How to fix "document is not defined" error
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;In Node.js:&lt;/strong&gt; As mentioned earlier, the document object is a browser feature and not a part of JavaScript. On the other hand, when there's no browser, there's no document object.&lt;/p&gt;

&lt;p&gt;With Node.js, you must review the code and figure out why you're accessing a browser object in a server-side code in the first place? Maybe it's just there because you borrowed the code from another file?&lt;/p&gt;

&lt;p&gt;However, if your code is used by both the front end and the server, you can place the reference to the &lt;code&gt;document&lt;/code&gt; inside a conditional statement - to ensure it'll only run by the browser's &lt;a href="https://www.decodingweb.dev/front-end-skills-to-get-you-started#javascript-engines"&gt;JavaScript engine&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;To do this, you can place it inside a conditional statement and check for the availability of the &lt;code&gt;document&lt;/code&gt; object:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// This code only runs on the browser&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;typeof&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt; &lt;span class="o"&gt;!==&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;undefined&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
   &lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;element&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;querySelector&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;.class-name&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

   &lt;span class="c1"&gt;// Manipulating the DOM here&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Serverside-rendering (SSR):&lt;/strong&gt; The "document is not defined" error might also occur when using static site generators, such as Nuxt.js, Next.js, or Gatsby.&lt;/p&gt;

&lt;p&gt;A quick fix - as suggested above - is to place any reference to the document object inside a conditional statement - to exclude it from the server-side rendering.&lt;/p&gt;

&lt;p&gt;If you use Next.js, you can place your DOM-related code inside a &lt;code&gt;useEffect&lt;/code&gt; hook. The callback passed to &lt;code&gt;useEffect&lt;/code&gt; runs after the component is mounted (and painted).&lt;/p&gt;

&lt;p&gt;The example below is from React's documentation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// useeffect-example&lt;/span&gt;

&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;React&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;useEffect&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;react&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;Example&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;count&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;setCount&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;useState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

  &lt;span class="c1"&gt;// Similar to componentDidMount and componentDidUpdate:&lt;/span&gt;
  &lt;span class="nx"&gt;useEffect&lt;/span&gt;&lt;span class="p"&gt;(()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// Update the document title using the browser API&lt;/span&gt;
    &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;title&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;You clicked &lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nx"&gt;count&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt; times&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;});&lt;/span&gt;

  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;p&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="nx"&gt;You&lt;/span&gt; &lt;span class="nx"&gt;clicked&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="nx"&gt;count&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="nx"&gt;times&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/p&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;      &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;button&lt;/span&gt; &lt;span class="nx"&gt;onClick&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;setCount&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;count&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)}&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="nx"&gt;Click&lt;/span&gt; &lt;span class="nx"&gt;me&lt;/span&gt;
      &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/button&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;    &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/div&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;  &lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;How about Nuxt.js?&lt;/strong&gt; If you're using Nuxt.js with Vue, and the error is raised in one of your components, you can wrap your component inside a &lt;code&gt;&amp;lt;client-only&amp;gt;&lt;/code&gt; component, and the error will go away. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;&amp;lt;client-only&amp;gt;&lt;/code&gt; guarantees that your component is only rendered on the client side.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// nuxtjs-client-only.js&lt;/span&gt;

&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;template&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;div&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;client&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="nx"&gt;only&lt;/span&gt; &lt;span class="nx"&gt;placeholder&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt; loading...&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nx"&gt;your&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="nx"&gt;component&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/client-only&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;  &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/div&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="sr"&gt;/template&lt;/span&gt;&lt;span class="err"&gt;&amp;gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Additionally, you can access DOM from within the &lt;code&gt;mounted&lt;/code&gt; Vue lifecycle hook.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Or maybe it's just a typo?&lt;/strong&gt; It's also worth checking the &lt;code&gt;document&lt;/code&gt; object is all lowercase and not capitalized!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// document-reference-case.js&lt;/span&gt;

&lt;span class="c1"&gt;// ⛔ Wrong&lt;/span&gt;
&lt;span class="nx"&gt;Document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;querySelector&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;.class-name&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;// ✅ Correct&lt;/span&gt;
&lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;querySelector&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;.class-name&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Wrapping up
&lt;/h2&gt;

&lt;p&gt;In this quick guide, you learned the &lt;code&gt;document&lt;/code&gt; object is a browser feature and should always be used in a browser environment.&lt;/p&gt;

&lt;p&gt;The most common reason for this error is that the code tries to access the &lt;code&gt;document&lt;/code&gt; object in a non-browser environment, such as Node.js.&lt;/p&gt;

&lt;p&gt;Two common way to avoid such errors is to use a conditional statement to ensure the code only runs in the browser.&lt;/p&gt;

&lt;p&gt;Alternatively, you can use hook mechanisms in case you're using an SSR framework such as Next or Nuxt.js.&lt;/p&gt;

&lt;p&gt;I hope this guide provided the answer you were looking for.&lt;/p&gt;

&lt;p&gt;Thanks for reading!&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;❤️ You might like:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.decodingweb.dev/fix-map-is-not-a-function-error-in-javascript"&gt;TypeError: map is not a function in JavaScript (Fixed)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.decodingweb.dev/add-commas-to-numbers-in-javascript"&gt;Add commas to numbers in JavaScript (Explained with examples)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.decodingweb.dev/syntaxerror-unexpected-end-of-json-input-in-javascript"&gt;SyntaxError: Unexpected end of JSON input in JavaScript (Fixed)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
    <item>
      <title>About "SyntaxError: Unexpected end of JSON input" in JavaScript</title>
      <dc:creator>Reza Lavarian</dc:creator>
      <pubDate>Mon, 06 Feb 2023 19:56:33 +0000</pubDate>
      <link>https://dev.to/lavary/about-syntaxerror-unexpected-end-of-json-input-in-javascript-22aj</link>
      <guid>https://dev.to/lavary/about-syntaxerror-unexpected-end-of-json-input-in-javascript-22aj</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;✋ &lt;strong&gt;Update:&lt;/strong&gt; This post was originally published on my blog &lt;a href="https://www.decodingweb.dev" rel="noopener noreferrer"&gt;decodingweb.dev&lt;/a&gt;, where you can read the &lt;a href="https://www.decodingweb.dev/syntaxerror-unexpected-end-of-json-input-in-javascript" rel="noopener noreferrer"&gt;latest version&lt;/a&gt; for a 💯 user experience. &lt;em&gt;~reza&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;You might have encountered the error “Uncaught SyntaxError: Unexpected end of JSON input” when using &lt;code&gt;JSON.parse()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The error looks like this on the browser console (Google Chrome):&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsjm7mkb4y4uwxooy7eby.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsjm7mkb4y4uwxooy7eby.jpg" alt="Image description" width="800" height="281"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;First of all, it’s not your code! What’s most likely wrong is the &lt;a href="https://www.decodingweb.dev/front-end-skills-to-get-you-started#data-interchange-formats" rel="noopener noreferrer"&gt;JSON string&lt;/a&gt; you’re trying to parse.&lt;/p&gt;

&lt;p&gt;When “Unexpected end of JSON input” is raised, your code is probably parsing:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;u&gt;An empty string&lt;/u&gt;&lt;/li&gt;
&lt;li&gt;&lt;u&gt;An empty array&lt;/u&gt;&lt;/li&gt;
&lt;li&gt;&lt;u&gt;Or an incomplete (a.k.a malformed) JSON data&lt;/u&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;That said, the first thing to examine is the JSON data.&lt;/p&gt;

&lt;p&gt;If you’re using Google Chrome (like me), you can click the link on the right-hand side of the error message. &lt;/p&gt;

&lt;p&gt;It’s usually in the form of &lt;strong&gt;&lt;code&gt;VM: Script ID&lt;/code&gt;&lt;/strong&gt;, e.g., &lt;code&gt;VM:1&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;If the log is empty, you’re probably dealing with an empty string! Otherwise, you’ll see the JSON data with an indicator.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to fix the Uncaught SyntaxError: Unexpected end of JSON input
&lt;/h2&gt;

&lt;p&gt;When working with JSON-formatted data in JavaScript, we’re either working with locally defined JSON data or fetching it from an API.&lt;/p&gt;

&lt;p&gt;But how can we resolve the issue?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When working with locally defined JSON data:&lt;/strong&gt; If you’re parsing local JSON content, the first thing to do is to ensure the variable isn’t empty. Maybe the variable is truncated for some reason.&lt;/p&gt;

&lt;p&gt;If it’s not, you can validate your JSON-formatted data with an online JSON validator like &lt;a href="https://jsonlint.com/" rel="noopener noreferrer"&gt;JSONLint&lt;/a&gt;. If you have an invalid JSON object, you’ll find out here!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When working with a third-party JSON API:&lt;/strong&gt; If you’re trying to parse a JSON API response, and you don’t have control over the back-end code, you can place your &lt;code&gt;JSON.parse&lt;/code&gt; reference into a &lt;code&gt;try/catch&lt;/code&gt; block – like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;JSON&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;parse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;jsonData&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
  &lt;span class="c1"&gt;// Do something with the JSON data&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;err&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;err&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Wrapping up
&lt;/h2&gt;

&lt;p&gt;The infamous "JSON input error" is a Syntax error usually raised when parsing empty or malformed JSON data. Fixing this issue is easy when dealing with locally-defined JSON data. &lt;/p&gt;

&lt;p&gt;If you don't have control over the back-end code generating the JSON data, a &lt;code&gt;try/catch&lt;/code&gt; block would help you avoid the "Uncaught SyntaxError" error.&lt;/p&gt;

&lt;p&gt;Additionally, you might find this &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse" rel="noopener noreferrer"&gt;Mozilla guide on &lt;code&gt;JSON.parse&lt;/code&gt;&lt;/a&gt; to avoid other types of parse errors.&lt;/p&gt;

&lt;p&gt;I hope this quick guide provided the answer you were looking for.&lt;/p&gt;

&lt;p&gt;Thanks for reading.&lt;/p&gt;

</description>
      <category>design</category>
      <category>uidesign</category>
      <category>productivity</category>
      <category>coding</category>
    </item>
    <item>
      <title>Add commas to numbers in JavaScript (Explained with examples)</title>
      <dc:creator>Reza Lavarian</dc:creator>
      <pubDate>Mon, 06 Feb 2023 19:49:12 +0000</pubDate>
      <link>https://dev.to/lavary/add-commas-to-numbers-in-javascript-explained-with-examples-27k8</link>
      <guid>https://dev.to/lavary/add-commas-to-numbers-in-javascript-explained-with-examples-27k8</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;✋ &lt;strong&gt;Update:&lt;/strong&gt; This post was originally published on my blog &lt;a href="https://www.decodingweb.dev" rel="noopener noreferrer"&gt;decodingweb.dev&lt;/a&gt;, where you can read the &lt;a href="https://www.decodingweb.dev/add-commas-to-numbers-in-javascript" rel="noopener noreferrer"&gt;latest version&lt;/a&gt; for a 💯 user experience. &lt;em&gt;~reza&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This guide explores the three common ways to add commas to numbers in JavaScript.&lt;/p&gt;

&lt;p&gt;Displaying numbers – whether currency or plain numbers – in an easy-to-read format significantly improves your &lt;a href="https://www.decodingweb.dev/learn-html" rel="noopener noreferrer"&gt;HTML page&lt;/a&gt; content and overall user experience. We usually achieve this by adding commas to numbers with the help of JavaScript and separating the digits by hundreds.&lt;/p&gt;

&lt;p&gt;There are plenty of ways to format your numbers. However, three of them are the most common among web developers:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Using the &lt;code&gt;Number.prototype.toLocalString()&lt;/code&gt; method&lt;/li&gt;
&lt;li&gt;Using &lt;code&gt;Intl.NumberFormat()&lt;/code&gt; object&lt;/li&gt;
&lt;li&gt;Using &lt;code&gt;String.prototype.replace()&lt;/code&gt; method with a regular expression&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let’s study each approach with examples.&lt;/p&gt;

&lt;h2&gt;
  
  
  Using &lt;code&gt;Number.prototype.toLocalString()&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;The method &lt;code&gt;Number.prototype.toLocalString()&lt;/code&gt; is the option you’re looking for if you need a quick solution. This method uses &lt;code&gt;Int.NumberFormat()&lt;/code&gt; object internally to do language-sensitive number formatting (more on this below).&lt;/p&gt;

&lt;p&gt;Here’s how we use it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;number&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;48372498372.34&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;number&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toLocaleString&lt;/span&gt;&lt;span class="p"&gt;())&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you call it without arguments, it'll format the respective number based on the default locale - in this case, the US locale.&lt;/p&gt;

&lt;p&gt;Some countries have their way of formatting numbers. For instance. in Germany, hundreds of separated by a period (&lt;code&gt;"."&lt;/code&gt;) and decimals with a comma. In that case, you can add the key as the first argument.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;number&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;4723984738.5748937&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;Intl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;NumberFormat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;de-DE&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;number&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="c1"&gt;// output: 834.723.984.738,575&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can fine-tune the output by passing it an options object. For instance, to display currency values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;number&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;834723984738.5748937&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;number&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toLocaleString&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;en-US&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;style&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;currency&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;currency&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;USD&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;}))&lt;/span&gt;
&lt;span class="c1"&gt;// output: ,723,984,738.58&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; when you set the style as currency, you must define the currency too. Otherwise, you'll get the following TypeError:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Uncaught TypeError: Currency code is required with currency style.
    at Number.toLocaleString (&amp;lt;anonymous&amp;gt;)
    at index.js:10:20
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The possible values for currency are &lt;strong&gt;ISO 4217&lt;/strong&gt; currency codes such as &lt;strong&gt;USD&lt;/strong&gt; for the US dollar, &lt;strong&gt;EUR&lt;/strong&gt; for the euro, or &lt;strong&gt;CNY&lt;/strong&gt; for the Chinese RMB.&lt;/p&gt;

&lt;p&gt;If you need to display decimal places with a fixed precision, you can define a &lt;code&gt;minimumFractionDigits&lt;/code&gt; or &lt;code&gt;maximumFractionDigits&lt;/code&gt; in the options object accordingly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;number&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;834723984738.5748937&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;number&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toLocaleString&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;en-US&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;style&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;currency&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;currency&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;EUR&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;minimumFractionDigits&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;}))&lt;/span&gt;
&lt;span class="c1"&gt;// output: €834,723,984,738.575&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;code&gt;Intl.NumberFormat()&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;The Intl object is the namespace for the ECMAScript Internationalization API, which provides language-sensitive string comparison, number formatting, and the date and time formatting.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;Intl.NumberFormat()&lt;/code&gt; constructor creates &lt;code&gt;Intl.NumberFormat&lt;/code&gt; objects that enable language-sensitive number formatting.&lt;/p&gt;

&lt;p&gt;To format a number, you call the &lt;code&gt;format()&lt;/code&gt; method against this object:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;number&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;834723984738.5748937&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;Intl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;NumberFormat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;en-US&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;number&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="c1"&gt;// output: 834,723,984,738.575&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output would be the same &lt;code&gt;toLocalString()&lt;/code&gt; since it uses &lt;code&gt;Intl.NumberFormat()&lt;/code&gt; internally (in implementations with &lt;code&gt;Intl.NumberFormat&lt;/code&gt; API support).&lt;/p&gt;

&lt;p&gt;And the options object is the same as the one in our &lt;code&gt;toLocalString()&lt;/code&gt; code example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;number&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;834723984738.5748937&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;Intl&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;NumberFormat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;en-US&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;style&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;currency&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;currency&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;USD&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;}).&lt;/span&gt;&lt;span class="nf"&gt;format&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;number&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;A note on performance, based on MDN docs:&lt;/strong&gt;&lt;br&gt;
When formatting a large set of numbers, it is better to create an &lt;code&gt;Intl.NumberFormat&lt;/code&gt; object and use the function provided by its format property.&lt;/p&gt;
&lt;h2&gt;
  
  
  Using regular expression to add commas to numbers
&lt;/h2&gt;

&lt;p&gt;Using regular expressions is the old-school way of handling number formatting. Even though &lt;code&gt;toLocalString()&lt;/code&gt; and &lt;code&gt;Intl.NumberFomat()&lt;/code&gt; is well-supported across most browsers, you might want to do it in an old-fashioned way.&lt;/p&gt;

&lt;p&gt;To do this, you should use the &lt;code&gt;String.prototype.replace()&lt;/code&gt; method with a regular expression that separates the hundreds by commas.&lt;/p&gt;

&lt;p&gt;Let's see how it's done:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;number&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;834723984738.5748937&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;number&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toString&lt;/span&gt;&lt;span class="p"&gt;().&lt;/span&gt;&lt;span class="nf"&gt;replace&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sr"&gt;/B&lt;/span&gt;&lt;span class="se"&gt;(?=(&lt;/span&gt;&lt;span class="sr"&gt;d&lt;/span&gt;&lt;span class="se"&gt;{3})&lt;/span&gt;&lt;span class="sr"&gt;+&lt;/span&gt;&lt;span class="se"&gt;(?!&lt;/span&gt;&lt;span class="sr"&gt;d&lt;/span&gt;&lt;span class="se"&gt;))&lt;/span&gt;&lt;span class="sr"&gt;/g&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;,&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
&lt;span class="c1"&gt;// output: 834,723,984,738.575&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code, first, converts your number into a string and then calls the replace method with this regex pattern &lt;code&gt;/\B(?=(\d{3})+(?!\d))/g&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This regular expression starts with a boundary (&lt;code&gt;\B&lt;/code&gt;) to avoid a comma at the beginning of the number. Then, it uses to &lt;em&gt;lookaheads&lt;/em&gt; to mark numbers in hundreds. Consequently, The &lt;code&gt;replace()&lt;/code&gt; method places a comma in each match.&lt;/p&gt;

&lt;h2&gt;
  
  
  Wrapping up
&lt;/h2&gt;

&lt;p&gt;Formatting numbers can be done in a variety of ways in JavaScript. However, the approaches we explored in this quick guide are the most common among web developers:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;code&gt;Number.prototype.toLocalString()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Intl.FormatNumber&lt;/code&gt; from the ECMAScript Internationalization API&lt;/li&gt;
&lt;li&gt;Regular expressions&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;I hope this guide helps you find the answer you're looking for.&lt;/p&gt;

&lt;p&gt;Thanks for reading.&lt;/p&gt;

</description>
      <category>network</category>
      <category>webdev</category>
      <category>softwaredevelopment</category>
      <category>discuss</category>
    </item>
    <item>
      <title>How to remove the last character from a string in PHP</title>
      <dc:creator>Reza Lavarian</dc:creator>
      <pubDate>Mon, 06 Feb 2023 19:36:21 +0000</pubDate>
      <link>https://dev.to/lavary/how-to-remove-the-last-character-from-a-string-in-php-31ci</link>
      <guid>https://dev.to/lavary/how-to-remove-the-last-character-from-a-string-in-php-31ci</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;✋ &lt;strong&gt;Update:&lt;/strong&gt; This post was originally published on my blog &lt;a href="https://www.decodingweb.dev" rel="noopener noreferrer"&gt;decodingweb.dev&lt;/a&gt;, where you can read the &lt;a href="https://www.decodingweb.dev/php-remove-last-character-from-string" rel="noopener noreferrer"&gt;latest version&lt;/a&gt; for a 💯 user experience. &lt;em&gt;~reza&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;How do you remove the last character from a string in PHP? Most &lt;a href="https://www.decodingweb.dev/how-to-become-a-web-developer" rel="noopener noreferrer"&gt;web developers&lt;/a&gt; face it at one time or another; It can be a white space, a trailing slash in a HTTP URL, the last comma in a comma-separated list, or even a new line characters (&lt;code&gt;\n&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;Luckily, PHP has plenty of string manipulation functions you can use to get rid of that last character. &lt;/p&gt;

&lt;p&gt;In this quick guide, we’ll try three ways of removing the last character(s) from a string in PHP.&lt;/p&gt;

&lt;p&gt;Let’s begin with my favorite option &lt;code&gt;rtrim()&lt;/code&gt; a.k.a the right trim.&lt;/p&gt;

&lt;h2&gt;
  
  
  Remove the last character by PHP &lt;code&gt;rtrim()&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;PHP &lt;code&gt;rtrim()&lt;/code&gt; accepts two arguments: the input string and characters you wish to be stripped from the end of the input string.&lt;/p&gt;

&lt;p&gt;For instance, to remove the last comma in a comma-separated list:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="nv"&gt;$var&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'Banana, apple, orange, '&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nv"&gt;$trimmed&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;rtrim&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$var&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;', '&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nb"&gt;var_dump&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$trimmed&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// output: string(21) "Banana, apple, orange"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's see a more realistic example; A common reason to remove the last character from a string is to remove the trailing slash in a URL.&lt;/p&gt;

&lt;p&gt;Imagine you have a function that accepts a URL prefix as an argument. This function adds a path (e.g., &lt;code&gt;/api/v2&lt;/code&gt;) to the URL prefix and returns the result.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;getApiUrl&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$baseUrl&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; 
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$baseUrl&lt;/span&gt; &lt;span class="mf"&gt;.&lt;/span&gt; &lt;span class="s1"&gt;'/api/v2'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nv"&gt;$apiUrl&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;getApiUrl&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'https://decodingweb.dev/'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nb"&gt;var_dump&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$apiUrl&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// output: string(31) "https://decodingweb.dev//api/v2"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The problem with the above approach is that if the &lt;code&gt;$baseUrl&lt;/code&gt; contains a trailing slash, you might end up with double slashes in the result.&lt;/p&gt;

&lt;p&gt;You can simply avoid double slashes with &lt;code&gt;rtrim()&lt;/code&gt; like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;getApiUrl&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$baseUrl&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; 
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;rtrim&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$baseUrl&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'/'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="mf"&gt;.&lt;/span&gt; &lt;span class="s1"&gt;'/api/v2'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nv"&gt;$apiUrl&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;getApiUrl&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'https://decodingweb.dev/'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nb"&gt;var_dump&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$apiUrl&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// output: string(31) https://decodingweb.dev/api/v2&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But what if you needed to remove a number of characters from the end of the string (regardless of what they are)? Please read on.&lt;/p&gt;

&lt;h2&gt;
  
  
  Remove the last character by PHP &lt;code&gt;substr()&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;One way to strip the last character in a string is by using the PHP &lt;code&gt;substr()&lt;/code&gt; function.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;substr()&lt;/code&gt; function returns a portion of a string based on an &lt;code&gt;offset&lt;/code&gt; and &lt;code&gt;length&lt;/code&gt; (number of characters).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="nv"&gt;$var&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'abcdef'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nv"&gt;$trimmed&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;substr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$var&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nb"&gt;var_dump&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$trimmed&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// output: string(2) "ab"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, the &lt;code&gt;offset&lt;/code&gt; is &lt;code&gt;0&lt;/code&gt; (the first character), and the &lt;code&gt;length&lt;/code&gt; is &lt;code&gt;2&lt;/code&gt;, which is the number of characters counting from the &lt;code&gt;offset&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;And the result is &lt;code&gt;ab&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;offset&lt;/code&gt; can also take a negative value! When the &lt;code&gt;offset&lt;/code&gt; is negative, the count will begin from the end of the string. Saying that &lt;code&gt;-1&lt;/code&gt; means the last character from the end of the string. The value &lt;code&gt;-2&lt;/code&gt; means the last two characters, and so forth.&lt;/p&gt;

&lt;p&gt;That sounds like what we need! Let's see an example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="nv"&gt;$baseUrl&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'http://decodingweb.dev/'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nb"&gt;var_dump&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;substr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$baseUrl&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;

&lt;span class="c1"&gt;// output:  string(22) "http://decodingweb.dev"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And if you want to remove the last three characters from a string:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="nv"&gt;$string&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'abcdf'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nv"&gt;$trimmed&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;substr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$string&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="nb"&gt;var_dump&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$trimmed&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// output: string(2) "ab"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or even remove the last five characters from the string:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="nv"&gt;$string&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'abcdf'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nv"&gt;$trimmed&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;substr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$string&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="nb"&gt;var_dump&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$trimmed&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// output: string(0) &lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above example will return an empty string.&lt;/p&gt;

&lt;p&gt;You can also use &lt;code&gt;substr()&lt;/code&gt; to check the last character in a string, like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="nv"&gt;$string&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'abcdf'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nb"&gt;var_dump&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;substr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$string&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;

&lt;span class="c1"&gt;// output: string(1) f&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How about the multi-byte characters?
&lt;/h2&gt;

&lt;p&gt;Each character in English takes one byte. However, many UTF-8 characters take more than one byte, called multi-byte characters. For instance, accents over characters such as ä, é, or even an emoji 🍏 takes more than a byte.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;offset&lt;/code&gt; and &lt;code&gt;length&lt;/code&gt; in &lt;code&gt;substr()&lt;/code&gt; function won't handle multi-byte characters as expected because they assume one byte per character.&lt;/p&gt;

&lt;p&gt;Let's see it in an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="nv"&gt;$var&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'Cartão de Crédito'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nv"&gt;$trimmed&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;substr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$var&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nb"&gt;var_dump&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$trimmed&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// output: string(21) string(6) "rtão "&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, the &lt;code&gt;offset=2&lt;/code&gt; and &lt;code&gt;length=6&lt;/code&gt; is supposed to return &lt;code&gt;rtão d&lt;/code&gt;. However, the returned value is &lt;code&gt;rtão&lt;/code&gt;. The reason is &lt;code&gt;ã&lt;/code&gt; is a multi-byte character, and &lt;code&gt;substr()&lt;/code&gt; function isn't aware of it!&lt;/p&gt;

&lt;p&gt;Luckily, PHP has a multi-byte safe &lt;code&gt;substr()&lt;/code&gt; alternative: &lt;code&gt;mb_substr()&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="nv"&gt;$var&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'Cartão de Crédito'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nv"&gt;$trimmed&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;mb_substr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$var&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nb"&gt;var_dump&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$trimmed&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// output: string(7) "rtão d"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Remove the last character by PHP &lt;code&gt;substr_replace()&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;Another method to remove the last character from a string in PHP is by using the &lt;code&gt;substr_replace()&lt;/code&gt; function. &lt;/p&gt;

&lt;p&gt;Just like &lt;code&gt;substr()&lt;/code&gt;, this function accepts a &lt;code&gt;position&lt;/code&gt; and &lt;code&gt;offset&lt;/code&gt; too. However, unlike &lt;code&gt;substr()&lt;/code&gt; - which returns a substring - &lt;code&gt;substr_replace()&lt;/code&gt; replaces the substring with a replacement value.&lt;/p&gt;

&lt;p&gt;Let's make it clear with an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="nv"&gt;$var&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'This is a test'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nv"&gt;$newVar&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;substr_replace&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$var&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'that'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nb"&gt;var_dump&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$newVar&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// output: string(14) "that is a test"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, &lt;code&gt;offset=0&lt;/code&gt; and &lt;code&gt;length=4&lt;/code&gt; refers to &lt;code&gt;"This"&lt;/code&gt; in our string. And in this case, &lt;code&gt;"This"&lt;/code&gt; is replaced with the word &lt;code&gt;"That"&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;As a result, the output would be: &lt;code&gt;"That is a test"&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now, what if we can target the last character and replace it with an empty string?&lt;/p&gt;

&lt;p&gt;We can! Let's see how:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="nv"&gt;$baseUrl&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'http://decodingweb.dev/'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nb"&gt;var_dump&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;substr_replace&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$baseUrl&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;''&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;

&lt;span class="c1"&gt;// output:  string(22) http://decodingweb.dev&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We set the &lt;code&gt;offset&lt;/code&gt; to &lt;code&gt;-1&lt;/code&gt; (the last character) and replaced it with an empty string (&lt;code&gt;''&lt;/code&gt;). Just like that!&lt;/p&gt;

&lt;h2&gt;
  
  
  Wrapping up
&lt;/h2&gt;

&lt;p&gt;As you see, PHP is great at string manipulation, thanks to the functions we can use from the standard library.&lt;/p&gt;

&lt;p&gt;I hope this quick guide gave you the answer you were looking for.&lt;/p&gt;

&lt;p&gt;Thanks for reading.&lt;/p&gt;

</description>
      <category>contentwriting</category>
      <category>career</category>
      <category>writing</category>
      <category>opensource</category>
    </item>
    <item>
      <title>About "TypeError: map is not a function" in JavaScript</title>
      <dc:creator>Reza Lavarian</dc:creator>
      <pubDate>Mon, 06 Feb 2023 19:21:55 +0000</pubDate>
      <link>https://dev.to/lavary/about-typeerror-map-is-not-a-function-in-javascript-80</link>
      <guid>https://dev.to/lavary/about-typeerror-map-is-not-a-function-in-javascript-80</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;✋ &lt;strong&gt;Update:&lt;/strong&gt; This post was originally published on my blog &lt;a href="https://www.decodingweb.dev" rel="noopener noreferrer"&gt;decodingweb.dev&lt;/a&gt;, where you can read the &lt;a href="https://www.decodingweb.dev/fix-map-is-not-a-function-error-in-javascript" rel="noopener noreferrer"&gt;latest version&lt;/a&gt; for a 💯 user experience. &lt;em&gt;~reza&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The error “TypeError: object.map is not a function” occurs when you call the &lt;code&gt;map()&lt;/code&gt; method on a non-array object in JavaScript. &lt;/p&gt;

&lt;p&gt;A non-array object can be an object literal, a string, a Map object, a Set object, etc.&lt;/p&gt;

&lt;p&gt;Let’s see a simple example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;course&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;JavaScript for Beginners&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; 
    &lt;span class="na"&gt;language&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;JavaScript&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// This will cause the error&lt;/span&gt;
&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;newData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// do something ...&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;item&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code raises the "TypeError: object. map is not a function" error because the calling object isn't an array - it's an object literal.&lt;/p&gt;

&lt;h2&gt;
  
  
  The &lt;code&gt;map()&lt;/code&gt; method in JavaScript only works on arrays
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;map()&lt;/code&gt; method is a part of the array prototype, meaning you can only call it on JavaScript arrays. Here's how MDN Web Docs defines it:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Array.prototype.map()&lt;/strong&gt;&lt;br&gt;
The &lt;code&gt;map()&lt;/code&gt; method creates a new array populated with the results of calling a provided function on every element in the calling array.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;apples&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;bananas&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;oranges&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;grapes&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="c1"&gt;// This is correct&lt;/span&gt;
&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;newArray&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="c1"&gt;// do something here ...&lt;/span&gt;
&lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;item&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How to solve "map is not a function" error in JavaScript
&lt;/h2&gt;

&lt;p&gt;Whenever you encounter this error, inspect the variable calling &lt;code&gt;map()&lt;/code&gt; - You can use &lt;code&gt;console.log(data)&lt;/code&gt; to do so.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Before making any change to your code, ensure you're calling &lt;code&gt;map()&lt;/code&gt; on the correct data object because you might be calling &lt;code&gt;map()&lt;/code&gt; on an object, whereas you intended to refer to an array inside that object!&lt;/p&gt;

&lt;p&gt;Here's an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// ...&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;success&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;items&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="na"&gt;course&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;JavaScript for beginners&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="na"&gt;course&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;PHP programming&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="na"&gt;course&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Learning Python&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;items&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you called the &lt;code&gt;map()&lt;/code&gt; method against the main data object, you'd have to change it to &lt;code&gt;data.items&lt;/code&gt; instead:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// ...&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;newArray&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;items&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// do something here ...&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;item&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Please note if data contains raw JSON, you should parse it into a valid JavaScript object literal with the help of &lt;code&gt;JSON.parse()&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// ...&lt;/span&gt;

&lt;span class="nx"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;JSON&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;parse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How to work around "... map is not a function" error when using object literals?
&lt;/h2&gt;

&lt;p&gt;If you have an object literal and want to use it with the &lt;code&gt;map()&lt;/code&gt; function, you need to convert your data into an array representation.&lt;/p&gt;

&lt;p&gt;There are several ways to do this. Let's explore each with a quick example.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Using Object.keys():&lt;/strong&gt; Since the &lt;code&gt;map()&lt;/code&gt; function only works with array values, you can create an array from the keys in your object and call &lt;code&gt;map()&lt;/code&gt; on the resulting array. &lt;/p&gt;

&lt;p&gt;Consequently, you can access the original object data using the key in a bracket notation: &lt;code&gt;data[key]&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Let's see how:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// map-object-keys.js&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;course&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;JavaScript for beginners&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;language&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;JavaScript&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;creator&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;decodingweb.dev&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;dataKeys&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;Object&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;keys&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;// dataKeys: ['course', 'language', 'creator']&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;newData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;dataKeys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;key&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// Get the data from the original object with the bracket notation&lt;/span&gt;
    &lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;item&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;key&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="c1"&gt;// do something here ...&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;item&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Using Object.values():&lt;/strong&gt; Instead of object keys, you can create an array from the object values too:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// map-object-values.js&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;course&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;JavaScript for beginners&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;language&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;JavaScript&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;creator&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;decodingweb.dev&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;dataKeys&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;Object&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;values&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;// dataKeys: ['JavaScript for beginners, 'JavaScript'', 'decodingweb.dev']&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;newData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;dataKeys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;itemValue&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// do something here ...&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;itemValue&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Using &lt;code&gt;Object.entries()&lt;/code&gt; method:&lt;/strong&gt; If you need to access to key/value pair in your &lt;code&gt;map()&lt;/code&gt; callback, you can use &lt;code&gt;Object.entries()&lt;/code&gt;. This function creates an array consisting of &lt;code&gt;[key, value]&lt;/code&gt; arrays:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// map-object-entries.js&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;course&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;JavaScript for beginners&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;language&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;JavaScript&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;creator&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;decodingweb.dev&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;dataKeys&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;Object&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;entries&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="cm"&gt;/*
 dataKeys: [
    ['course',   'JavaScript for beginners']
    ['language', 'JavaScript']
    ['creator',  'decodingweb.dev']
]
*/&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;newData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;dataKeys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// do something here ...&lt;/span&gt;

    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="c1"&gt;// key&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="c1"&gt;// value&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt;  &lt;span class="nx"&gt;item&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Add a length property to objects with integer-keyed properties:&lt;/strong&gt; If you have an object with numerical keys, you can make it map-ready by giving it a &lt;code&gt;length&lt;/code&gt; property. After adding the &lt;code&gt;length&lt;/code&gt; property, which should contain the number of properties in the object, you can call the &lt;code&gt;map()&lt;/code&gt; method manually.&lt;/p&gt;

&lt;p&gt;Let's see an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// object-to-array.js&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;JavaScript&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;PHP&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Python&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Adding the length property&lt;/span&gt;
&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;length&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;

&lt;span class="cm"&gt;/* 
The data now looks like this: 
{
    length: 3,
    0: 'JavaScript',
    1: 'PHP',
    2: 'Python'
}

*/&lt;/span&gt;

&lt;span class="c1"&gt;// We call the map directly from the Array prototype passing data as the context (this)&lt;/span&gt;
&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;newData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;Array&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;prototype&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;map&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;call&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;item&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since &lt;code&gt;map()&lt;/code&gt; is a function, we can invoke it via &lt;code&gt;call()&lt;/code&gt;. We pass our object as the context (&lt;code&gt;this&lt;/code&gt;) to the call as the first argument. The second argument is the callback function, which is eventually passed to the &lt;code&gt;map()&lt;/code&gt; method.&lt;/p&gt;

&lt;h2&gt;
  
  
  If you're using JavaScript Map objects
&lt;/h2&gt;

&lt;p&gt;If you're calling the &lt;code&gt;map()&lt;/code&gt; method on a Map object, you'll still get this error.&lt;/p&gt;

&lt;p&gt;Luckily, Map objects implement &lt;code&gt;keys()&lt;/code&gt;, &lt;code&gt;values()&lt;/code&gt;, and &lt;code&gt;entries()&lt;/code&gt; methods. Using these methods, you generate arrays based on keys, values, or key/value pairs respectively (just like object literals in the above examples).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;//map-on-map-object.js&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;map1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Map&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;

&lt;span class="nx"&gt;map1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;a&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nx"&gt;map1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;b&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="nx"&gt;map1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;c&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="c1"&gt;// Since Map.prototype.keys() return a Map Iterator object, we use the spread operator to turn it into an array&lt;/span&gt;
&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;mapKeys&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[...&lt;/span&gt;&lt;span class="nx"&gt;map1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;keys&lt;/span&gt;&lt;span class="p"&gt;()]&lt;/span&gt; &lt;span class="c1"&gt;// [1, 2, 3]&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;newData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;mapKeys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;key&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// Do something here ...&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;map1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)]&lt;/span&gt;
&lt;span class="p"&gt;})&lt;/span&gt;

&lt;span class="c1"&gt;// Create a new Map object with the transformed array&lt;/span&gt;
&lt;span class="nx"&gt;map2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;newData&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You could also use &lt;code&gt;map1.values()&lt;/code&gt; and &lt;code&gt;map1.entries()&lt;/code&gt; methods accordingly.&lt;/p&gt;

&lt;p&gt;If you're working with a JavaScript Set object, the algorithm is the same.&lt;/p&gt;

&lt;h2&gt;
  
  
  Adding a check: Array.isArray()
&lt;/h2&gt;

&lt;p&gt;If you want to call the &lt;code&gt;map()&lt;/code&gt; method only if the data is an array (without adjusting it), you can put your code inside a conditional statement:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// map-array-if.js&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;JavaScript&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;PHP&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Python&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;newData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[]&lt;/span&gt;

&lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;Array&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;isArray&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="nx"&gt;newData&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;item&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
         &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;item&lt;/span&gt; 
       &lt;span class="p"&gt;})&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;newData&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As a result, the &lt;code&gt;map()&lt;/code&gt; method will only be called if the respective data object is a JavaScript array.&lt;/p&gt;

&lt;h2&gt;
  
  
  Wrapping up
&lt;/h2&gt;

&lt;p&gt;Alright, I think that does it! Whenever you encounter this error, first check you're using an array. If the input isn't an array object, before anything, ensure you're referring to the right value. Then, depending on your object (object literal, Map, or Set) transform your data into an array, then call its &lt;code&gt;map()&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;Additionally, you can check if the object is an array, and then, call the &lt;code&gt;map()&lt;/code&gt; method against it.&lt;/p&gt;

&lt;p&gt;Thanks for reading.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;❤️ You might like:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.decodingweb.dev/fix-map-is-not-a-function-error-in-javascript" rel="noopener noreferrer"&gt;TypeError: map is not a function in JavaScript in JavaScript (Fixed)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.decodingweb.dev/syntaxerror-unexpected-end-of-json-input-in-javascript" rel="noopener noreferrer"&gt;SyntaxError: Unexpected end of JSON input in JavaScript (Fixed)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.decodingweb.dev/how-to-solve-referenceerror-document-is-not-defined" rel="noopener noreferrer"&gt;How to fix "ReferenceError: document is not defined" in JavaScript&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>devto</category>
      <category>announcement</category>
      <category>offers</category>
    </item>
    <item>
      <title>PHP double question marks (Null coalescing operator) explained</title>
      <dc:creator>Reza Lavarian</dc:creator>
      <pubDate>Mon, 06 Feb 2023 18:51:01 +0000</pubDate>
      <link>https://dev.to/lavary/php-double-question-marks-null-coalescing-operator-explained-49d7</link>
      <guid>https://dev.to/lavary/php-double-question-marks-null-coalescing-operator-explained-49d7</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;✋ &lt;strong&gt;Update:&lt;/strong&gt; This post was originally published on my blog &lt;a href="https://www.decodingweb.dev" rel="noopener noreferrer"&gt;decodingweb.dev&lt;/a&gt;, where you can read the &lt;a href="https://www.decodingweb.dev/php-double-question-marks" rel="noopener noreferrer"&gt;latest version&lt;/a&gt; for a 💯 user experience. &lt;em&gt;~reza&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;PHP double question marks (&lt;code&gt;??&lt;/code&gt;) – officially known as &lt;em&gt;Null coalescing operator&lt;/em&gt; – is a convenient alternative to ternary expressions in conjunction with &lt;code&gt;isset()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;You might have seen the following expression in your Laravel or PHP projects:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="nv"&gt;$result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$value&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="nv"&gt;$alternativeValue&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But what do two question marks mean in PHP?&lt;/p&gt;

&lt;p&gt;The above expression returns its first operand (&lt;code&gt;$value&lt;/code&gt;) if it exists and is not &lt;code&gt;null&lt;/code&gt;; otherwise, it returns the second operand (&lt;code&gt;$alternativeValue&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;The above expression is equivalent to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="nv"&gt;$result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;isset&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$value&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="nv"&gt;$value&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;$alternativeValue&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How to use PHP double question marks
&lt;/h2&gt;

&lt;p&gt;Before the Null coalescing operator, you'd have to use a ternary operator with a call to &lt;code&gt;isset()&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="nv"&gt;$iceCreamFlavor&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;isset&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$_POST&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'flavor'&lt;/span&gt;&lt;span class="p"&gt;])&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="nv"&gt;$_POST&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'flavor'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'vanilla'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or as an &lt;code&gt;if&lt;/code&gt; statement:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="nv"&gt;$iceCreamFlavor&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'vanilla'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;isset&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$_POST&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'flavor'&lt;/span&gt;&lt;span class="p"&gt;]))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nv"&gt;$iceCreamFlavor&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$_POST&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'flavor'&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But with the Null coalescing operator, you can summarize it into:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="nv"&gt;$iceCreamFlavor&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nv"&gt;$_POST&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'flavor'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="s1"&gt;'vanilla'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can also chain multiple operators:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="nv"&gt;$display_name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt;  &lt;span class="nv"&gt;$first_name&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="nv"&gt;$last_name&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="s1"&gt;'Anonymous'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code will return the first defined value among &lt;code&gt;$first_name&lt;/code&gt;, &lt;code&gt;$last_name&lt;/code&gt;, and &lt;code&gt;Anonymous&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The Null coalescing operator has been added to PHP since version 7.&lt;/p&gt;

&lt;p&gt;I hope you found this quick tip helpful :-)&lt;/p&gt;

&lt;p&gt;Thanks for reading!&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;❤️ You might like:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.decodingweb.dev/php-remove-last-character-from-string" rel="noopener noreferrer"&gt;How to remove the last character from a string in PHP&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.decodingweb.dev/how-to-become-a-web-developer" rel="noopener noreferrer"&gt;How to become a web developer when you have no degree&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.decodingweb.dev/cms-knowledge" rel="noopener noreferrer"&gt;Do you need to know CMS as a back-end developer?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.decodingweb.dev/backend-web-frameworks" rel="noopener noreferrer"&gt;How back-end web frameworks work?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.decodingweb.dev/your-master-sword-a-programming-language" rel="noopener noreferrer"&gt;Your master sword: a programming language&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.decodingweb.dev/what-do-back-end-developers-do" rel="noopener noreferrer"&gt;What do back-end developers do?&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>announcement</category>
      <category>devto</category>
      <category>community</category>
      <category>offers</category>
    </item>
    <item>
      <title>How to Flatten an array in PHP (four methods)</title>
      <dc:creator>Reza Lavarian</dc:creator>
      <pubDate>Mon, 06 Feb 2023 18:28:05 +0000</pubDate>
      <link>https://dev.to/lavary/how-to-flatten-an-array-in-php-four-methods-dnd</link>
      <guid>https://dev.to/lavary/how-to-flatten-an-array-in-php-four-methods-dnd</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;✋ &lt;strong&gt;Update:&lt;/strong&gt; This post was originally published on my blog &lt;a href="https://www.decodingweb.dev" rel="noopener noreferrer"&gt;decodingweb.dev&lt;/a&gt;, where you can read the &lt;a href="https://www.decodingweb.dev/flatten-array-php" rel="noopener noreferrer"&gt;latest version&lt;/a&gt; for a 💯 user experience. &lt;em&gt;~reza&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;There’s no built-in function in PHP to flatten a multi-dimensional array, but it’s not a difficult thing to do in PHP. In fact, it’s quite easy.&lt;/p&gt;

&lt;p&gt;We usually flatten arrays of data fetched from a database or an API. In real-world scenarios, we’d usually want to take a few fields off each row for displaying in our views.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to flatten an array in PHP
&lt;/h2&gt;

&lt;p&gt;In this tutorial, we’ll explore four ways of flattening arrays (two-dimensional and multi-dimensional) in PHP:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;u&gt;Flatten two-dimensional arrays in PHP (when keys don’t matter)&lt;/u&gt;&lt;/li&gt;
&lt;li&gt;&lt;u&gt;Pluck a list of the given key/value pairs from a PHP array&lt;/u&gt;&lt;/li&gt;
&lt;li&gt;&lt;u&gt;Flatten a PHP array recursively I&lt;/u&gt;&lt;/li&gt;
&lt;li&gt;&lt;u&gt;Flatten a PHP array recursively II&lt;/u&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Flatten two-dimensional arrays in PHP
&lt;/h2&gt;

&lt;p&gt;If you have a two-dimensional array, you can flatten it by unpacking the array and passing it as an argument to the &lt;code&gt;array_merge()&lt;/code&gt; function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="c1"&gt;// Each array has two Apple devices in each category (iPads, phones, and laptops)&lt;/span&gt;
&lt;span class="nv"&gt;$products&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
     &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'iPad Air'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'iPad pro'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
     &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'iPhone 13'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'iPhone 13 mini'&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
     &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'MacBook Air'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'MacBook Pro'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="p"&gt;];&lt;/span&gt;

&lt;span class="c1"&gt;// Flatten the array&lt;/span&gt;
&lt;span class="nv"&gt;$result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;array_merge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mf"&gt;...&lt;/span&gt;&lt;span class="nv"&gt;$products&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nb"&gt;print_r&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$result&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And this will be the output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Array
(
  [0] =&amp;gt; iPad Air
  [1] =&amp;gt; iPad pro
  [2] =&amp;gt; iPhone 13
  [3] =&amp;gt; iPhone 13 mini
  [4] =&amp;gt; MacBook Air
  [5] =&amp;gt; MacBook Pro
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In PHP versions before 8.1, if the &lt;code&gt;$products&lt;/code&gt; array has string keys, you must extract the values with &lt;code&gt;array_values()&lt;/code&gt; first:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;
&lt;span class="c1"&gt;// ...&lt;/span&gt;

&lt;span class="nv"&gt;$result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;array_merge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mf"&gt;...&lt;/span&gt;&lt;span class="nb"&gt;array_values&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$products&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;For PHP versions before 7.4:&lt;/strong&gt; if the &lt;code&gt;$products&lt;/code&gt; array is empty, the &lt;code&gt;array_merge()&lt;/code&gt; would be invoked without arguments. This will raise an error. To avoid the error, add an empty array &lt;code&gt;[]&lt;/code&gt; to the &lt;code&gt;array_merge()&lt;/code&gt; arguments:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;
&lt;span class="c1"&gt;// ...&lt;/span&gt;

&lt;span class="nv"&gt;$results&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;array_merge&lt;/span&gt;&lt;span class="p"&gt;([],&lt;/span&gt; &lt;span class="mf"&gt;...&lt;/span&gt;&lt;span class="nv"&gt;$products&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Argument unpacking has been available since PHP 5.6+.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; Since PHP 8.1, unpacking the outer array with string keys (associative arrays) is possible without using &lt;code&gt;array_values()&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Pluck a list of the given key/value pairs from the array
&lt;/h2&gt;

&lt;p&gt;If you have an array of arrays (two-dimensional), and you want to take a specific key (e.g., &lt;code&gt;name&lt;/code&gt;) off each array and create an array of names, you can use &lt;code&gt;array_column()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Imagine you've fetched a list of customers from the database, and you have the results as a two-dimensional array. Now you want to create an array containing the name of each person.&lt;/p&gt;

&lt;p&gt;Here's how it's done:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="c1"&gt;// Array representing a possible record set returned from a database&lt;/span&gt;
&lt;span class="nv"&gt;$records&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;array&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="k"&gt;array&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="s1"&gt;'id'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;2135&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s1"&gt;'first_name'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'John'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s1"&gt;'last_name'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'Doe'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;),&lt;/span&gt;
    &lt;span class="k"&gt;array&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="s1"&gt;'id'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;3245&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s1"&gt;'first_name'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'Sally'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s1"&gt;'last_name'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'Smith'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;),&lt;/span&gt;
    &lt;span class="k"&gt;array&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="s1"&gt;'id'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;5342&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s1"&gt;'first_name'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'Jane'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s1"&gt;'last_name'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'Jones'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;),&lt;/span&gt;
    &lt;span class="k"&gt;array&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="s1"&gt;'id'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;5623&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s1"&gt;'first_name'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'Peter'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s1"&gt;'last_name'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'Doe'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nv"&gt;$first_names&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;array_column&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$records&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'first_name'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nb"&gt;print_r&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$first_names&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And the output will be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Array
(
    [0] =&amp;gt; John
    [1] =&amp;gt; Sally
    [2] =&amp;gt; Jane
    [3] =&amp;gt; Peter
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Flatten a PHP array recursively I
&lt;/h2&gt;

&lt;p&gt;If your array has more than two dimensions (multi-dimensional), we need to take a recursive approach. The starter method is &lt;code&gt;array_walk_recursive()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Here's how it's done:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="nv"&gt;$data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="s1"&gt;'name'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'James'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s1"&gt;'contact'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="s1"&gt;'phone'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
            &lt;span class="s1"&gt;'work_phone'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'000'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s1"&gt;'home_phone'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'111'&lt;/span&gt;
        &lt;span class="p"&gt;],&lt;/span&gt;
        &lt;span class="s1"&gt;'emails'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'james@test'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="p"&gt;];&lt;/span&gt;

&lt;span class="nv"&gt;$results&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[];&lt;/span&gt;
&lt;span class="nb"&gt;array_walk_recursive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$data&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$item&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="nv"&gt;$results&lt;/span&gt;&lt;span class="p"&gt;){&lt;/span&gt;&lt;span class="nv"&gt;$results&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$key&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$item&lt;/span&gt;&lt;span class="p"&gt;;});&lt;/span&gt;

&lt;span class="nb"&gt;print_r&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$results&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This function takes an array and iterates over every element recursively. On each iteration, the provided callback is executed. &lt;/p&gt;

&lt;p&gt;The callback accepts two arguments, &lt;code&gt;$item&lt;/code&gt; and &lt;code&gt;$key&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Since the &lt;code&gt;$results&lt;/code&gt; array is declared in the global scope, we import it into the callback (via &lt;code&gt;use()&lt;/code&gt;) as a reference (&lt;code&gt;&amp;amp;$results&lt;/code&gt;) - so that we can modify it.&lt;/p&gt;

&lt;p&gt;And this will be the output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Array
(
  [name] =&amp;gt; James
  [work_phone] =&amp;gt; 000
  [home_phone] =&amp;gt; 111
  [emails] =&amp;gt; james@test
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Please note if there are elements with the same key, the former will be overridden by the latter.&lt;/p&gt;

&lt;h2&gt;
  
  
  Flatten a PHP array recursively II
&lt;/h2&gt;

&lt;p&gt;If you need more control over the flattening process, it's easy to create a recursive function yourself.&lt;/p&gt;

&lt;p&gt;Let's see how:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="cp"&gt;&amp;lt;?php&lt;/span&gt;

&lt;span class="nv"&gt;$data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="s1"&gt;'name'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'James'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s1"&gt;'contact'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="s1"&gt;'phone'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
            &lt;span class="s1"&gt;'work_phone'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'000'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s1"&gt;'home_phone'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'111'&lt;/span&gt;
        &lt;span class="p"&gt;],&lt;/span&gt;
        &lt;span class="s1"&gt;'emails'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="s1"&gt;'james@test'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="p"&gt;];&lt;/span&gt;

&lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;flatten&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$array&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nv"&gt;$results&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[];&lt;/span&gt;

    &lt;span class="k"&gt;foreach&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$array&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="nv"&gt;$key&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$value&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;is_array&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$value&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="o"&gt;!&lt;/span&gt; &lt;span class="k"&gt;empty&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$value&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nv"&gt;$results&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;array_merge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$results&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;flatten&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$value&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nv"&gt;$results&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$key&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$value&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$results&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;span class="nv"&gt;$results&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[];&lt;/span&gt;
&lt;span class="nv"&gt;$results&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;flatten&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$data&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nb"&gt;print_r&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$results&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, we took a recursive approach. The &lt;code&gt;flatten()&lt;/code&gt; function takes a PHP array and iterates over all the elements by a &lt;code&gt;foreach()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;On each iteration, we check if the current value is an array and not empty. &lt;/p&gt;

&lt;p&gt;If it's a non-empty array, we call the &lt;code&gt;flatten()&lt;/code&gt; function with the current element as its argument.&lt;/p&gt;

&lt;p&gt;If the current element isn't an array, we push it to &lt;code&gt;$results&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Basically, the function keeps calling itself until it has gone over all non-array elements (down to the deepest level), and has pushed them to the &lt;code&gt;$results&lt;/code&gt; array.&lt;/p&gt;

&lt;p&gt;And this will output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Array
(
  [name] =&amp;gt; James
  [work_phone] =&amp;gt; 000
  [home_phone] =&amp;gt; 111
  [emails] =&amp;gt; james@test
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Wrapping up
&lt;/h2&gt;

&lt;p&gt;We usually flatten arrays fetched from a data source, like a database or an API. Taking a recursive approach is usually the most natural way to flatten arrays. However, &lt;code&gt;array_walk_recursive()&lt;/code&gt; and &lt;code&gt;array_column()&lt;/code&gt; work quite well in specific scenarios.&lt;/p&gt;

&lt;p&gt;I hope you found this guide helpful.&lt;/p&gt;

&lt;p&gt;Thanks for reading.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;❤️ You might like&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.decodingweb.dev/php-double-question-marks" rel="noopener noreferrer"&gt;PHP double question marks (Null coalescing operator) explained&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.decodingweb.dev/php-remove-last-character-from-string" rel="noopener noreferrer"&gt;How to remove the last character from a string in PHP&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.decodingweb.dev/how-to-become-a-web-developer" rel="noopener noreferrer"&gt;How to become a web developer when you have no degree&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.decodingweb.dev/cms-knowledge" rel="noopener noreferrer"&gt;Do you need to know CMS as a back-end developer?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.decodingweb.dev/backend-web-frameworks" rel="noopener noreferrer"&gt;How back-end web frameworks work?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.decodingweb.dev/your-master-sword-a-programming-language" rel="noopener noreferrer"&gt;Your master sword: a programming language&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.decodingweb.dev/what-do-back-end-developers-do" rel="noopener noreferrer"&gt;What do back-end developers do?&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>announcement</category>
      <category>devto</category>
      <category>community</category>
    </item>
  </channel>
</rss>
