<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by wathsala danthasinghe on Medium]]></title>
        <description><![CDATA[Stories by wathsala danthasinghe on Medium]]></description>
        <link>https://medium.com/@dkwathsala?source=rss-de61b3afaa03------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oOO008xdsq3u5pFeOkLpXA.jpeg</url>
            <title>Stories by wathsala danthasinghe on Medium</title>
            <link>https://medium.com/@dkwathsala?source=rss-de61b3afaa03------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:50:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dkwathsala/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Machine Learning Use Case: Build a Linear Regression Model to Predict the Weather.]]></title>
            <link>https://medium.com/@dkwathsala/machine-learning-use-case-build-a-linear-regression-model-to-predict-the-weather-9c61443f4a1a?source=rss-de61b3afaa03------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c61443f4a1a</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[wathsala danthasinghe]]></dc:creator>
            <pubDate>Tue, 17 Dec 2024 09:07:18 GMT</pubDate>
            <atom:updated>2024-12-24T16:16:08.683Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Is there a relationship between humidity and temperature? What about between humidity and apparent temperature? Can you predict the apparent temperature given the humidity?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U4Gek7xPXbZgyLZ5" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Today, we are going to develop a machine-learning <strong>linear regression model</strong> to predict the weather. We are not going to discuss the theoretical concept of machine learning, but we are going to focus on implementing a machine learning model. So, I think you have some basic knowledge of the machine learning concept and Python. We implement the model with the following steps.</p><ol><li><strong>Problem definition.</strong></li><li><strong>Collect the data.</strong></li><li><strong>Data preprocess.</strong></li><li><strong>Feature engineering.</strong></li><li><strong>Train the model.</strong></li><li><strong>Model evaluation.</strong></li></ol><h3>What is Linear Regression?</h3><blockquote><a href="https://www.ibm.com/topics/linear-regression">Linear regression analysis is used to predict the value of a variable based on the value of another variable. The variable you want to predict is called the dependent variable. The variable you are using to predict the other variable’s value is called the independent variable</a>.</blockquote><p>Linear Regression is used in Supervised-machine learning to identify the line relationship between the dependent variable and one or more independent features by fitting a linear equation. I recommend this <a href="https://www.geeksforgeeks.org/ml-linear-regression/"><em>article </em></a>for more about Linear Regression for ML.</p><h3>Problem definition.</h3><p>The problem that we are going to implement is,</p><p><strong>Use case</strong>: Is there a relationship between humidity and temperature? What about between humidity and apparent temperature? Can you predict the apparent temperature given the humidity?</p><p>Before implementing a machine learning model, there is a complete idea about the problem domain in which you are going to implement the solution.</p><p>Here discuss the humidity, temperature, and apparent temperature. So we need to have a clear knowledge about these terms.</p><p>In simple, Humidity is a measure of the amount of water vapor in the air.</p><blockquote><strong>Apparent Temperature</strong>: The perceived temperature in degrees Fahrenheit derived from either a combination of temperature and wind (Wind Chill) or temperature and humidity (Heat Index) for the indicated hour. <a href="https://meteor.geol.iastate.edu/~ckarsten/bufkit/apparent_temperature.html">source</a></blockquote><h3><strong>DataSet</strong></h3><p>Collecting data to the relevant problem domain is important because your solution is based on the quality and the quantity of the data. The data directly impacts to your machine-learning model and its accuracy.</p><p>The dataset for our problem is taken from the <a href="https://www.kaggle.com/budincsevity/szeged-weather?select=weatherHistory.csv">Kegalle</a>.</p><h3>Data preprocessing</h3><p>Data preprocessing is a data mining technique that is used to transform the raw data into a useful and efficient format. Under the data preprocessing <strong>Filling missing values, Removing duplicates, Dealing with outliers, Data Transformations, Splitting the dataset, and feature scaling </strong>are done.</p><p>Each steps are discussed in the Python <a href="https://github.com/KuWathsala/Linear-Regression---Weather-Dataset/blob/master/Solution_174025D.ipynb">notebook</a>.</p><h4><strong>Filling missing values</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*pQtSRcuhH9OtAjopcIJ-AA.png" /></figure><h4><strong>Removing duplicates</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*vlCK6vlC4WHRDHCRmPohkQ.png" /></figure><h4><strong>Dealing with outliers</strong></h4><p>The ‘Humidity’, ‘Wind speed (km/h)’, and ‘Pressure (millibars)’ have outliers. The IQR is used to handle the outliers of the ‘Humidity’ because the outlier lower_limit is far away from 0.1649. However, the IQR is not effective to use, because of the ‘Pressure (millibars)’ lower limit of 998.1500000000001 and the upper limit of 1034.79. However, we can see the outlier lies far away less than 200. The ‘Temperature’, ‘Wind Bearing (degrees)’, ‘Pressure (millibars)’ there are no such outliers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*7wZpScdxd4ULj2_sOcP70w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*o8CgnpwXtJGw4Y52_eH9sw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*hUF4BFEHfrARIrhUTpf3YA.png" /></figure><h4>Data encoding</h4><p>Numerical variables and categorical variables are in the dataset. So, categorical variables cannot be handled without encoding. The following code shows that ‘Precip Type’ is encoded label encoding. Here simply used label encoding because only 2 values need to be represented by numerical values. (rain as 0 and snow as 1)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Wqm5rS7X_0K9ZLi7x8Saw.png" /></figure><h4>Feature Transformations</h4><p>The Q-Q plots show the ‘Temperature ©’ and ‘Pressure (millibars)’ lie on the red line which means a normal (or Gaussian) distribution appears in a straight line. The ‘’Wind Speed (km/h)’ is right skewed according to the view of the histogram. The ‘Humidity’ is also left skewed.</p><p>Therefore, to reduce the skewness and come to normal distribution form, the ‘<strong>Wind Speed (km/h)</strong>’ needs to <strong>log transformation</strong>, and the ‘<strong>Humidity</strong>’ needs to <strong>exponent transformation</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*daNjPJu1XsSdsaY-RRrE2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*Cmuko29SLAxH9pyMhDRySQ.png" /></figure><h4><strong>Feature scaling</strong></h4><p>Feature scaling Standardization methods enable the normalizing of the range of values of independent variables. The standard standardization and s min max standardization methods can be identified as standardization methods.</p><p>Here, I used the standard standardization method for Feature scaling. standardization sets 0 as mean (μ) and standard deviation (σ) as 1.</p><p>It is important to remove categorical features before the standardization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*RImT9nnc2FsMMKR2s5daJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*ZR15ZNCQpHN8zRaRJllS0A.png" /><figcaption>The features means are very close to the 0 and the std is close to the 1.</figcaption></figure><h4>Variable Discretization</h4><p>Variable Discretization transforms the continuous variables into discrete variables. There are mainly 3 discretization approaches Supervised, Unsupervised, and Custom discretization.</p><p>Here we use an unsupervised approach named k-means clustering to the continuous variables then each cluster is considered as a bin. Here I used 8 bins for each feature. It is important to remove categorical features before the variable discretization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*4_GgA8MISJQ3SNkA9dg--A.png" /></figure><h3>Feature Extraction</h3><p>Feature extraction is a process of dimensionality reduction that identifies important features of the data using domain knowledge. It helps to only include relevant inputs to the machine learning model. More features may lead to a decline in accuracy if they include irrelevant features creating the unrequired noise in the model.</p><p>We identify significant and independent features by using a correlation matrix and use <strong>PCA </strong>for feature reduction.</p><h4>Correlation matrix</h4><p>The correlation matrix represents the correlations between pairs of variables. it lies between -1 and +1. minus values say that there are negative correlations and positive values say that there are negative correlations.</p><p><strong>r &lt; 0.3 None or very weak<br>0.3 &lt; r &lt;0.5 Weak<br>0.5 &lt; r &lt; 0.7 Moderate<br>r &gt; 0.7 Strong</strong></p><p>According to the heatmap in the dataset, we can conclude that</p><p><strong>* humidity and temperature (-0.60) -&gt; moderately negative correlation<br>* humidity and Apparent temperature (-0.59) -&gt; moderately negative correlation<br>* Visibility and Apparent temperature (0.38) -&gt; weak positive correlation<br>* Precip type and Apparent temperature (-0.56) -&gt; moderately negative correlation</strong></p><p>According to our use case, the answer to the,</p><p>“<strong>Is there a relationship between humidity and temperature?</strong>”<br>“YES”<br> * humidity and temperature (-0.60) have a moderately negative correlation<br> <br><strong>“What about between humidity and apparent temperature?”</strong><br> * humidity and Apparent temperature (-0.59) has moderately negative correlation<br> <br><strong>“Can you predict the apparent temperature given the humidity?”</strong><br> * Here we can not directly predict apparent temperature by given humidity because the apparent temperature depends on<br> Temperature, humidity, Precip type, and as well as visibility<br> <br>Temperature, humidity, Precip type have moderate relationships with the Apparent temperature. The visibility and Pressure have a weak relationship with the Apparent temperature.</p><p><strong>Significant Features to Apparent Temperature ©:</strong><br><strong> </strong>* Temperature © → 0.98<br> * Humidity → -0.59<br> * Visibility (km) → 0.38<br> * Pressure (millibars) → -0.28</p><p><strong>Features with Low Significance:</strong><br> * Wind Speed (km/h) → -0.035 (very low correlation).<br> * Wind Bearing (degrees) → 0.029 (negligible correlation)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EUpqBbWM7VgDqbnBNgmYBg.png" /></figure><h4>Principle Component Analysis (PCA)</h4><p>PCA is used commonly as a Feature extraction technique to reduce the dimensions of the dataset.</p><p>By using the attribute explained_variance<em>_ratio_</em> the variance first principal components containing up to 95% are taken to the model training. The training model takes 5 components containing over 95% of the information.</p><h3>Train the Model</h3><p>The next step is to implement a model with our prepared data set. Here, I use linear regression to implement the model for our problem domain that predicts the Apparent temperature.</p><p>The linear Regression techniques are used to implement a linear relationship between the independent/s(X) and the dependent(Y) variables. It predicts the dependent variable based on the independent variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*ZMjsm2QFN6rbN5EZwax-gA.png" /></figure><h3>Evaluate the model</h3><p>to evaluate the linear regression model we can use<strong> Mean squad error (MSE) </strong>and <strong>Root mean squad error (RMSE).</strong></p><p>Feature with the lowest MSE reflects the strongest linear relationship with the target.</p><p>The lowest MSE generally indicated that the model has better performance, a good fix, and the most significant features are selected in feature engineering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*QdrXzhamNlYXPP65-J_glA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*BZSYKc_AWi9u695KzJju9A.png" /></figure><h3>Code Base</h3><p><a href="https://github.com/KuWathsala/Linear-Regression---Weather-Dataset">GitHub - KuWathsala/Linear-Regression---Weather-Dataset</a></p><h3><strong>Conclusion</strong></h3><p>The implemented model is achieved with more than 95% accuracy with the lowest MSE. The lowest MSE generally indicated that the model has better performance and, a good fix, and the feature selection is done in perfect. Now we can give the answers to the questions that we had in the use case.</p><p>“<strong>Is there a relationship between humidity and temperature?</strong>”<br>“YES”<br> * humidity and temperature (-0.60) have a moderately negative correlation<br> <br><strong>“What about between humidity and apparent temperature?”</strong><br> * humidity and Apparent temperature (-0.59) have a moderately negative correlation.</p><p><strong>“Can you predict the apparent temperature given the humidity?”</strong><br> * Here we can not directly predict apparent temperature by given humidity because the apparent temperature depends on Temperature, humidity, Precip type, and as well as visibility</p><h3><strong>Reference</strong></h3><ul><li><a href="https://www.ibm.com/topics/linear-regression">What Is Linear Regression? | IBM</a></li><li><a href="https://www.geeksforgeeks.org/ml-linear-regression/">Linear Regression in Machine learning - GeeksforGeeks</a></li><li><a href="https://github.com/KuWathsala/Linear-Regression---Weather-Dataset">GitHub - KuWathsala/Linear-Regression---Weather-Dataset</a></li><li><a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html#sklearn.linear_model.LinearRegression">LinearRegression</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c61443f4a1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning Use Case : Build a classification model to predict the Bank marketing.]]></title>
            <link>https://medium.com/@dkwathsala/machine-learning-use-case-build-a-classification-model-to-predict-the-bank-marketing-4795377e3c05?source=rss-de61b3afaa03------2</link>
            <guid isPermaLink="false">https://medium.com/p/4795377e3c05</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[classification-algorithms]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[wathsala danthasinghe]]></dc:creator>
            <pubDate>Wed, 28 Dec 2022 13:26:57 GMT</pubDate>
            <atom:updated>2024-12-24T16:17:18.046Z</atom:updated>
            <content:encoded><![CDATA[<h3>Machine Learning Use Case : Build a classification model to predict the Bank marketing.</h3><p>Implement an classification model using Support Vector Machine (SVM).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zyC3iIzdTX-Gtak2" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Today we are going to develop a machine learning classification model with Support Vector Machine (SVM). Here, we are not going to discuss the theoretical concept of the machine learning, but we focus to implement a machine learning model. So, I think you have some basic knowledge of machine learning concept and python. We implement the model with following steps.</p><ol><li><strong>Problem definition.</strong></li><li><strong>Collect the data.</strong></li><li><strong>Data preprocess.</strong></li><li><strong>Feature engineering.</strong></li><li><strong>Train the model.</strong></li><li><strong>Model evaluation.</strong></li></ol><p>First of all, Let’s define our problem domain.</p><h4><strong>1. Problem definition.</strong></h4><p>The problem that we are going to implement is,</p><p><strong>Use case: Bank Marketing Dataset.</strong></p><blockquote>The dataset is related with direct marketing campaigns (phone calls) of a Portuguese banking institution. <strong>The goal is to predict if the client will subscribe a term deposit ?.</strong></blockquote><p><strong>Problem domain</strong> — The direct marketing campaign of Portuguese banking institution’s phone calls dataset is given. The marketing campaign is based on the phone calls. It is going to predict the client will subscribe a term deposit using given data.</p><h4><strong>2. Collect the data</strong></h4><p>The collecting data to the relevant problem domain is important because your solution is based on the quality and the quantity of the data. The data directly impact to your machine learning model and its accuracy.</p><p>The dataset to our problem is taken from the <a href="https://archive.ics.uci.edu/ml/datasets/bank+marketing#">UCI Machine Learning Repository: Bank Marketing Data Set</a></p><p><strong>Input variables:<br> </strong># bank client data:<br> 1 — age (numeric)<br> 2 — job : type of job (categorical: ‘admin.’,’blue-collar’,’entrepreneur’,’housemaid’,’management’,’retired’,’self-employed’,’services’,’student’,’technician’,’unemployed’,’unknown’)<br> 3 — marital : marital status (categorical: ‘divorced’,’married’,’single’,’unknown’; note: ‘divorced’ means divorced or widowed)<br> 4 — education (categorical: ‘basic.4y’,’basic.6y’,’basic.9y’,’high.school’,’illiterate’,’professional.course’,’university.degree’,’unknown’)<br> 5 — default: has credit in default? (categorical: ‘no’,’yes’,’unknown’)<br> 6 — housing: has housing loan? (categorical: ‘no’,’yes’,’unknown’)<br> 7 — loan: has personal loan? (categorical: ‘no’,’yes’,’unknown’)<br> # related with the last contact of the current campaign:<br> 8 — contact: contact communication type (categorical: ‘cellular’,’telephone’)<br> 9 — month: last contact month of year (categorical: ‘jan’, ‘feb’, ‘mar’, …, ‘nov’, ‘dec’)<br> 10 — day_of_week: last contact day of the week (categorical: ‘mon’,’tue’,’wed’,’thu’,’fri’)<br> 11 — duration: last contact duration, in seconds (numeric). Important note: this attribute highly affects the output target (e.g., if duration=0 then y=’no’). Yet, the duration is not known before a call is performed. Also, after the end of the call y is obviously known. Thus, this input should only be included for benchmark purposes and should be discarded if the intention is to have a realistic predictive model.<br> # other attributes:<br> 12 — campaign: number of contacts performed during this campaign and for this client (numeric, includes last contact)<br> 13 — pdays: number of days that passed by after the client was last contacted from a previous campaign (numeric; 999 means client was not previously contacted)<br> 14 — previous: number of contacts performed before this campaign and for this client (numeric)<br> 15 — poutcome: outcome of the previous marketing campaign (categorical: ‘failure’,’nonexistent’,’success’)<br> # social and economic context attributes<br> 16 — emp.var.rate: employment variation rate — quarterly indicator (numeric)<br> 17 — cons.price.idx: consumer price index — monthly indicator (numeric)<br> 18 — cons.conf.idx: consumer confidence index — monthly indicator (numeric)<br> 19 — euribor3m: euribor 3 month rate — daily indicator (numeric)<br> 20 — nr.employed: number of employees — quarterly indicator (numeric)<br> <br> <strong>Output variable (desired target):<br> </strong>21 — y — has the client subscribed a term deposit? (binary: ‘yes’,’no’)</p><p><strong>Source</strong>: <a href="https://archive.ics.uci.edu/ml/datasets/bank+marketing">UCI Machine Learning Repository: Bank Marketing Data Set</a></p><h4>3. Data preprocessing</h4><p>Data preprocessing is a data mining technique which is used to transform the raw data in a useful and efficient format. Under the data preprocessing <em>Filling missing values, removing duplicates, dealing with outliers, Data Transformations, Splitting the dataset, feature scaling</em> are mainly done.</p><p>As the first step of the coding, it is needed to import the Data. Here imports the CSV file into Python using Pandas (fig. 1).</p><pre>banking_df = pd.read_csv(‘banking.csv’)</pre><p>In the dataset there are 41188 rows. Out of them,<em> ‘job’, ‘marital’, ‘education’, ‘default’, ‘housing’, ‘loan’, ‘contact’, ‘month’, ‘day_of_week’, ‘poutcome’</em> are categorical. Others are continuous. here,<em> ‘y’ </em>is the target variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*VNMVlO4KBlVJ8vm1nuz9EQ.png" /><figcaption>fig. 1 ( information of the dataset.)</figcaption></figure><p>When we consider about the dataset, we can identify that there are couple of irrelevant features according to the problem domain.</p><p>The ‘duration’ is mentioned that,</p><blockquote>duration: last contact duration, in seconds (numeric). Important note: this attribute highly affects the output target (e.g., if duration=0 then y=’no’). Yet, the duration is not known before a call is performed. Also, after the end of the call y is obviously known. Thus, this input should only be included for benchmark purposes and should be discarded if the intention is to have a realistic predictive model.</blockquote><p>So, I drop the <em>duration </em>column from the dataset.</p><pre>df = banking_df.copy()<br>banking_df = banking_df.drop([&#39;duration&#39;], axis=1)</pre><h4><strong>3.1 Handle the missing values</strong></h4><p>There are no null values in the dataset (fig 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*qOzKElQ7uFyLgh4h-oZD3w.png" /><figcaption>fig 2. (no null values in the dataset)</figcaption></figure><h4>3.2 Remove duplicates</h4><pre># drop the duplicates</pre><pre>dups = df.duplicated()<br>print(&#39;before are there any duplicates : &#39;, dups.any())<br>df.drop_duplicates(inplace=True)</pre><pre># reset indices after dropping rows<br>df=df.reset_index(drop=True)</pre><pre>print(&#39;after are there any duplicates : &#39;, df.duplicated().any())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*DsRBCq7VbWr4RDjf3aESZQ.png" /><figcaption>fig 3. (remove the duplicates)</figcaption></figure><h4>3.3 Handle the outliers</h4><p>When we are working only with the continuous features to handle the outliers.</p><pre>import scipy.stats as stats<br>import matplotlib.pyplot as plt</pre><pre>cols = [&#39;age&#39;, &#39;campaign&#39;, &#39;emp_var_rate&#39;, &#39;cons_price_idx&#39;, &#39;cons_conf_idx&#39;, &#39;euribor3m&#39;,&#39;nr_employed&#39;]</pre><pre>for col in cols: <br>    fig, axes = plt.subplots(nrows=1,ncols=3, figsize=(15, 4))<br>    fig.suptitle(col)<br>    axes[0].boxplot(df[col])<br>    axes[1].hist(df[col])<br>    stats.probplot(df[col], dist=&#39;norm&#39;, plot=axes[2])<br>    plt.show()</pre><p>The age lies between 17 and the 98. However, we can see some data points act like the outliers. However, the age contextually ok in this range. So, no need to remove these data point as the outliers in the age (fig 4).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cIn2DpZ58zJkOrhc4peKDw.png" /><figcaption>fig. 4 (age’s boxplot, histogram and probability plot)</figcaption></figure><p>The <em>emp_var_rate</em>, <em>cons_price_idx</em>, <em>euribor3m </em>and <em>nr_employed </em>have no outliers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*X5pWJjPN5Hj-5kOq-lCXVA.png" /><figcaption>fig. 5 ( <em>emp_var_rate</em>, <em>cons_price_idx</em>, <em>euribor3m </em>and <em>nr_employed — </em>boxplot, histogram and probability plot)</figcaption></figure><p>In the <em>campaign </em>we can identify the outliers and let’s remove them (fig. 6).</p><pre># remove outlier of campaign</pre><pre>fig, axes = plt.subplots(1,2)</pre><pre>df2 = df</pre><pre>col=&#39;campaign&#39;</pre><pre>print(&quot;Before Shape:&quot;,df2.shape)<br>axes[0].title.set_text(&quot;Before&quot;)<br>sns.boxplot(df2[col],orient=&#39;v&#39;,ax=axes[0])</pre><pre># Removing campaign above 50 <br>df2 = df2[ (df2[col]&lt;50)]<br>print(&quot;After Shape:&quot;,df2.shape)</pre><pre>axes[1].title.set_text(&quot;After&quot;)<br>sns.boxplot(df2[col],orient=&#39;v&#39;,ax=axes[1])<br>df=df2;<br>plt.show()</pre><pre># reset indices after dropping rows<br>df=df.reset_index(drop=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*_XZSdpxZvQJYahSG8hA0VA.png" /><figcaption>fig. 6 (before and after removing the outliers from campaign)</figcaption></figure><p>Also, in the <em>cons_conf_idx </em>we can identify the outliers and let’s remove them.</p><pre># remove outlier of cons_price_idx</pre><pre>fig, axes = plt.subplots(1,2)<br>plt.tight_layout(0.2)</pre><pre>df2 = df</pre><pre>col=&#39;cons_conf_idx&#39;</pre><pre>print(&quot;Before Shape:&quot;,df2.shape)<br>axes[0].title.set_text(&quot;Before&quot;)<br>sns.boxplot(df2[col],orient=&#39;v&#39;,ax=axes[0])</pre><pre># Removing cons_price_idx above -28 <br>df2 = df2[ (df2[col]&lt;-28)]<br>print(&quot;After Shape:&quot;,df2.shape)</pre><pre>axes[1].title.set_text(&quot;After&quot;)<br>sns.boxplot(df2[col],orient=&#39;v&#39;,ax=axes[1])<br>df=df2;<br>plt.show()</pre><pre># reset indices after dropping rows<br>df=df.reset_index(drop=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*yZueKhttgElFJBJY3YFyeg.png" /><figcaption>fig. 7 (before and after removing the outliers from <em>cons_conf_idx</em>)</figcaption></figure><h4>3.4 Feature encoding</h4><p>There are both numerical and categorical features in the dataset. So, categorical variables cannot be handled without encoding. The solution is the feature encoding.</p><p>Let’s check how many categorical features (fig. 8),</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*ZExyHvJtHJwxoDW045h2IA.png" /><figcaption>fig. 8 (categorical features)</figcaption></figure><p>Here we can see the contact only two unique values (fig 9). So, they can be simply label encoded since only 2 values that need to represent by numerical values.</p><pre>df[&#39;contact&#39;] = df[&#39;contact&#39;].astype(&#39;category&#39;).cat.codes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*EBT84woNEfSgN6QCYDPZrQ.png" /><figcaption>fig. 9(contact has only 2 unique values)</figcaption></figure><p>Then the f<em>eatures job, marital, education, default, housing, loan, month, day_of_week, and poutcome</em> are used the one-hot encoding since they have more than 2 unique values.</p><pre>from sklearn.preprocessing import OneHotEncoder<br>encoder=OneHotEncoder(sparse=False)</pre><pre>columns = [&#39;job&#39;,&#39;marital&#39;,&#39;education&#39;,&#39;default&#39;,&#39;housing&#39;,&#39;loan&#39;,&#39;month&#39;,&#39;day_of_week&#39;,&#39;poutcome&#39;]</pre><pre>df_encoded = pd.DataFrame (encoder.fit_transform(df[columns]))</pre><pre>df_encoded.columns = encoder.get_feature_names(columns)<br>df.drop(columns ,axis=1, inplace=True)</pre><pre>df= pd.concat([df, df_encoded ], axis=1)</pre><p>Here, I divide first nine columns to continuous features and rest into the categorical features. It helps to future when work with only continues features.</p><h4><strong>3.5 Data transformation</strong></h4><p><em>age, campaign and previous are right skewed </em>and <em>nr_employed </em>is left skewed (fig. 10).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dDsYR0nPq4OVYPjkXG0tEA.png" /><figcaption>fig. 10 (histogram of <em>age, campaign, previous and nr_employed</em>)</figcaption></figure><p>Therefore, to reduce the skewness and come to normal distribution form, the <em>age, campaign and previous </em>are applied log transformation.</p><pre>#Do the logarithm trasnformations for required features<br>from sklearn.preprocessing import FunctionTransformer</pre><pre>logarithm_transformer = FunctionTransformer(np.log1p, validate=True)</pre><pre># apply the transformation to your data<br>columns = [&#39;age&#39;, &#39;campaign&#39;, &#39;previous&#39;]<br>to_right_skewed = logarithm_transformer.transform(df[columns])</pre><pre>df[&#39;age&#39;] = to_right_skewed[:, 0]<br>df[&#39;campaign&#39;] = to_right_skewed[:, 1]<br>df[&#39;previous&#39;] = to_right_skewed[:, 2]</pre><p><em>nr_employed </em>is applied x² transformation.</p><pre>columns = [&#39;nr_employed&#39;]<br>exp_transformer = FunctionTransformer(lambda x:x**2, validate=True) # FunctionTransformer(np.exp, validate=True) #<br>to_left_skewed = exp_transformer.transform(df[columns])<br>df[&#39;nr_employed&#39;] = to_left_skewed[:, 0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MNEfew9fEQ6CwAiMDugbdQ.png" /><figcaption>fig. 10 (histogram of <em>age, campaign, previous and nr_employed after transformation</em>)</figcaption></figure><h4><strong>3.6 Variable Discretization</strong></h4><p>Variable Discretization transforms the continuous variables into discrete variables. There are mainly 3 discretization approaches named Supervised, Unsupervised and Custom discretization.</p><p>Here we use an unsupervised approach named k-means clustering to the continuous variables then each cluster is considered as a bin. Here I used 10 bins for the feature <em>age</em>.</p><pre>from sklearn.preprocessing import KBinsDiscretizer</pre><pre>data = pd.DataFrame(df, columns=[&#39;age&#39;])</pre><pre># fit the scaler to the  data<br>discretizer = KBinsDiscretizer(n_bins=10, encode=&#39;ordinal&#39;, strategy=&#39;kmeans&#39;) <br>discretizer.fit(data)<br>_discretize = discretizer.transform(data)<br>x = pd.DataFrame(_discretize, columns=[&#39;age&#39;])<br>df[&#39;age&#39;] = x[&#39;age&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*eGe3Rn5Fn7fOyTqyq1s1oQ.png" /><figcaption>fig. 11 (age before discretization)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*WfOoPNscDAMCv66pUWLF1g.png" /><figcaption>fig. 12 (age after discretization)</figcaption></figure><h4>3.7 Feature Scaling</h4><p>Feature scaling Standardization methods enable the normalizing the range of values of independent variables. The standard standardization and s min max standardization methods can be identified as standardization methods.</p><p>Here, I used the standard standardization method to Feature scaling. standardization sets 0 as mean (μ) and standard deviation (σ) as 1.</p><p>It is important to removing categorical features before the standardization. Also, the age is not standardized since it is discretized.</p><pre>from sklearn.preprocessing import StandardScaler</pre><pre>df2 = df</pre><pre># Removing Categorical Features before the feature scaling<br>columns = df.columns<br># Continous col<br>columns_cont = np.delete(columns,np.s_[9:])<br># Categorical col<br>columns_categorical = np.delete(columns,np.s_[0:9])</pre><pre># except age since it is discretized<br>except_age_cont = np.delete(columns_cont, [0])</pre><pre># Applying Standardization <br># Init StandardScaler<br>scaler = StandardScaler()</pre><pre>#Transformation of training dataset features<br>Except = pd.DataFrame(df, columns = except_age_cont)<br>scaler.fit(Except)</pre><pre>df = pd.DataFrame(scaler.transform(Except), columns = except_age_cont).join(df[columns_categorical])<br>df = df.join(df2[&#39;age&#39;])</pre><pre># Get age in last column to first column<br>cols = list(df.columns)<br>cols = [cols[-1]] + cols[:-1]  #make last column first<br>df=df[cols]</pre><h4><strong>3.8 Splitting the dataset</strong></h4><p>In here dataset is divided in to 2 parts as training dataset and testing dataset. Here, I use 80 presents as training and 20 presents for testing.</p><p>Also, the dataset also divided as independent variables and target dataset because our aim to predict the Apparent Temperature. So, ‘y’ is the target dataset and rest of features are taken as independent variables (fig 13).</p><pre>from sklearn.model_selection import train_test_split</pre><pre># set apparent temperature as target<br>columns_value = df.columns<br>index = np.argwhere(columns_value == &#39;y&#39;)<br>columns_value_new = np.delete(columns_value, index)</pre><pre>data = pd.DataFrame(df, columns=columns_value_new)</pre><pre># target as Y<br>selected_columns = [&#39;y&#39;]<br>y_true = df[selected_columns].copy()</pre><pre># X as indipendent <br>X = data</pre><pre># create training and testing vars<br>X_train, X_test, y_train, y_test = train_test_split(X, y_true, test_size=0.2)<br>print(X_train.shape, y_train.shape)<br>print(X_test.shape, y_test.shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O02Cp_vgWVzFIHrcFSAB8A.png" /><figcaption>fig 13. (X_train and y_train after split the dataset)</figcaption></figure><h4>4. Feature Engineering</h4><p>Feature extraction is the process of dimensionality reduction that identifies important features of the data using the domain knowledge. It helps to only include relevant inputs to machine learning model. More features may lead to a decline in the accuracy, if they include irrelevant features creating the unrequired noise in model.</p><p>We identify significant and independent features by using correlation metrix and use PCA to feature reduction.</p><h4>4.1 Correlation matrix</h4><p>Correlation matrix represents the correlations between pairs of variables. it lies bet ween -1 and +1. minus values say that there are negative correlation and positive values says that there is positive correlation.</p><p><em>r&lt;0.3 None or very weak</em></p><p><em>0.3 ≤r&lt;0.5 Weak</em></p><p><em>0.5≤r&lt;0.7 Moderate</em></p><p><em>1≤r≤0.7 Strong</em></p><p>Here, we consider only the continuous features. According to the heatmap in the dataset we can conclude that,</p><blockquote><strong>nr_employed, euribor3m, emp_var_rate and emp_pricce_idx are depend each other.</strong></blockquote><blockquote><strong>The age, campaign, cons_conf_idx, pdays, previous are independent.</strong></blockquote><pre>#correlation matrix</pre><pre>df_for_feature_eng = df[columns_cont]<br>plt.figure(figsize=(16, 16))<br># Set the range of values to be displayed on the colormap from -1 to 1, and set the annotation to True to display the correlation values on the heatmap.<br>plt.figure(figsize=(16, 6))<br>heatmap = sns.heatmap(df_for_feature_eng.corr(), vmin=-1, vmax=1, annot=True)<br># Give a title to the heatmap. Pad defines the distance of the title from the top of the heatmap.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2w5RQbNsYEB1_z3oylB3Hw.png" /><figcaption>fig 14. (Heat map for in continuous features)</figcaption></figure><p>Let’s compare the features with the target variable (fig15).</p><pre>#correlation matrix</pre><pre>df_for_feature_eng = df[columns_cont]<br>df_for_feature_eng= df_for_feature_eng.join(df[&#39;y&#39;])<br>plt.figure(figsize=(16, 16))<br># Set the range of values to be displayed on the colormap from -1 to 1, and set the annotation to True to display the correlation values on the heatmap.<br>plt.figure(figsize=(16, 6))<br>heatmap = sns.heatmap(df_for_feature_eng.corr(), vmin=-1, vmax=1, annot=True)<br># Give a title to the heatmap. Pad defines the distance of the title from the top of the heatmap.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LMh1T5EXs2ttHtzoYHuiZw.png" /><figcaption>fig 15. (Heat map for in continuous features and target)</figcaption></figure><p>Using the heatmap, we cannot get clear idea about the features’ correlation with the target, since there are no variables with strong or moderate correlation with the target. However, the <em>nr_employed </em>and <strong><em>euribor3m </em></strong>have weak correlation with target. Also, these are depending with other features also.</p><blockquote>So, I decide to to keep <strong><em>nr_employed </em></strong>and drop the <strong><em>euribor3m, emp_var_rate and emp_pricce_idx </em></strong>since they are depended each other.</blockquote><pre># drop emp.var.rate, cons.price.idx ,euribor3m</pre><pre>X_train = X_train.drop(&#39;emp_var_rate&#39;, 1)<br>X_train = X_train.drop(&#39;cons_price_idx&#39;, 1)<br>X_train = X_train.drop(&#39;euribor3m&#39;, 1)</pre><pre>X_test = X_test.drop(&#39;emp_var_rate&#39;, 1)<br>X_test = X_test.drop(&#39;cons_price_idx&#39;, 1)<br>X_test = X_test.drop(&#39;euribor3m&#39;, 1)</pre><p>In the next step we try to feature reduction using the PCA.</p><h4>4.2 Principle Component Analysis (PCA)</h4><p>With the categorical features there are 57 features to predict the target. However, with the increasing the features of the model, if becomes more complex and leads to overfit.</p><p>PCA is used commonly as Feature extraction technique to reduce the dimensions of the dataset. It is an unsupervised statical technique that use to identify the interrelation between the features.</p><p>By using the attribute <strong>explained_variance_ratio_ </strong>the variance first principal components contain up to 95% are taken to the model training.</p><p>The training model takes 25 components contain 95% of the information (fig. 16).</p><pre>from sklearn.decomposition import PCA</pre><pre># see explained variance ratios<br>pca = PCA()<br>pca.fit(X_train)</pre><pre>pca.explained_variance_ratio_</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*M2doXXJfo8yivNdp8eZEiw.png" /><figcaption>fig. 16 (pace.explained_variance_ratio_ )</figcaption></figure><pre>pca = PCA(n_components = 25)<br>pca.fit(X_train)<br>X_train_pca = pca.transform(X_train)<br>X_test_pca = pca.transform(X_test)</pre><h4>5. Train the model</h4><p>The next step is trained the implemented model. Here, I use the Support Vector Machine (SVM) to implement the model.</p><h4>Support Vector Machine (SVM)</h4><p>SVM is a supervised (y is categorical) machine learning algorithm and it is used to the classification models. The model performs better with limited numbers of data and faster compared to neural network models. The SVM works with binary classification as well as the multi class classification. In here, we discuss about the binary classification. Also, it performs both linear and nonlinear data.</p><p>In the binary classification, if it can be drawn a line (hyperplane) to separate the data points into two the classes and the data point belongs to one class in each side, then it is known as linearly separable. For an example feature X and Y with two classes (blue, red) lie in 2-dimentional vector space as follows. Here, we can identify many hyperplanes to separates the data points. Therefore, we must choose the optimal hyperplane. The optimal hyperplane is given, when we choose the hyperplane with the maximum margin distance to the opposite data points. Here, the data point that support to find optimal hyperplane are known as support vectors (fig. 16).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hb9KVPaRQxG-ic-yDMjbhQ.png" /><figcaption>fig. 16 (SVC representation in 2-dimentional vector space)</figcaption></figure><p>The <strong><em>kernel trick</em></strong> is used, when we apply the linear classifier to the non-linear data points. Here, the non-linear data points are mapped to a higher dimension that can be linearly separable. For an example feature X and Y which are non-linearly separable in 2-dimnesion vector space. Then it is created a new dimension (Z) and now can be used the linearly separable (fig. 18).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rQ3aWZuG1WQqiNnsQmatXw.png" /><figcaption>fig. 17 (using the kernel trick to non-linear data points)</figcaption></figure><pre>#Import svm model<br>from sklearn import svm</pre><pre>#Create a svm Classifier<br>#gamma: Kernel coefficient for ‘rbf’, ‘poly’ and ‘sigmoid’. Higher the value of gamma, will try to exact fit the as per training data set i.e. generalization error and cause over-fitting problem.<br>clf = svm.SVC(kernel=&#39;rbf&#39;, gamma=1)</pre><pre>#Train the model using the training sets<br>clf.fit(X_train_pca, y_train)</pre><pre>#Predict the response for test dataset<br>y_pred = clf.predict(X_test_pca)</pre><h4>6. Model evaluation</h4><p>The model gives 89% higher accuracy (fig. 18), but we cannot satisfy only the accuracy value since the target variable is highly imbalanced (fig. 29).</p><pre>#Import scikit-learn metrics module for accuracy calculation<br>from sklearn import metrics</pre><pre># Model Accuracy: how often is the classifier correct?<br>print(&quot;Accuracy:&quot;,metrics.accuracy_score(y_test, y_pred))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*0e079OUOU_DvSDWF6C1Czg.png" /><figcaption>fig. 18 (model accuracy)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*PgN71PKN-o4X18gY-NEPew.png" /><figcaption>fig. 19(target variable (y) is highly imbalanced)</figcaption></figure><p>So, let’s try to evaluate the performance of the model using the confusion matrix.</p><h4>Confusion matrix</h4><p>Confusion matrix has 4 combinations of actual and predicted values (fig. 21). Let’s discuss it using an example. A model predicts the Tsunami occurrence.</p><p>1. <strong>TP </strong>: There is a Tsunami and model also predicted there is a Tsunami.</p><p>2. <strong>TN </strong>: There is no Tsunami and model also predicted there is no Tsunami.</p><p>3. <strong>FP </strong>: There is no Tsunami, but model predicted there is a Tsunami.</p><p>4. <strong>FN</strong> : There is a Tsunami, but model predicted there is no Tsunami.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*8YRu9e0tu5LRkFWKfTijLg.png" /><figcaption>fig. 20 (confusion matrix)</figcaption></figure><p><strong><em>Recall</em></strong>: number of correctly predicted as Positive (1), out of the Actually positive (1) class.</p><p><strong><em>Precision</em></strong>: number of correctly predicted as Positive (1), out of the predicted as positive (1) class.</p><p><strong><em>Accuracy</em></strong>: number of correctly predicted, out of the all the classes.</p><pre>cm = metrics.confusion_matrix(y_test, y_pred)<br>plt.figure(figsize = (8,8))<br>fig, ax = plt.subplots(1)<br>ax = sns.heatmap(cm, ax=ax, annot=True) #normalize=&#39;all&#39;<br>plt.title(&#39;Confusion matrix&#39;)<br>plt.ylabel(&#39;True category&#39;)<br>plt.xlabel(&#39;Predicted category&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*yaCduzxZ339Xsel0WPxD_g.png" /><figcaption>fig. 21 (confusion matrix)</figcaption></figure><p>The model is not much performed well since the <strong><em>Recall</em></strong> value is less. Also we can interpret it using the confusion matrix.</p><p>Out of the actually data points labeled as 1(TP + FN), the model predicated more data point as 0 (FN). So,<strong><em> it can be concluded that model not perform well (fig. 22)</em></strong>.</p><pre>print(&quot;Precision : &quot;, metrics.precision_score(y_test, y_pred))<br>print(&quot;Recall : &quot;, metrics.recall_score(y_test, y_pred))<br>print(&quot;f1_score:&quot;, metrics.f1_score(y_test, y_pred, average=&quot;macro&quot;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*8RR5QCkKDKg_2qNLBnknwg.png" /><figcaption>fig. 22</figcaption></figure><p><strong>Recommended</strong></p><p>As a solution we can recommend to balance the target class, before train the model. If you are going to balance the imbalance classes, the <a href="https://www.analyticsvidhya.com/blog/2020/10/overcoming-class-imbalance-using-smote-techniques/">SMOTE </a>is recommended for you. <strong>SMOTE </strong>uses the oversampling methods to balance the imbalance classes.</p><p>The SMOTE technique is used only for the training dataset.</p><pre>from sklearn.model_selection import train_test_split<br>from imblearn.over_sampling import SMOTE</pre><pre># create training and testing vars<br>X_train, X_test, y_train, y_test = train_test_split(X, y_true, test_size=0.3, random_state = 100)</pre><pre>smt = SMOTE(random_state = 101)<br>X_train, y_train = smt.fit_resample(X_train, y_train)</pre><pre>print(X_train.shape, y_train.shape)<br>print(X_test.shape, y_test.shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*5adA3rFZAHGtP-U9AkYhNg.png" /><figcaption>fig. 23 (After apply SMOTE to train data set)</figcaption></figure><p>After apply SMOTE, 23 features are taken to model train (fig. 24).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vRPymaUnMwFicTO1nOI-Ow.png" /><figcaption>fig. 24 (After apply SMOTE, 23 features are taken to model train)</figcaption></figure><p>Then train the model again.</p><pre>#Import svm model<br>from sklearn import svm</pre><pre>#Create a svm Classifier<br>#gamma: Kernel coefficient for ‘rbf’, ‘poly’ and ‘sigmoid’.<br>clf = svm.SVC(kernel=&#39;rbf&#39;,  gamma=0.001, C=100)</pre><pre>#Train the model using the training sets<br>clf.fit(X_train_pca, y_train)</pre><pre>#Predict the response for test dataset<br>y_pred = clf.predict(X_test_pca)</pre><p><strong><em>Gamma </em></strong>decides curvature of the decision boundary. Higher the value of gamma generalizes the error and cause over-fitting problem. <strong><em>C</em> </strong>adds a penalty for each misclassified data point.</p><p>Then dataset is trained gain and the accuracy of the model is 83%. It shows that the accuracy score of the model is reduced (fig. 25).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*gkMykMNn3lTNhFjlUoy5xA.png" /><figcaption>fig. 25 (model accuracy score after SMOTE)</figcaption></figure><p>However the confusion matrix shows that there is some improvement of the model (fig. 26). However, the <strong><em>recall </em></strong>is improved (62%). but, <strong><em>precision </em>is getting low.</strong> It means that,</p><p><strong><em>when 100 data points predicted as 1, only the 37 are correctly predicted.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*3BzwRU5i67hyDuFU8KkEOg.png" /><figcaption>fig. 26 (confusion matrix after apply SMOTE to model)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*MLJTxqUFdUum2d28Nv8TTA.png" /><figcaption>fig. 27 (classification report of the model)</figcaption></figure><h4><strong>Conclusion</strong></h4><p>In this article we implemented a machine learning classification model regarding to a specific problem domain. Here, we discussed that how to do preprocess process techniques to the dataset and then use Support Vector Classification to implement the model. Finally we evaluate the model performance with the confession matrix. You can access the complete notebook from <a href="https://github.com/KuWathsala/ml-classification-model-bank-marketing">here</a>.</p><p><a href="https://github.com/KuWathsala/ml-classification-model-bank-marketing">KuWathsala/ml-classification-model-bank-marketing</a></p><h4>Reference</h4><ul><li><a href="https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html">SVC</a></li><li><a href="https://www.analyticsvidhya.com/blog/2017/09/understaing-support-vector-machine-example-code/">Learn How to Use Support Vector Machines (SVM) for Data Science</a></li><li><a href="https://www.analyticsvidhya.com/blog/2020/10/overcoming-class-imbalance-using-smote-techniques/">SMOTE for Imbalanced Classification with Python</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4795377e3c05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Use Cases for reduce() in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/5-use-cases-for-reduce-in-javascript-61ed243b8fef?source=rss-de61b3afaa03------2</link>
            <guid isPermaLink="false">https://medium.com/p/61ed243b8fef</guid>
            <category><![CDATA[software]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[wathsala danthasinghe]]></dc:creator>
            <pubDate>Fri, 10 Jul 2020 16:21:52 GMT</pubDate>
            <atom:updated>2020-07-10T16:21:52.952Z</atom:updated>
            <content:encoded><![CDATA[<h4>An introduction to JavaScript array reduce() and its use cases.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OMc9i1Q7b5ud4sHF" /><figcaption>Photo by <a href="https://unsplash.com/@goshua13?utm_source=medium&amp;utm_medium=referral">Joshua Aragon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><em>The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value. </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce"><em>source</em></a></blockquote><p>The reduce() method reduces all the elements in an array into a single output value. The output value can be a number, object, or string. reduce() method has two arguments. The first one is a <strong>callback function </strong>and the second one is the <strong>initial value</strong>.</p><h4><strong>Callback function</strong></h4><p>The callback function is executed on each element of the array. The return value of the callback function is accumulated result and provided as an argument in the next call to the callback function. The callback function takes four arguments.</p><p><strong><em>Accumulator</em></strong><br>The accumulator accumulates return value of the callback function.</p><p><strong><em>Current Value</em></strong><br>The current element of the array is processed.</p><p><strong><em>Current Index</em></strong><br>The index of the current element of the array is processed.</p><p><strong><em>Source Array</em></strong><br>The array reduce() was called upon.</p><p>The <strong>Current Index </strong>and <strong>Source Array </strong>are optional.</p><h4><strong>Initial value</strong></h4><p>If the initial value is specified, the accumulator is set initialValue as the initial element. Otherwise, the accumulator is set as the first element of the array as the initial element.</p><pre>arr.reduce(callback(accumulator, currentValue[,index[,array]])[, initialValue])</pre><p>In the below code fragment, first accumulator is assigned the initial value 0. The currentValue is the element of the numbersArr array being processed. Here, currentValue is added to the accumulator. The return value is provided as an argument in the next call to the callback function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d723480e1a6d28f5a7ea9e0443b34eb/href">https://medium.com/media/9d723480e1a6d28f5a7ea9e0443b34eb/href</a></iframe><p>Output:</p><pre>accumulator is 0 current value is 67<br>accumulator is 67 current value is 90<br>accumulator is 157 current value is 100<br>accumulator is 257 current value is 37<br>accumulator is 294 current value is 60<br>total : 354</pre><h3><strong>Use Cases for JavaScript reduce</strong></h3><h4><strong>1. Sum all the values of an array</strong></h4><p>In the below code, studentResult array has 5 numbers. Using the reduce() method array is reduced to a single value that the sum of all values of the studentResult array and the result is assigned to the total.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94145f20e2c5c743ae2d5a627e496a6c/href">https://medium.com/media/94145f20e2c5c743ae2d5a627e496a6c/href</a></iframe><p>Output:</p><pre>354</pre><h4><strong>2. Sum of values in an object array</strong></h4><p>Generally, we are fetching data from the back-end as object arrays. Therefore, the reduce() method helps to manage our front-end logic. In the below code, studentResult object array has three subjects with their marks as objects. Here, currentValue.marks take the marks of each subject in the studentResult object array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dfd321f7ab210778f4d780681a6fbe2/href">https://medium.com/media/5dfd321f7ab210778f4d780681a6fbe2/href</a></iframe><p>Output:</p><pre>251</pre><h4><strong>3. Flatten an array of arrays</strong></h4><p>“Flatten an array” means the transformation of the multi-dimensional array into one dimension. In the below code, twoDArr 2D array is transformed into oneDArr one dimensional array. Here, the first [1,2] array is assigned to the accumulator and then each rest of the elements of the twoDArr array is concatenated to the accumulator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77d87c1e562bedd512b1f440fc13b496/href">https://medium.com/media/77d87c1e562bedd512b1f440fc13b496/href</a></iframe><p>Output:</p><pre>[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]</pre><h4><strong>4. Grouping objects by a property</strong></h4><p>Based on the properties of an object, we can group the object array into several groups using the reduce() method. You can understand the idea clearly with the below code fragment. Here, result object array has five objects that each object has subject and marks properties. The subject is passed if marks are greater than or equal to 50. Otherwise the subject fails. reduce() is used to group the result into the pass and fail. First initialValue is assigned to the accumulator, then push() method adds current object to the pass and the fail properties as object arrays after checking the condition.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c970cfead94f9204b2c8eab2fbb8016/href">https://medium.com/media/5c970cfead94f9204b2c8eab2fbb8016/href</a></iframe><p>Output:</p><pre>{<br> pass: [<br>  { subject: ‘Chemistry’, marks: 59 },<br>  { subject: ‘Applied Maths’, marks: 90 },<br>  { subject: ‘English’, marks: 64 }<br> ],<br> fail: [<br>  { subject: ‘Physics’, marks: 41 },<br>  { subject: ‘Pure Maths’, marks: 36 }<br> ]<br>}</pre><h4><strong>5. Remove duplicates in an array</strong></h4><p>In the below code fragment, duplicates in the duplicatedArr array are removed. First, an empty array is assigned to the accumulator as initial value. accumulator.includes() checks whether each element of the duplicatedArr array is already available in the accumulator. If the currentValue is not available in the accumulator, it is added using the push().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/997f702baa32e66cf4081a0f9c6a0277/href">https://medium.com/media/997f702baa32e66cf4081a0f9c6a0277/href</a></iframe><p>Output:</p><pre>[ 1, 5, 6, 7, 8, 9 ]</pre><h4><strong>Conclusion</strong></h4><p>In this article, we discuss about the array reduce() method. First,reduce() method is introduced. Then, its behavior is discussed using a simple example. Finally, the most common five use cases of the reduce() method is discussed with the examples. If you are a beginner to the JavaScript, this article will be helpful to you.</p><h4><strong>Reference</strong></h4><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce">Array.prototype.reduce() - JavaScript | MDN</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61ed243b8fef" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/5-use-cases-for-reduce-in-javascript-61ed243b8fef">5 Use Cases for reduce() in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[7 Use Cases for Destructuring in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/7-use-cases-for-destructuring-in-javascript-4c8a73b28855?source=rss-de61b3afaa03------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c8a73b28855</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[destructuring-assignment]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[wathsala danthasinghe]]></dc:creator>
            <pubDate>Sat, 04 Jul 2020 09:37:34 GMT</pubDate>
            <atom:updated>2020-07-04T09:37:34.413Z</atom:updated>
            <content:encoded><![CDATA[<h4>An introduction to array and object destructuring in JavaScript and its use cases</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ABcdikPi61fWoxL0" /><figcaption>Photo by <a href="https://unsplash.com/@sapegin?utm_source=medium&amp;utm_medium=referral">Artem Sapegin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>“The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables”. </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment"><em>MDN</em></a></p><p>Destructuring assignment helps to build your code fragments in clear and easier manner. It unpacks individual values from arrays or properties from objects and assigns them into distinct variables. Simply, it takes an object or an array and convert them into smaller objects elements or variables. There are two types of destructuring in JavaScript.</p><p><em>Array destructuring </em><br> <em>Object destructuring</em></p><h3><strong>1. Array destructuring</strong></h3><p>Array destructuring allows to take the individual elements from an array and assign them into individual variables. Let’s discuss with an example. The days of the week are set to the <strong><em>week </em></strong>array.</p><pre>const week = [‘monday’, ‘tuesday’, ‘wednesday’, ‘thuresday’, ‘friday’];</pre><p>Without destructuring assignment, you might access the items in an array like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c089046c2cbc796702047173a3a38b65/href">https://medium.com/media/c089046c2cbc796702047173a3a38b65/href</a></iframe><p>Now, Let’s do it with destructuring assignment. Here, <strong><em>week </em></strong>(array you want to destructuring) is put to the right side to the equal(=) and <strong><em>day1, day2, day3, day4, day5</em></strong><em> </em>variables are assigned each value in the<em> </em><strong><em>week </em></strong>array. <strong><em>[]</em></strong> is used to destructure the array. single line of code to assign each value of the array week</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ce036518f41cc31bff5d40e7ca00185/href">https://medium.com/media/2ce036518f41cc31bff5d40e7ca00185/href</a></iframe><h3><strong>2. Object destructuring</strong></h3><p>Object destructuring allows to take the individual properties from an object and assigns them into smaller objects elements or individual variables. <strong><em>{}</em></strong> is used to destructure the objects. Here, we must ensure the property name is same as the variable name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06265a8deac0f6b18fa49600582366aa/href">https://medium.com/media/06265a8deac0f6b18fa49600582366aa/href</a></iframe><h3><strong>3. Use cases of destructuring assignment</strong></h3><h4><strong>3.1 Combine an array with another array</strong></h4><p>Combine two arrays is commonly used when we are coding. Destructuring assignument can be used to combine an array at any place with another array. In the example, array <strong><em>weekDays </em></strong>is added to the beginning of the <strong><em>week </em></strong>array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af8591f0956af10753b9dc8f5ea3fff0/href">https://medium.com/media/af8591f0956af10753b9dc8f5ea3fff0/href</a></iframe><h4><strong>3.2 Combine two objects</strong></h4><p>Object destructuring can be used to combine two different objects. In this example, both <strong><em>studentDetails </em></strong>and <strong><em>studentGrade </em></strong>objects’ properties are copies to the <strong><em>studentResult </em></strong>object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cf2d3460d12a58103eb232f7ddd8422/href">https://medium.com/media/8cf2d3460d12a58103eb232f7ddd8422/href</a></iframe><p>Output:</p><pre>{ name: ‘John’, age: 20, subject: ‘Physics’, grade: ‘A’ }</pre><p>Note that there is a same property in both objects which going to combine, the second object’s property value is over written. In this example, name property is available both objects. Therefore, the <strong><em>StudentGrade </em></strong>object name value <strong><em>‘John Mary’</em></strong> is the value of the <strong><em>name </em></strong>in <strong><em>StudentResult</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/226dc792d3a1aaad61685fd204c4e798/href">https://medium.com/media/226dc792d3a1aaad61685fd204c4e798/href</a></iframe><p>Output:</p><pre>{ name: ‘John Mary’, age: 20, subject: ‘Physics’, grade: ‘A’ }</pre><h4><strong>3.3 Function parameters destructuring</strong></h4><p>Function’s parameter destructuring helps to prevent passing unnecessary properties in the objects to the function. Let’s clear this idea with an example. In the bellow code, <strong><em>studentDetails</em></strong> object is passed to the <strong><em>printName() </em></strong>function. But only <strong><em>firstName </em></strong>and <strong><em>lastName </em></strong>is used inside the function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7121ee44b681d3be7705f447538a1284/href">https://medium.com/media/7121ee44b681d3be7705f447538a1284/href</a></iframe><p>Using the destructuring, we can take only necessary properties as an object into the function. This is very helpful, when we deal with large objects. In the bellow code, the only <strong><em>firstName </em></strong>and <strong><em>lastName </em></strong>properties’ values are input to the <strong><em>printName()</em></strong> function as standalone variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85ce96669b4665e2957ef8cd53c61416/href">https://medium.com/media/85ce96669b4665e2957ef8cd53c61416/href</a></iframe><p>Output:</p><pre>Full name is John Mary</pre><h4><strong>3.4 Convert array into object</strong></h4><p>In this example, <strong><em>birthDayArr </em></strong>array is converted into <strong><em>birthDayObj </em></strong>object. Here, <strong><em>birthDayArr </em></strong>is destructured into <strong><em>year</em></strong>, <strong><em>month</em>,<em> day </em></strong>and works as input parameters of the <strong><em>arrayConvertToObj </em></strong>function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/faac434051e91f3f436d52dbe247979d/href">https://medium.com/media/faac434051e91f3f436d52dbe247979d/href</a></iframe><p>Output:</p><pre>{ year: 2000, month: 1, day: 1}</pre><h4><strong>3.5 Skipping Items</strong></h4><p>During the destructuring, we can skip elements from the array that we do not want to use. It helps to save unnecessarily using the memory for the variables which useless elements in the array . We can skip the elements just putting the <strong>commas</strong>(<strong><em>,</em></strong>). For an example, given numebers array, I want only third and fifth elements. therefore, skips others from putting the commas.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d6f9d0d502ad66314fb02badaceba50/href">https://medium.com/media/7d6f9d0d502ad66314fb02badaceba50/href</a></iframe><p>Output:</p><pre>3<br>5</pre><h4><strong>3.6 Rest in Object Destructuring</strong></h4><p>Rest operator helps to have single variable that contains group of elements not already picked off by the destructuring pattern. In the example, <strong><em>firstName </em></strong>and <strong><em>lastName </em></strong>properties are assigned individually and the rest of properties(<strong><em>age</em></strong>, <strong><em>country</em></strong>) are assigned to the single variable <strong><em>rest</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89593dfcda687f52cf7b8e0f4a4546e4/href">https://medium.com/media/89593dfcda687f52cf7b8e0f4a4546e4/href</a></iframe><p>Output:</p><pre>John<br>Mary<br>{ age: 20, country: ‘Sri Lanka’ }</pre><h4><strong>3.7 Assign new variables name and set default values</strong></h4><p>During the object destructuring, the property name of the object must match to the variable name. However, we can assign it to a variable with different name. Also, we can assign default value to the variable instead of <strong>undefined. </strong>In the given example, <strong><em>firstName </em></strong>vale is mapped to <strong><em>fName </em></strong>and<strong> ‘not given’ </strong>is assigned as default value instead of <strong>undefined</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5b29f727eab7bf1ef26db1bd7d6c16a/href">https://medium.com/media/b5b29f727eab7bf1ef26db1bd7d6c16a/href</a></iframe><p>Output:</p><pre>John<br>Mary</pre><h4><strong>Reference</strong></h4><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">Destructuring assignment - JavaScript | MDN</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c8a73b28855" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/7-use-cases-for-destructuring-in-javascript-4c8a73b28855">7 Use Cases for Destructuring in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 best practices for writing better React code]]></title>
            <link>https://javascript.plainenglish.io/5-best-practices-for-writing-better-react-code-f6120d94c350?source=rss-de61b3afaa03------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6120d94c350</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[wathsala danthasinghe]]></dc:creator>
            <pubDate>Fri, 26 Jun 2020 05:46:54 GMT</pubDate>
            <atom:updated>2024-12-24T16:20:29.047Z</atom:updated>
            <content:encoded><![CDATA[<h4>5 best practices that every React developer should know</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vi-F86aPZaR9BhML" /><figcaption>Photo by <a href="https://unsplash.com/@casparrubin?utm_source=medium&amp;utm_medium=referral">Caspar Camille Rubin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>React is a famous JavaScript library for building user interfaces. If you enter to develop your front end with React, this article will be helpful to you. I’m going to discuss 5 best practices to keep your code in well-organized manner.</p><h4><strong>1. Use functional components</strong></h4><p>As we know, there are two types of components in React which class components and functional components. The class components are state full that have internal state and life cycle methods. Functional components are stateless. But using <a href="https://medium.com/dev-genius/introduction-to-react-hooks-e49738432f54"><em>React Hooks</em></a><em>,</em> it can acts as a state full components. The functional components accept props as arguments and return a React elements. The advantages of functional components are less code, simpler comparing to class-based functions, stateless, no “this” binding and easy to understand.</p><pre>import React from ‘react’;</pre><pre>export default function App() {<br> return(<br>  &lt;h2&gt;Hello world&lt;/h2&gt;<br> );<br>}</pre><h4><strong>2. Use small components and separate your functionalities</strong></h4><p>React application is built with set of components. When you write small components, you can easily read and understand what is the function(activity) of this component. The re-usability of the code is also increased. When you write a code to do couple of functions(activities) in a single component, it will be hard to understand.</p><p>For an example, the App component contains the two lists of books and files. The following code print whole books list and files list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fc0ce958858dbf648274ddf108543cd/href">https://medium.com/media/7fc0ce958858dbf648274ddf108543cd/href</a></iframe><p>We can use <em>ItemsList </em>component to display the books list and the files. Therefore, the re-usability of the code is increased and clearly functions(activities) are separated to two components.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63ed4e54b2afb26d9d0901446c41e9a9/href">https://medium.com/media/63ed4e54b2afb26d9d0901446c41e9a9/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ede91fd6f4a76d7cab9d489c7678320/href">https://medium.com/media/5ede91fd6f4a76d7cab9d489c7678320/href</a></iframe><h4><strong>3. Use JavaScript destructuring to remove redundancy</strong></h4><p><em>The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment"><em>source</em></a></p><p>We pass the arguments as props from the parent component to the child component. For example, the following code, Parent component(App) send its state values to the child (Sum) component as a prop. Here, <em>props.values </em>are redundant four times.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2188ac4ef1165b209a366ed0d3e18c3/href">https://medium.com/media/d2188ac4ef1165b209a366ed0d3e18c3/href</a></iframe><p>We can use JavaScript<strong> </strong>destructing to remove redundancy of <em>props.values.</em>b by writing:</p><p><strong>const {value1, value2, value3, value4} = props.values;</strong></p><pre>function <strong>Sum</strong>(props){ <br> const {<strong>value1</strong>, <strong>value2</strong>, <strong>value3</strong>, <strong>value4</strong>} = <strong>props.values</strong>;<br> return &lt;h2&gt;sum: {<strong>value1 </strong>+ <strong>value2 </strong>+ <strong>value3 </strong>+ <strong>value4</strong>}&lt;/h2&gt;;<br>}</pre><h4><strong>4. Use prop-types library (if you’re not using TypeScript/Flow)</strong></h4><p>prop-types is a library for type checking props. It validates the type of the props. It helps to prevents bugs when passing the wrong data-type props to a component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4b42c2927d9163d07aa048a3ab50aea/href">https://medium.com/media/c4b42c2927d9163d07aa048a3ab50aea/href</a></iframe><h4><strong>5. Use React developer tools</strong></h4><p>When you develop a React project, React developer tools is very useful. It views the component hierarchy, component’s state, props, and children and it also helps to debug.</p><p><strong>Reference</strong></p><p><a href="http://reactjs.org/docs">Getting Started - React</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6120d94c350" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/5-best-practices-for-writing-better-react-code-f6120d94c350">5 best practices for writing better React code</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance optimization with React Hooks — useCallback & useMemo]]></title>
            <link>https://blog.devgenius.io/performance-optimization-with-react-hooks-usecallback-usememo-f2e527651b79?source=rss-de61b3afaa03------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2e527651b79</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[wathsala danthasinghe]]></dc:creator>
            <pubDate>Sun, 21 Jun 2020 11:49:35 GMT</pubDate>
            <atom:updated>2020-06-21T20:36:34.113Z</atom:updated>
            <content:encoded><![CDATA[<h3>Performance optimization with React Hooks — useCallback &amp; useMemo</h3><h4>An introduction to use useCallback &amp; useMemo Hooks to optimize the performance of the web applications.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uKAcWPM8CgLhuw1H" /><figcaption>Photo by <a href="https://unsplash.com/@sapegin?utm_source=medium&amp;utm_medium=referral">Artem Sapegin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article is the 3rd part of the “introduction to React Hooks” series. Up to now, I discuss about the Basic Hooks and the <em>useReducer </em>Hook in Additional Hooks.</p><p>part 1: <a href="https://medium.com/@dkwathsala/introduction-to-react-hooks-e49738432f54">Introduction to React Hooks — Basic Hooks</a><br> part 2: <a href="https://medium.com/dev-genius/introduction-to-react-hooks-usereducer-7b87a6cb4289">Introduction to React Hooks — useReducer</a></p><p>In this article, I am going to discuss <em>useCallback </em>&amp; <em>useMemo </em>Hooks and how to use them to optimize the perform of the web application with examples</p><p><strong>1.<em> useCallback</em></strong></p><p><strong>what is <em>useCallback?</em></strong></p><blockquote>Returns a <a href="https://en.wikipedia.org/wiki/Memoization">memoized</a> callback.</blockquote><p><em>useCallback </em>is a built in Hook in React is used to return a memoized version of callback function. Memoization does the remembering or caching the results of the function. Memoized version of callback only changes, if one of the dependencies has changed. The cashed result is returned when same inputs are called again. <strong>Function </strong>and a <strong>list of dependencies</strong> are the input parameters to the <em>useCallback</em>. When one of these dependencies is changed return memoized.</p><pre><strong>React</strong>.<strong>useCallback</strong>(<em>function</em>, <em>dependencies</em>)</pre><p>For example,</p><pre><strong>const </strong>memoizedCallback = <strong><em>useCallback</em></strong>(<br> () =&gt; {<br>  setValue(value);<br> },<br> [value],<br>);</pre><p><strong>Why use <em>useCallback?</em></strong></p><p><em>useCallback </em>is used to prevent unnecessary re-rendering in Parent component, when passing callbacks to the child components.</p><p><strong>2. <em>useMemo</em></strong></p><p><strong>what is <em>useMemo?</em></strong></p><blockquote>Returns a memoized value.</blockquote><p><em>useMemo </em>is a<em> </em>built in Hook in React pass a create function and array of dependencies. It helps to avoiding complex calculations.</p><p><strong>difference between <em>useCallback </em>and <em>useMemo</em></strong></p><ul><li><strong><em>useCallback </em></strong>is to memoize a callback itself (referential equality) between renders</li><li><em>useMemo </em>is to memoize a calculation result between a function’s calls and between renders</li></ul><p>when useCallback memoizes functions, useMemo memoizes any value.</p><pre><strong>const </strong>memoizedValue = <strong><em>useMemo</em></strong>(() =&gt; computeExpensiveValue(a), [a]);</pre><p><em>useCallback</em>(<em>fn</em>, <em>deps</em>) is equivalent to <em>useMemo</em>(() =&gt; <em>fn</em>, <em>deps</em>).</p><p>Now, I am going to implement an simple web application with increment counter and multiply counter. Here, I use <strong>Counter </strong>function and <strong>App </strong>function components. In the App function Component contains the both increment Counter,the multiply Counter components and their values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*lxW1Rdf90zb1Ic0CBT-dZA.jpeg" /><figcaption>Figure 1 (web application view)</figcaption></figure><p><strong>Counter.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/968dd222664e817401ae645c8c746c51/href">https://medium.com/media/968dd222664e817401ae645c8c746c51/href</a></iframe><p>Here <em>Counter </em>function components is warped <em>React.memo</em> and it will be re-rendered when state is changed. <em>React.memo</em> is a higher order component that prevents function component being re-rendered, if props or state is not changed.</p><p><strong>App.js without using <em>useCallback()</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91d4b4be8f1ce8768586048c342e503f/href">https://medium.com/media/91d4b4be8f1ce8768586048c342e503f/href</a></iframe><p>When click the <strong>increment </strong>button then change only the value of the <strong><em>incrementValue, </em></strong>So the <strong>Counter increment</strong> is re-rendered. But, here, <strong>Counter multiply </strong>also re-rendered, although <strong><em>mulValue</em></strong><em> </em>is not changed (initial value of mulValue is 2). If there is 10 components in App container, all are going to re-render. So that the <em>useCallback </em>helps to optimize the performance of the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*RM55vBNJoEFETnWXz1kHqA.jpeg" /><figcaption>Figure 4 (when click the increment both increment-counter and multiply-counter are re-rendered)</figcaption></figure><p><strong>App.js using <em>useCallback()</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aba6bcfbb23b4adb99aded3d4bc7683f/href">https://medium.com/media/aba6bcfbb23b4adb99aded3d4bc7683f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*Usqj4mRO3rn-RmowA6VAYA.jpeg" /><figcaption>Figure 4 (when click the increment only increment-counter is re-rendered)</figcaption></figure><p>Here, the <em>useCallback </em>prevents the re-render of the multiply Counter.</p><p><strong>Reference</strong></p><p><a href="https://reactjs.org/docs/hooks-reference.html">Hooks API Reference - React</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2e527651b79" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/performance-optimization-with-react-hooks-usecallback-usememo-f2e527651b79">Performance optimization with React Hooks — useCallback &amp; useMemo</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to React Hooks — useReducer]]></title>
            <link>https://blog.devgenius.io/introduction-to-react-hooks-usereducer-7b87a6cb4289?source=rss-de61b3afaa03------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b87a6cb4289</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[wathsala danthasinghe]]></dc:creator>
            <pubDate>Sat, 20 Jun 2020 12:28:43 GMT</pubDate>
            <atom:updated>2020-06-20T20:04:06.788Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to React Hooks — useReducer</h3><h4>A quick guide to build web application with React Hooks-useReducer.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NP4JkFI83ZR6jhl0" /><figcaption>Photo by <a href="https://unsplash.com/@flowforfrank?utm_source=medium&amp;utm_medium=referral">Ferenc Almasi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>React Hooks is available since React 16.8 and React Native supported since version 0.59. In my previous article is discussed about the <strong>Basic Hooks</strong> of React. If you’re new to React Hooks, click <a href="https://medium.com/dev-genius/introduction-to-react-hooks-e49738432f54"><strong>here</strong></a><strong> </strong>to read it. In this article, I am going to discuss the <em>useReducer </em>in the<em> </em>Additional Hooks on React.</p><p>There are two types of built-in Hooks in React which Basic Hooks and Additional Hooks.</p><p><strong>Basic Hooks</strong><br> <em>useState</em><br> <em>useEffect</em><br> <em>useContext</em><br><strong>Additional Hooks</strong><br> <em>useReducer</em><br> <em>useCallback<br> useMemo<br> useRef<br> useImperativeHandle<br> useLayoutEffect<br> useDebugValue</em></p><p><strong>What is useReducer?</strong></p><blockquote>An alternative to useState. Accepts a reducer of type (state, action) =&gt; newState, and returns the current state paired with a dispatch method.<a href="https://reactjs.org/docs/hooks-reference.html#usereducer">source</a></blockquote><p><em>useReducer </em>is a built in Hook in React is used to state management in React. <em>useReducer </em>is an alternative to <em>useState</em>. It is related to reducer functions. If you have clear idea about the Redux state management, then you already have enough knowledge how it works. Click <a href="https://medium.com/dev-genius/getting-started-with-react-native-redux-479fb6e37be4"><strong>here</strong></a><strong> </strong>to take clear idea about Redux.</p><p><strong>Why we use useReducer over useState?</strong></p><p><em>useState </em>is used, when state values are primitives, state values are only used in a single component inside or logic is simple.</p><p><em>useReducer </em>is used, when we have complex state like involves objects or arrays, next state is depend on previous one, data share among the components and update state more complex. <em>useReducer </em>is optimized performance for components that trigger deep updates because you can pass dispatch down instead of callbacks.</p><p>Now, I am going to implement a simple counter web application with discussing the features of the <em>useReducer.</em></p><p><strong>Step 1. define initial state and reducer function.</strong></p><p>The reducer function accept two parameters which current state and action then return one value which is the new state. a<em>ction </em>parameter <em>i</em>s given the instruction the reducer function to perform. Here, <em>INCREMENT</em>, <em>DECREMENT </em>and <em>RESET </em>are the given instructions(<em>action</em>) to the reducer function.</p><pre>const initialState = {<br> value: 0<br>}</pre><pre>const reducer = (state, action) =&gt; {<br> switch(action.type){<br>  case ‘INCREMENT’ :<br>   return {value: state.value + 1 };<br>  case ‘DECREMENT’ :<br>   return {value: state.value — 1 };<br>  case ‘RESET’ : <br>   return initialState;<br>  default:<br>   return state; <br> }<br>}</pre><p><strong>Step 2. useReducer Hook</strong></p><p>First we need to import the <em>useReducer </em>from React local state to the function component.</p><pre><strong>import </strong>React, { <strong><em>useReducer</em></strong>} from ‘react’;</pre><p><em>state</em>, <em>initializer argument </em>and the <em>initializer </em>are the input parameter to the useReducer. We can initialize <em>useReducer </em>state by two different ways.</p><p><strong>2.1 Specifying the initial state</strong></p><p>The first way is, pass the initial state as a second argument. It is the simple way. here <em>useReducer </em>accepts two arguments which <em>reducer </em>function and the initial state.</p><pre><strong>const </strong>[count, dispatch] = <strong><em>useReducer</em></strong>(reducer, initialState);</pre><p>the <em>count.value</em> print the value and it is update with the dispatch types of the action. Complete code,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35235f9314951f71030a63f81dc53afd/href">https://medium.com/media/35235f9314951f71030a63f81dc53afd/href</a></iframe><p><strong>2.2 Lazy initialization</strong></p><blockquote>React doesn’t use the state = initialState argument convention popularized by Redux. <a href="https://reactjs.org/docs/hooks-reference.html#usereducer">source</a></blockquote><p>The other way is, create the initial state lazily. In here, pass an <em>init </em>function as as the third argument. Using this way we can initial state outside the reducer. <em>useReducer </em>accepts the optional third argument to the initial action that is called during the initial render.</p><p>In the below code, I pass initial value 0 to the Counter function as a props since App function component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/634c63a470b88a8d9a7c7c48e9115aba/href">https://medium.com/media/634c63a470b88a8d9a7c7c48e9115aba/href</a></iframe><p><strong>Conclusion</strong><br>In this article, we discussed about the <em>useReducer </em>Hook, the difference between <em>useState </em>and <em>useReducer</em> and implement simple counter web application using React Hooks. I think this article will be helpful who enter to follow React Hooks.</p><p><strong>References</strong></p><p><a href="https://reactjs.org/docs/hooks-reference.html#usereducer">Hooks API Reference - React</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b87a6cb4289" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/introduction-to-react-hooks-usereducer-7b87a6cb4289">Introduction to React Hooks — useReducer</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spread operator (…) in JavaScript]]></title>
            <link>https://blog.devgenius.io/what-is-spread-operator-in-javascript-87233cd85bff?source=rss-de61b3afaa03------2</link>
            <guid isPermaLink="false">https://medium.com/p/87233cd85bff</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[spread-operator]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[wathsala danthasinghe]]></dc:creator>
            <pubDate>Thu, 11 Jun 2020 14:39:21 GMT</pubDate>
            <atom:updated>2020-06-20T07:26:49.497Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quick guide to use spread operator in JavaScript.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F61cuA-3fsvCe0zS" /><figcaption>Photo by <a href="https://unsplash.com/@emilep?utm_source=medium&amp;utm_medium=referral">Emile Perron</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When we follows JavaScript code we can see there are 3 dots (…) sometimes. What is this three dots (…). It is the spread operator in Java Script. In this article, I am going to discuss about the spread operator in JavaScript.</p><p>With the new Features of the ES6, spread operator is one of them. Let’s discuss what is it?, why is it?, use cases and so on with relevant examples.</p><p>According to the MDN</p><blockquote>Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">source</a></blockquote><p><strong>What spread operator does?</strong></p><p>It can be spread out the items in an array or string as individual arguments or elements and spread out key-value pairs in the objects. Lets discuss with examples.</p><p><strong>Where we use it?</strong></p><p>Spread operator is use in</p><ol><li>function calls</li><li>array literals or strings</li><li>object literals</li></ol><p><strong>1.function calls</strong></p><p>First we write a function to find summation of two numbers.</p><pre>const numbers = [6,8];</pre><pre>function findSum(num1, num2){<br>  console.log(num1+num2);  //14<br>}</pre><pre>findSum(numbers[0], numbers[1]);</pre><p>The output of the above code is 14<strong>. </strong>now add spread operator. We can add spread operator to pass the <strong><em>numbers </em></strong>without using <em>numbers[0], numbers[1].</em></p><pre>const numbers = [6,8];</pre><pre>function findSum(num1, num2){<br> console.log(num1+num2);  //14<br>}</pre><pre>findSum(…numbers);</pre><p>The output,</p><pre>14</pre><p><strong><em>…numbers </em></strong>passes elements of the array to the function. In there <em>findSum() </em>take only first and second elements of the array. lets try to improve the code.</p><pre>const numbers = [6,8,3];</pre><pre>function findSum(...arg){<br>  console.log(arg);              //[ 6, 8, 3 ]               <br>  console.log(arg[0] + arg[1]);  //14<br>}</pre><pre>findSum(...numbers);</pre><p>The output,</p><pre>[ 6, 8, 3 ]<br>14</pre><p>Here,<em> findSum()</em> is added spread operator to <strong>function parameters</strong> also.</p><p><strong>2.array literals or strings</strong></p><p>Here I have arra odd and arrat even. I want to add them to a single array. Try it..</p><pre>const odds = [1,3,5];<br>const even = [2,4,6];</pre><pre>const numbers = [odds, even]</pre><pre>console.log(numbers);  //[ [ 1, 3, 5 ], [ 2, 4, 6 ] ]</pre><p>The output,</p><pre>[ [ 1, 3, 5 ], [ 2, 4, 6 ] ]</pre><p>But here I could not get expected output here which not a single array without nested array. However use concatintor in Array.prototype.concat<em>()</em>…</p><pre>const odds = [1,3,5];<br>const even = [2,4,6];</pre><pre>const numbers = odds.concat(even)</pre><pre>console.log(numbers);     //[ 1, 3, 5, 2, 4, 6 ]</pre><p>The output,</p><pre>[ 1, 3, 5, 2, 4, 6 ]</pre><p>Now try to add spread operator.</p><pre>const odds = [1,3,5];<br>const even = [2,4,6];</pre><pre>const numbers = […odds, …even]</pre><pre>console.log(numbers);</pre><p>The output,</p><pre>[ 1, 3, 5, 2, 4, 6 ]</pre><p>Here we have single array which contains all those elements both odd and even are combined. Both <strong><em>concat()</em></strong><em> </em>and <strong>spread operator </strong>are succeed.</p><p>Now compare and contrast the <strong><em>push()</em></strong> vs <strong><em>spread operator</em></strong></p><pre>let odds = [1,3,5];<br>let updatedOdd = odds        <br>updatedOdd.push(7)</pre><pre>console.log(updatedOdd);        //[1,3,5,7]<br>console.log(odds);              //[1,3,5,7]</pre><pre>/* using spread syntax */</pre><pre>let even = [2,4,6];<br>let updatedEven = even<br>updatedEven = […even, 8];</pre><pre>console.log(updatedEven);       //[2,4,6]<br>console.log(even);              //[2,4,6,8]</pre><p>According to the above code, that when we try to add 7 to <strong><em>updatedOdd</em></strong><em>, the </em>original array (<strong><em>odds</em></strong>)is also changed. But spread operator is not affected to the original array (<strong><em>evens</em></strong>)when we try to add 8 to <strong><em>updatedEven</em></strong>.</p><p><strong>3.object literals</strong></p><blockquote>The Rest/Spread Properties for ECMAScript proposal (ES2018) added spread properties to object literals. It copies own enumerable properties from a provided object onto a new object. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">source</a></blockquote><p>Object literals with spread operator is used to extend the existing objects with new objects.</p><pre>studentBio={<br> name: “Jenny”,<br> age: “20”<br>}</pre><pre>studentCollege={<br> collegeName: “x”,<br> collegeLevel: 4<br>}</pre><pre>const studentDetails = {…studentBio, …studentCollege};<br>console.log(studentDetails)</pre><p>The output,</p><pre>{ name: ‘Jenny’, age: ‘20’, collegeName: ‘x’, collegeLevel: 4 }</pre><p>Here all enumerable details are copied to merged object. <strong><em>studentDetails </em></strong>is a copy of <strong><em>studentBio </em></strong>and <strong><em>studentCollege</em></strong>.</p><p><strong>Conclusion</strong></p><p>This article is covered a basic topic behind the spread operator in JavaScript. Here discussed what is spread operator, where it is used. Then discuss the behavior of the spread operator with the implementing code fragments.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">Spread syntax (...) - JavaScript | MDN</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87233cd85bff" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/what-is-spread-operator-in-javascript-87233cd85bff">Spread operator (…) in JavaScript</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[var, let and const in JavaScript]]></title>
            <link>https://blog.devgenius.io/difference-between-var-let-and-const-in-javascript-7be7d83f63aa?source=rss-de61b3afaa03------2</link>
            <guid isPermaLink="false">https://medium.com/p/7be7d83f63aa</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[variables]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[wathsala danthasinghe]]></dc:creator>
            <pubDate>Tue, 09 Jun 2020 17:41:20 GMT</pubDate>
            <atom:updated>2020-06-10T03:30:21.101Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quick guide to JavaScript variable declaration and their scope.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eDVzMZVPxmTr1Kce" /><figcaption>Photo by <a href="https://unsplash.com/@cebbbinghaus?utm_source=medium&amp;utm_medium=referral">Christopher Robin Ebbinghaus</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article is going to discuss about the difference between <em>var, let,</em> and <em>const</em>, their scopes and what is the best over the others according to the situation.</p><p>When we use a programming language to build an application, we must need clear understanding about the variables declarations. Variables are containers for storing data values. Scope defines the visibility of the variable. With the new features of the ES6, JavaScript is added new variable declarations which <strong><em>let </em></strong>and <strong><em>const </em></strong>additionally <strong><em>var</em></strong>.</p><h4><strong><em>1. var</em></strong></h4><blockquote>The var statement declares a <strong>function-scoped</strong> or <strong>globally-scoped</strong> variable, <strong>optionally initializing</strong> it to a value. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var"><em>source</em></a></blockquote><p>according to the definition, <strong><em>var</em></strong> is a function-scoped or globally-scoped variable.</p><p><strong>function-scoped?</strong><br>Each function of JavaScript creates a new scope. When a variable is defined inside a function, it is only visible inside the function. It is can not access in out side the visible.</p><p><strong>globally-scoped?</strong><br>When a variable is declared outside a function, it becomes global variable which can be accessed all scripts and functions on the web page.</p><p>Next one is <em>var </em><strong>initialization is optional</strong>. The default value is <strong><em>undefined</em></strong>. Also <strong>duplicate variable </strong>declarations by <em>var </em>are <strong>not occurred errors</strong>. Now we discuss with examples. Variable declarations is are processed before any code is executed. It is called hoisting. So, always declare variables at the top of their scope.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11d35224f19c2ff4ae35aa827c491850/href">https://medium.com/media/11d35224f19c2ff4ae35aa827c491850/href</a></iframe><pre>undefined<br>inside function x: 1<br>inside function y: 2<br>outside function x: 1</pre><p>In <em>Example1.js</em> <em>var </em>declarations, variable <em>x </em>is initialized as 1. <em>x </em>is global variable in here. <br>variable <em>y </em>declaration using <em>var </em>is initialized as 2. It is scoped to the function <em>print</em>. If y is tried to access outside the function generate error <strong>ReferenceError: y is not defined.</strong></p><p>When variable is declared using var in the global context, the property descriptor <strong>can not</strong> <strong>be changed </strong>or <strong>deleted</strong>.</p><blockquote>JavaScript has automatic memory management, and it would make no sense to be able to use the delete operator on a global variable. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var">source</a></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/318789ca45dbe026eac8cd7731206970/href">https://medium.com/media/318789ca45dbe026eac8cd7731206970/href</a></iframe><pre>inside the function x: 2<br>inside the function y: undefined<br>outside the function x: 1</pre><h4>2. let</h4><blockquote>The let statement declares a <strong>block-scoped local variable</strong>, optionally initializing it to a value.<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_dead_zone">source</a></blockquote><p><em>var </em>keyword is defined the variable to scoped to the globally or locally to a entire function, In <em>let</em><strong><em> </em>variable is limited to the scope of a block statement </strong>(figure 3) block can be {}, for loop, if -else, etc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c36dedc14d3179fcb04f2754f8bdd366/href">https://medium.com/media/c36dedc14d3179fcb04f2754f8bdd366/href</a></iframe><pre>inside the code block of printVar: 2<br>inside the printVar: 2<br>inside the code block of printLet: 2<br>inside the printLet: 1</pre><p>Next, discuss second one, <em>let</em> is <strong>error occurred</strong>, when it is accessed <strong>before variable is declare</strong>d. The variable is in a “temporal dead zone” from the start of the block until the initialization is processed. But <em>var</em> is given <strong>undefined </strong>in the same situation because of Hoisting.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/673883e21fd1417956d44d86078dc718/href">https://medium.com/media/673883e21fd1417956d44d86078dc718/href</a></iframe><pre>inside printVar before declared: undefined<br>inside printVar after declared: 1<br> console.log(“inside printLet before declared: “+ y);<br>ReferenceError: Cannot access &#39;y&#39; before initialization</pre><p>Third one is, Declaration duplicate variables in <strong>same block or function</strong> using let is occurred <strong>Syntax Error. </strong>But <em>var </em>allows <strong>duplicate variables </strong>in same block.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d6d5b5c1bb2199d0cd071beff67cc9f/href">https://medium.com/media/8d6d5b5c1bb2199d0cd071beff67cc9f/href</a></iframe><pre>let y = 1;<br> ^<br>SyntaxError: Identifier ‘y’ has already been declared</pre><p>when we are going to write switch statement with a single block and declare variable using <em>let </em>inside in every cases, generate a Syntax Error. The solution is adding a block to each and every case clause (Figure 6).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c48738fd06f5dca3d6033974e8fd0188/href">https://medium.com/media/c48738fd06f5dca3d6033974e8fd0188/href</a></iframe><h4><strong>3. const</strong></h4><blockquote>Constants are <strong>block-scoped</strong>, much like variables defined using the let keyword. The value of a <strong>constant </strong>can’t be changed through reassignment, and it <strong>can’t be</strong> <strong>redeclared</strong>. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const">source</a></blockquote><p>The <em>const</em> is changed from the <em>let</em> is can not be reassigned. <em>const </em>must be initialized. Normally, <em>const </em>variables are declared with uppercase.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02d7b5938af57c9ed0eb17c93b6b307d/href">https://medium.com/media/02d7b5938af57c9ed0eb17c93b6b307d/href</a></iframe><p><em>const</em> block scope can be either global or local to the block. The <em>const </em>variables are not a property of the window object unlike <em>var</em>. Re declare a <em>const </em>variable in same block throws an error.</p><p>In example8.js PI is constant declared and give value as 3.14 globally. In the <em>if </em>condition, created a PI variable using let. It is a non constant variable and scoped to <em>if </em>block.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e477aadfce6feee06b2c8112ac0fe3ff/href">https://medium.com/media/e477aadfce6feee06b2c8112ac0fe3ff/href</a></iframe><pre>3.14<br>3.142857142857143<br>3.14</pre><p><strong>Conclusion</strong></p><p>When we summarize the difference between <em>var</em>, <em>let </em>and the <em>const</em>,</p><p><strong><em>var</em></strong><br> · function scoped or globally-scoped.</p><p>· optionally initializing. The default value is undefined.</p><p>· duplicate variable not occurred errors</p><p>· undefined when accessing a variable before it’s declared.</p><p>· variable is declared using var in the global context, the property descriptor cannot be changed or deleted.</p><p><strong><em>let</em></strong></p><p>· lock-scoped local variable.</p><p>· optionally initializing it to a value.</p><p>· accessed before variable is declared, error occurred.</p><p>· duplicate variables in same block or function not allowed.</p><p><strong><em>const</em></strong></p><p>· block-scoped.</p><p>· constant can’t be changed through reassignment.</p><p>· can’t be re declared</p><p>· he const variables are not a property of the window object.</p><p><strong>References</strong></p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements">Statements and declarations</a></li><li><a href="https://tylermcginnis.com/var-let-const/">var vs let vs const in JavaScript</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7be7d83f63aa" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/difference-between-var-let-and-const-in-javascript-7be7d83f63aa">var, let and const in JavaScript</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to React Hooks — Basic Hooks]]></title>
            <link>https://blog.devgenius.io/introduction-to-react-hooks-e49738432f54?source=rss-de61b3afaa03------2</link>
            <guid isPermaLink="false">https://medium.com/p/e49738432f54</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[wathsala danthasinghe]]></dc:creator>
            <pubDate>Sat, 06 Jun 2020 17:03:47 GMT</pubDate>
            <atom:updated>2020-07-06T14:57:28.755Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to React Hooks — Basic Hooks</h3><h4>A quick guide to build web application with React Hooks.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_GZO1oEtSkFY405QQK02VA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@marvelous?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Marvin Meyer</a> on <a href="https://unsplash.com/s/photos/web-deveopment?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>React Hooks is available since React 16.8 and React Native supported since version 0.59. Normally, We know React class components are stateful and function components are stateless. When stateful components can keep state and handle changing the data, stateless components have neither state nor logic in function and takes data via props render React elements.</p><p>So, React applications commonly, parent class Component keeps state and changes according to the logic. Then child function components is passed data via props and render them without changes done itself.</p><p>But no longer you need to use React class Components. Use function components with React Hooks…</p><p><strong>What is React Hooks</strong></p><blockquote>Hooks are functions that let you “hook into” React <strong>state </strong>and <strong>lifecycle features</strong> from function components. Hooks don’t work inside classes — they let you use React without classes. <a href="https://reactjs.org/docs/hooks-state.html">source</a></blockquote><p>According to the above statement React Hooks enable <strong>state </strong>and <strong>life-cycle features </strong>in the function components. With the using React Hooks you can use all features with out a class. Also you do not need to change any line of code already written to move Hooks. You can reuse stateful logic between your components without changing their component hierarchy. Also no need to use lifecycle methods like <em>componentDidMount()</em>, <em>componentDidUpdate() </em>to perform side effects that making code reuse and code organization more difficult with classes.</p><p>Here I am going to discuses basic <strong>Basic Hooks </strong>and <strong>custom Hooks</strong> with comparatively class components.</p><p>Basic Hooks : <br><em> useState<br> useEffect<br> useContext</em></p><p><strong>useState</strong></p><p>We can write React components using both classes and functions. First, I write App class component. Here, displayed name is changed according to the input text changes. It is simple and work it…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/deeee41766f965c1edb315210f2a2a2f/href">https://medium.com/media/deeee41766f965c1edb315210f2a2a2f/href</a></iframe><p>Now, try to write above task as a function component. I want to add current value of “name ”state variable and the other is a function “setName ” that set the name state variable. But I’m in struggle (line no 5 and 6 in figure 2)because of function component is stateless??</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/902a3ffbfe21f1c9f9db7c26ae93465c/href">https://medium.com/media/902a3ffbfe21f1c9f9db7c26ae93465c/href</a></iframe><p>React solve this problem with Hooks. <em>useState </em>from React local state to the function component solve the problem. “helloWorld” is passed to initialize the state name. Here, <em>useState </em>is a Hook which is a function in React. <em>useState </em>can be used more than once in a function</p><pre> import React, {<em>useState</em>} from ‘react’<br> const [name, setName]= <em>useState</em>(‘helloWorld’); </pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1aae97b8e75dced70608ed219d1625fd/href">https://medium.com/media/1aae97b8e75dced70608ed219d1625fd/href</a></iframe><p><strong>useEffect</strong></p><p>classes have life cycle methods that series of events perform from birth to death of a React component. Any component goes through mounting, updating and unmounted. We use some cycle methods like <em>componentDidMount()</em>, <em>componentDidUpdate()</em>, <em>componentWillUnmount()</em>, etc to perform side effects in class components. The operations like data fetching, subscriptions, or manually changing the DOM from React components are called side effects. In the following code is added <em>componentDidMount()</em>, <em>componentDidUpdate() </em>to change document title with the changing of the input name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2926976c4bb60d988a908fea2e50cca8/href">https://medium.com/media/2926976c4bb60d988a908fea2e50cca8/href</a></iframe><p>The render() method is pure and no side-effects because they can affect other components. So how do it in a function component? <em>useEffect </em>hook is used to it. <em>useEffect </em>run both after the initial render and after every updates. <em>useEffect </em>is also use more than once.</p><pre>useEffect(()=&gt;{<br>    document.title = name<br>});</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1aaa5c1a23bc6024929da1ea6eb22e02/href">https://medium.com/media/1aaa5c1a23bc6024929da1ea6eb22e02/href</a></iframe><p><strong>useContext</strong></p><p>Context API provides clean and easy way to share state between the components without passing the props by React itself. Go through my previous document from <a href="https://medium.com/dev-genius/react-native-state-management-with-context-api-61f63f5b099">here</a> to study about more about Context API. <em>useContext </em>hook accepts the the context object which value returned from <em>React.createContext().</em></p><p>In the example <em>ColorContext</em> default value is given as light.</p><pre>const colors = {<br> light: ‘white’,<br> dark: ‘black’,<br> danger: ‘red’<br>}</pre><pre>const ColorContext = React.createContext(colors.light);</pre><p><em>Home </em>function <em>useContext </em>to accept<em> ColorContext.</em></p><pre>function Home(){<br> const color = useContext(ColorContext);<br> return(<br>  &lt;text style={{color: color.danger}} &gt;Hello world&lt;/text&gt;<br> )<br>}</pre><p>Then <em>&lt;ColorContext.Provider&gt;</em> provides the capability to access context which wrapped from it (Here <strong>Home)</strong>.It provides the data and functions to pass down to all the components.</p><pre>export default function App() {</pre><pre>return (<br> &lt;ColorContext.Provider value={colors}&gt;<br>  &lt;Home/&gt;<br> &lt;/ColorContext.Provider&gt;<br> );<br>}</pre><p>complete code,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc99cb4cc536ffaf9558646a46122836/href">https://medium.com/media/bc99cb4cc536ffaf9558646a46122836/href</a></iframe><p><strong>custom Hooks</strong></p><blockquote>A custom Hook is a JavaScript function whose name starts with “use” and that may call other Hooks. <a href="https://reactjs.org/docs/hooks-custom.html">source</a></blockquote><p>The goal of the custom Hooks is preventing the duplicating logic. Custom Hooks lets to reuse stateful logic between components without adding more components. In this code is seperated logic to <em>useNameInput()</em> and <em>useDocumentTitle()</em> functions. Now they are Hooks. Now custom Hooks are totally independent from state itself. So now you can use custom Hooks multiple times in a single component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5250d45d9df184ae0b70b7ac1cb8f8ba/href">https://medium.com/media/5250d45d9df184ae0b70b7ac1cb8f8ba/href</a></iframe><p><strong>Rules of Hooks</strong></p><p>There are two rules to Hooks additionally used JavaScript functions rules.</p><blockquote>Only call Hooks <strong>at the top level</strong>. Don’t call Hooks inside loops, conditions, or nested functions.</blockquote><blockquote>Only call Hooks <strong>from React function components</strong>. Don’t call Hooks from regular JavaScript functions. <a href="https://reactjs.org/docs/hooks-rules.html">source</a></blockquote><p><strong>Conclusion</strong></p><p>In this article, we discussed the basic concepts of the React Hooks and why React introduced Hook. Then build function components with Hooks and compare with class components. Mainly <em>useState</em>, <em>useEffect</em>, <em>useContext </em>and custom Hooks and rules of Hooks are discussed. I think this article will be helpful who enter to follow React Hooks. Next we discuss about:</p><ul><li><a href="https://medium.com/dev-genius/introduction-to-react-hooks-usereducer-7b87a6cb4289">Introduction to React Hooks — useReducer</a></li><li><a href="https://medium.com/dev-genius/performance-optimization-with-react-hooks-usecallback-usememo-f2e527651b79">Performance optimization with React Hooks — useCallback &amp; useMemo</a></li></ul><p><strong>References</strong></p><p><a href="https://reactjs.org/docs/hooks-intro.html">Introducing Hooks - React</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fdpw9EHDh2bM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Ddpw9EHDh2bM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fdpw9EHDh2bM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad70d92540011512f84156a5f5c802a0/href">https://medium.com/media/ad70d92540011512f84156a5f5c802a0/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e49738432f54" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/introduction-to-react-hooks-e49738432f54">Introduction to React Hooks — Basic Hooks</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>