<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ variables - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ variables - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 25 May 2026 10:49:49 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/variables/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Write Better Names for Your Variables, Functions, and Classes – With Examples ]]>
                </title>
                <description>
                    <![CDATA[ Naming is one of the most important and challenging parts of writing clean, maintainable, and scalable code. A well-thought-out variable name, for example, can act as self-documenting code, saving time and effort in understanding the logic. But poorl... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-write-better-variable-names/</link>
                <guid isPermaLink="false">6750922cfe6f3f72caf2624a</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ variables ]]>
                    </category>
                
                    <category>
                        <![CDATA[ naming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Asfak Ahmed ]]>
                </dc:creator>
                <pubDate>Wed, 04 Dec 2024 17:32:28 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1733325693047/f3dff206-f0cf-47b0-9345-991b4d980d71.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Naming is one of the most important and challenging parts of writing clean, maintainable, and scalable code. A well-thought-out variable name, for example, can act as self-documenting code, saving time and effort in understanding the logic. But poorly chosen names, on the other hand, can lead to confusion and bugs.</p>
<p>This article will serve as a comprehensive guide on how to come up with meaningful names for class names, variables, and functions with examples and best practices.</p>
<h2 id="heading-why-does-naming-matter"><strong>Why Does Naming Matter?</strong></h2>
<ul>
<li><p><strong>Readability:</strong> Good names make your code intuitive and reduce the learning curve for others.</p>
</li>
<li><p><strong>Maintainability:</strong> It is easier to refactor or debug well-named code.</p>
</li>
<li><p><strong>Collaboration:</strong> Clear names improve team communication and productivity.</p>
</li>
<li><p><strong>Scalability:</strong> Meaningful names help keep large projects manageable.</p>
</li>
</ul>
<h2 id="heading-different-naming-convention-styles">Different Naming Convention Styles</h2>
<p>Different naming convention styles are crucial in improving code readability and maintainability across various programming languages.</p>
<p>Styles like camelCase, PascalCase, snake_case, and kebab-case are tailored to specific contexts and practices.</p>
<p><strong>camelCase</strong> is widely used for variables and functions, while <strong>PascalCase</strong> is preferred for classes. <strong>snake_case</strong> is a favorite in Python for its clarity, and <strong>kebab-case</strong> dominates CSS for HTML element styling.</p>
<p>Each style ensures consistency, making code intuitive for teams and future developers. Here’s a quick summary table of some popular naming conventions along with their use cases and examples:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Style</strong></td><td><strong>Example</strong></td><td><strong>Common Usage</strong></td></tr>
</thead>
<tbody>
<tr>
<td>camelCase</td><td><code>userName</code></td><td>Variables, functions, object properties</td></tr>
<tr>
<td>PascalCase</td><td><code>UserName</code></td><td>Classes, components, constructors</td></tr>
<tr>
<td>kebab-case</td><td><code>primary-button</code></td><td>CSS classes, HTML IDs, file names</td></tr>
<tr>
<td>snake_case</td><td><code>user_name</code></td><td>Variables, function names in Python</td></tr>
<tr>
<td>SCREAMING_SNAKE_CASE</td><td><code>MAX_CONNECTIONS</code></td><td>Constants</td></tr>
<tr>
<td>dot.case</td><td><code>config.file.path</code></td><td>Configurations, keys</td></tr>
<tr>
<td>Train-Case</td><td><code>Primary-Button</code></td><td>Titles rarely used</td></tr>
<tr>
<td>Hungarian Notation</td><td><code>bIsActive</code></td><td>Legacy code</td></tr>
<tr>
<td>UPPERCASE with Spaces</td><td><code>USER ACCOUNT DETAILS</code></td><td>Rare, mostly for old-style documentation</td></tr>
<tr>
<td>Flatcase</td><td><code>username</code></td><td>Minimalist, filenames, identifiers</td></tr>
</tbody>
</table>
</div><h3 id="heading-how-to-choose-the-right-style"><strong>How to Choose the Right Style</strong></h3>
<ol>
<li><p><strong>Language-Specific:</strong> Follow the conventions of your programming language or framework. For example:</p>
<ul>
<li><p>JavaScript: <code>camelCase</code> for variables and functions, <code>PascalCase</code> for components.</p>
</li>
<li><p>Python: <code>snake_case</code> for variables and functions.</p>
</li>
<li><p>CSS/HTML: <code>kebab-case</code> for class names and IDs.</p>
</li>
</ul>
</li>
<li><p><strong>Team or Project Standards:</strong> Consistency is key. Use the agreed style for your team/project.</p>
</li>
<li><p><strong>Purpose-Specific:</strong> Use naming styles that best represent the entity being named (for example, constants in <code>SCREAMING_SNAKE_CASE</code>).</p>
</li>
</ol>
<h2 id="heading-general-naming-guidelines"><strong>General Naming Guidelines</strong></h2>
<p>Before diving into specific naming conventions for class names, variables, and functions, let’s explore some universal principles:</p>
<ol>
<li><p><strong>Be descriptive and concise:</strong> Names should convey the purpose or role of the variable/function/etc:</p>
<pre><code class="lang-javascript"> <span class="hljs-comment">// Bad</span>
 <span class="hljs-keyword">let</span> x = <span class="hljs-number">10</span>;

 <span class="hljs-comment">// Good</span>
 <span class="hljs-keyword">let</span> maxUsersAllowed = <span class="hljs-number">10</span>;
</code></pre>
</li>
<li><p><strong>Avoid cryptic abbreviations</strong> that might be hard for other devs to understand (or even your future self):</p>
<pre><code class="lang-javascript"> <span class="hljs-comment">// Bad</span>
 <span class="hljs-keyword">let</span> usrNm = <span class="hljs-string">"John"</span>;

 <span class="hljs-comment">// Good</span>
 <span class="hljs-keyword">let</span> userName = <span class="hljs-string">"John"</span>;
</code></pre>
</li>
<li><p><strong>Use consistent naming conventions:</strong> Choose a naming style (camelCase, PascalCase, kebab-case, snake_case) and stick with it throughout your project.</p>
</li>
<li><p><strong>Avoid reserved keywords or confusing names:</strong></p>
<pre><code class="lang-javascript"> <span class="hljs-comment">// Bad</span>
 <span class="hljs-keyword">let</span> <span class="hljs-keyword">let</span> = <span class="hljs-number">5</span>;

 <span class="hljs-comment">// Good</span>
 <span class="hljs-keyword">let</span> variableName = <span class="hljs-number">5</span>;
</code></pre>
</li>
</ol>
<p>Alright, now that we’ve covered the basis, lets dig deeper into some helpful naming conventions.</p>
<h2 id="heading-how-to-create-good-class-names"><strong>How to Create Good Class Names</strong></h2>
<p>Class names define the visual or structural behavior of elements in your application. Writing clear class names ensures your HTML and CSS are easy to understand and maintain.</p>
<h3 id="heading-1-use-descriptive-names"><strong>1. Use Descriptive Names</strong></h3>
<p>Class names should describe the purpose of the element, not its appearance.</p>
<pre><code class="lang-xml"><span class="hljs-comment">&lt;!-- Bad --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"red-button"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-comment">&lt;!-- Good --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"primary-button"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<h3 id="heading-2-follow-the-bem-block-element-modifier-methodology"><strong>2. Follow the BEM (Block-Element-Modifier) Methodology</strong></h3>
<p>BEM is a popular convention for writing scalable and maintainable CSS. It separates components into:</p>
<ul>
<li><p><strong>Block:</strong> Represents the component (for example, <code>card</code>).</p>
</li>
<li><p><strong>Element:</strong> Represents child elements of the block (for example, <code>card__title</code>).</p>
</li>
<li><p><strong>Modifier:</strong> Represents variations of the block or element (for example, <code>card__title--highlighted</code>).</p>
</li>
</ul>
<p><strong>Example:</strong></p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card__title card__title--highlighted"</span>&gt;</span>Welcome<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card__description"</span>&gt;</span>This is a card component.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<h3 id="heading-3-use-kebab-case"><strong>3. Use kebab-case</strong></h3>
<p>CSS class names are traditionally written in kebab-case for better readability.</p>
<pre><code class="lang-xml"><span class="hljs-comment">&lt;!-- Bad --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"primaryButton"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-comment">&lt;!-- Good --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"primary-button"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<h2 id="heading-how-to-create-good-variable-names"><strong>How to Create Good Variable Names</strong></h2>
<p>Variables hold data and should have meaningful names that describe what they represent.</p>
<h3 id="heading-1-use-nouns-for-variables"><strong>1. Use Nouns for Variables</strong></h3>
<p>Variables are typically nouns because they represent entities or data.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Bad</span>
<span class="hljs-keyword">let</span> a = <span class="hljs-string">"John"</span>;

<span class="hljs-comment">// Good</span>
<span class="hljs-keyword">let</span> userName = <span class="hljs-string">"John"</span>;
</code></pre>
<h3 id="heading-2-use-prefixes-to-add-context"><strong>2. Use Prefixes to Add Context</strong></h3>
<p>Adding prefixes helps clarify the type or purpose of a variable:</p>
<ul>
<li><p><strong>Boolean:</strong> <code>is</code>, <code>has</code>, <code>can</code></p>
</li>
<li><p><strong>Numbers:</strong> <code>max</code>, <code>min</code>, <code>total</code></p>
</li>
<li><p><strong>Arrays:</strong> Use plural forms (for example, <code>users</code>, <code>items</code>).</p>
</li>
</ul>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> isUserLoggedIn = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">const</span> maxUploadLimit = <span class="hljs-number">5</span>; <span class="hljs-comment">// MB</span>
<span class="hljs-keyword">const</span> usersList = [<span class="hljs-string">"John"</span>, <span class="hljs-string">"Jane"</span>];
</code></pre>
<h3 id="heading-3-avoid-generic-names"><strong>3. Avoid Generic Names</strong></h3>
<p>Avoid names like <code>data</code>, <code>value</code>, or <code>item</code> unless they’re necessary.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Bad</span>
<span class="hljs-keyword">let</span> data = <span class="hljs-number">42</span>;

<span class="hljs-comment">// Good</span>
<span class="hljs-keyword">let</span> userAge = <span class="hljs-number">42</span>;
</code></pre>
<h2 id="heading-how-to-create-good-function-names"><strong>How to Create Good Function Names</strong></h2>
<p>Functions perform actions, so their names should reflect the operation or process they execute.</p>
<h3 id="heading-1-use-verbs-for-functions"><strong>1. Use Verbs for Functions</strong></h3>
<p>Functions are action-oriented, so their names should begin with a verb:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Bad</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">userData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// ...</span>
}

<span class="hljs-comment">// Good</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchUserData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// ...</span>
}
</code></pre>
<h3 id="heading-2-be-specific-about-functionality"><strong>2. Be Specific About Functionality</strong></h3>
<p>Function names should indicate what they do.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Bad</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handle</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// ...</span>
}

<span class="hljs-comment">// Good</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleFormSubmit</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// ...</span>
}
</code></pre>
<h3 id="heading-3-use-prefixes-for-intent"><strong>3. Use Prefixes for Intent</strong></h3>
<ul>
<li><p>For event handlers: <code>handle</code>, <code>on</code></p>
</li>
<li><p>For utilities: <code>calculate</code>, <code>convert</code>, <code>format</code></p>
</li>
<li><p>For fetch operations: <code>fetch</code>, <code>get</code>, <code>load</code></p>
</li>
<li><p>For setters and getters: <code>set</code>, <code>get</code></p>
</li>
</ul>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleButtonClick</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Button clicked!"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateDiscount</span>(<span class="hljs-params">price, discountPercentage</span>) </span>{
  <span class="hljs-keyword">return</span> price * (discountPercentage / <span class="hljs-number">100</span>);
}
</code></pre>
<h2 id="heading-how-to-know-if-a-name-is-good-for-a-variable-function-or-class">How to Know if a Na<strong>me is Good for a Variable, Function, or Class</strong></h2>
<p>To understand if a name is good for a variable, function, or class, evaluating it using several key principles is important. Here’s a guide to help you decide whether a name is appropriate and meaningful in your programming context:</p>
<h3 id="heading-1-does-it-represent-the-purpose">1. <strong>Does It Represent the Purpose?</strong></h3>
<p><strong>Purpose-driven names</strong> are the most important characteristic of good naming. A name should immediately tell you what the variable, function, or class represents or does without needing to read additional comments or documentation.</p>
<p><strong>How to Assess:</strong></p>
<p>Ask yourself: "When I read this name, can I immediately understand its purpose?"</p>
<p><strong>Example:</strong></p>
<ul>
<li><code>userAge</code> is better than <code>a</code> because <code>userAge</code> tells you what the variable represents, whereas <code>a</code> is too ambiguous.</li>
</ul>
<h3 id="heading-2-is-it-specific-enough">2. <strong>Is It Specific Enough?</strong></h3>
<p>The name should be <strong>specific enough</strong> to reflect the exact role of the entity in your code. Overly generic names like <code>data</code> or <code>temp</code> can be confusing because they don’t provide enough context.</p>
<p><strong>How to Assess:</strong></p>
<p>Ask: "Is this name specific to what this variable, function, or class represents in my application?"</p>
<p><strong>Example:</strong></p>
<ul>
<li><code>calculateTaxAmount()</code> is better than <code>calculate()</code> because it’s clear what the function is calculating.</li>
</ul>
<h3 id="heading-3-does-it-follow-a-consistent-naming-convention">3. <strong>Does It Follow a Consistent Naming Convention?</strong></h3>
<p><strong>Consistency</strong> in naming conventions is vital. When all team members follow the same conventions, the code is easier to understand and navigate.</p>
<p><strong>How to Assess:</strong></p>
<p>Ask: "Is this name consistent with the naming conventions used in the rest of the project?" Follow project guidelines such as:</p>
<ul>
<li><p><code>camelCase</code> for variables and functions (e.g., <code>userAge</code>)</p>
</li>
<li><p><code>PascalCase</code> for classes (e.g., <code>UserProfile</code>)</p>
</li>
<li><p><code>UPPERCASE_SNAKE_CASE</code> for constants (e.g., <code>MAX_USERS</code>)</p>
</li>
</ul>
<p><strong>Example:</strong></p>
<ul>
<li>If your team follows <code>camelCase</code>, <code>userData</code> is better than <code>UserData</code>.</li>
</ul>
<h3 id="heading-4-does-it-avoid-ambiguity">4. <strong>Does it Avoid Ambiguity?</strong></h3>
<p>A good name <strong>eliminates ambiguity</strong>. It should not be open to multiple interpretations. If it can mean different things in different contexts, it will lead to confusion.</p>
<p><strong>How to Assess:</strong></p>
<p>Ask: "Could someone unfamiliar with the codebase misinterpret what this name refers to?"</p>
<p><strong>Example:</strong></p>
<ul>
<li>Instead of naming a boolean <code>isValid</code>, use <code>isUserLoggedIn</code> or <code>isEmailVerified</code> to make it clearer what is being checked.</li>
</ul>
<h3 id="heading-5-is-it-easy-to-read-and-pronounce">5. <strong>Is It Easy to Read and Pronounce?</strong></h3>
<p>While not strictly necessary, <strong>ease of reading and pronunciation</strong> can improve the overall readability and maintainability of your code.</p>
<p><strong>How to Assess:</strong></p>
<p>Ask: "Is this name easy to read aloud, and can I understand it at a glance?"</p>
<p>Avoid long names, and use common abbreviations only when they are widely accepted.</p>
<p><strong>Example:</strong></p>
<ul>
<li><code>maxRetries</code> is better than <code>maximumNumberOfAttemptsToReconnect</code>.</li>
</ul>
<h3 id="heading-6-does-it-avoid-redundancy">6. <strong>Does It Avoid Redundancy?</strong></h3>
<p><strong>Avoid redundancy</strong> in names. Don’t repeat information that is already implied or described by the context.</p>
<p><strong>How to Assess:</strong></p>
<p>Ask: "Am I repeating information that is already clear from the surrounding context?"</p>
<p><strong>Example:</strong></p>
<ul>
<li>If you have a class named <code>User</code>, naming a method <code>userGetData()</code> is redundant. Instead, use <code>getData()</code>.</li>
</ul>
<h3 id="heading-7-is-it-self-documenting">7. <strong>Is It Self-Documenting?</strong></h3>
<p>The best names <strong>document themselves</strong>. Good names reduce the need for additional comments or explanations.</p>
<p><strong>How to Assess:</strong></p>
<p>Ask: "Does this name fully describe the variable, function, or class without requiring a comment to explain what it does?"</p>
<p><strong>Example:</strong></p>
<ul>
<li><code>calculateTotalPrice</code> is self-explanatory, so there’s no need for an additional comment like “This function calculates the total price after discount.”</li>
</ul>
<h3 id="heading-8-is-it-contextual-and-relevant-to-the-domain">8. <strong>Is It Contextual and Relevant to the Domain?</strong></h3>
<p>The name should fit within the context of your project and its domain. For example, naming conventions for a web application may differ from those for a mobile app or a machine learning model.</p>
<p><strong>How to Assess:</strong></p>
<p>Ask: "Is this name aligned with the domain and context of my project?"</p>
<p>If you’re working in a specific domain (for example, finance, health, gaming), use domain-specific terms that are easily recognizable.</p>
<p><strong>Example:</strong></p>
<ul>
<li>In a gaming app, <code>healthPoints</code> is more appropriate than <code>hp</code>, as it reflects its meaning.</li>
</ul>
<h3 id="heading-9-is-it-future-proof">9. <strong>Is It Future-Proof?</strong></h3>
<p>Think about how your code will evolve. Names should be flexible enough to accommodate future changes without requiring refactoring.</p>
<p><strong>How to Assess:</strong></p>
<p>Ask: "Will this name still make sense if the functionality changes or the project grows?"</p>
<p><strong>Example:</strong></p>
<ul>
<li><code>userInfo</code> could become outdated if the data structure changes. It’s better to use <code>userProfile</code> if you expect more fields to be added.</li>
</ul>
<h3 id="heading-10-does-it-avoid-magic-numbers-and-hard-coded-values">10. <strong>Does It Avoid Magic Numbers and Hard-Coded Values?</strong></h3>
<p><strong>Magic numbers</strong> (numbers with unclear meaning) should be avoided in favor of named constants.</p>
<p><strong>How to Assess:</strong></p>
<p>Ask: "Does this name represent a meaningful constant, or is it just a raw number?"</p>
<p><strong>Example:</strong></p>
<ul>
<li>Instead of using <code>1000</code>, use a constant like <code>MAX_FILE_SIZE</code> to explain the meaning behind the number.</li>
</ul>
<h2 id="heading-practical-examples"><strong>Practical Examples</strong></h2>
<h3 id="heading-css-example"><strong>CSS Example</strong></h3>
<p>The following CSS example demonstrates how to apply <strong>BEM (Block-Element-Modifier)</strong> naming conventions to maintain a structured and scalable class hierarchy in your stylesheet:</p>
<pre><code class="lang-xml"><span class="hljs-comment">&lt;!-- HTML --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"navbar"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"navbar__list"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"navbar__item navbar__item--active"</span>&gt;</span>Home<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"navbar__item"</span>&gt;</span>About<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"navbar__item"</span>&gt;</span>Contact<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-css"><span class="hljs-comment">/* CSS */</span>
<span class="hljs-selector-class">.navbar</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#333</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span>;
}

<span class="hljs-selector-class">.navbar__list</span> {
  <span class="hljs-attribute">list-style</span>: none;
}

<span class="hljs-selector-class">.navbar__item</span> {
  <span class="hljs-attribute">display</span>: inline-block;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span>;
}

<span class="hljs-selector-class">.navbar__item--active</span> {
  <span class="hljs-attribute">color</span>: orange;
}
</code></pre>
<p>Here’s what’s going on in this code:</p>
<ul>
<li><p><strong>BEM Naming</strong>: <code>navbar</code> is the <strong>Block</strong>, representing the main navigation component.</p>
</li>
<li><p><code>navbar__list</code> is the <strong>Element</strong>, a child of the block, representing the list of navigation items.</p>
</li>
<li><p><code>navbar__item</code> is another <strong>Element</strong> representing individual list items.</p>
</li>
<li><p><code>navbar__item--active</code> is a <strong>Modifier</strong>, used to highlight the active menu item.<br>  This approach makes it easy to understand relationships and roles within the HTML and CSS, supporting modular and reusable styles.</p>
</li>
</ul>
<h3 id="heading-javascript-example"><strong>JavaScript Example</strong></h3>
<p>This JavaScript example shows how to use meaningful and consistent naming conventions for variables and functions to make the code self-explanatory:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Variables</span>
<span class="hljs-keyword">let</span> isUserLoggedIn = <span class="hljs-literal">false</span>;
<span class="hljs-keyword">const</span> maxAllowedItems = <span class="hljs-number">10</span>;

<span class="hljs-comment">// Functions</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchUserDetails</span>(<span class="hljs-params">userId</span>) </span>{
  <span class="hljs-comment">// Fetch user data from the API</span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateTotalPrice</span>(<span class="hljs-params">cartItems</span>) </span>{
  <span class="hljs-keyword">return</span> cartItems.reduce(<span class="hljs-function">(<span class="hljs-params">total, item</span>) =&gt;</span> total + item.price, <span class="hljs-number">0</span>);
}
</code></pre>
<p>Here’s what’s going on in the code:</p>
<ul>
<li><p><strong>Variables</strong>:</p>
<ul>
<li><p><code>isUserLoggedIn</code>: A boolean variable named to clearly indicate its purpose. Prefixing with <code>is</code> helps identify it as a boolean.</p>
</li>
<li><p><code>maxAllowedItems</code>: A constant with an uppercase <code>max</code> prefix shows it's a limit, making its intent clear.</p>
</li>
</ul>
</li>
<li><p><strong>Functions</strong>:</p>
<ul>
<li><p><code>fetchUserDetails(userId)</code>: The name reflects the purpose of the function, that is retrieving user details. The parameter <code>userId</code> is descriptive and avoids ambiguity.</p>
</li>
<li><p><code>calculateTotalPrice(cartItems)</code>: The function name explicitly states the action performed. The <code>cartItems</code> parameter is contextually relevant to the e-commerce domain.</p>
</li>
</ul>
</li>
</ul>
<p><strong>Why It’s Good</strong>: These conventions ensure the code is readable and intuitive, reducing the cognitive load for other developers working on the same project.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Meaningful naming is both an important convention and an art form that significantly impacts your code's readability and maintainability.</p>
<p>Try to follow these basic principles:</p>
<ul>
<li><p>Use descriptive, concise names.</p>
</li>
<li><p>Adhere to consistent conventions like BEM for class names and camelCase for variables and functions.</p>
</li>
<li><p>Use prefixes to add context and clarity.</p>
</li>
</ul>
<p>These and the other tips we’ve discussed here will make your code a joy to work with, whether you revisit it months later or collaborate with a team. Start applying these tips today, and watch your code quality soar.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Variables and Data Types in JavaScript – Explained With Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ A variable is like a box where you can store data or a reference to data. In this article, you will learn how to create and use variables. You'll also learn about the different data types in JavaScript and how to use them. Let's get started! Table of... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-variables-and-data-types-in-javascript/</link>
                <guid isPermaLink="false">66c3499e4f7405e6476b019b</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ variables ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Austin Asoluka ]]>
                </dc:creator>
                <pubDate>Mon, 19 Aug 2024 13:33:18 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723754441356/34416215-e12b-41ec-8c11-332d2c8214e1.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A variable is like a box where you can store data or a reference to data.</p>
<p>In this article, you will learn how to create and use variables. You'll also learn about the different data types in JavaScript and how to use them.</p>
<p>Let's get started!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-a-variable-example-1">What is a Variable? Example #1</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-a-variable-example-2">What is a Variable? Example #2</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-a-variable-example-3">What is a Variable? Example #3</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-declare-a-variable">How to Declare a Variable</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-variable-assignment-and-initialization">Variable Assignment and Initialization</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-call-a-variable">How to Call a Variable</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-name-variables">How to Name Variables</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-reserved-words-in-javascript">Reserved Words in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-rules-for-naming-variables-in-javascript">Rules for Naming Variables in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-popular-variable-naming-conventions">Popular Variable Naming Conventions</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-variable-data-types">Variable Data Types</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-primitive-data-types">Primitive Data Types</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-reference-types-in-javascript">Reference types in JavaScript</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-summary">Summary</a></p>
</li>
</ul>
<h3 id="heading-what-is-a-variable-example-1">What is a Variable? Example #1</h3>
<p>When a child is born, they are given a name and throughout their life, they'll be referred to b<a class="post-section-overview" href="#reference-types-in-javascript">y</a> that name (unless the name gets changed at some point).</p>
<p>Have you seen anyone without a name? How were you able to call them?<br>In an ideal world, everyone should have a name or a unique way we can refer to them. In JavaScript, every variable has a name.</p>
<blockquote>
<p>Everyone must have a name or a way by which we can refer to them.</p>
</blockquote>
<h3 id="heading-what-is-a-variable-example-2"><strong>What is a Variable? Example #2</strong></h3>
<p>In a math equation, when we say <code>x = 1</code> it means, "anywhere you see <code>x</code>, you should replace it with <code>1</code>". In this case, <code>x</code> is a variable, while <code>1</code> is the value of it. That is: <code>x</code> points to <code>1</code>.</p>
<p>This means that without <code>x</code>, there will be no reference to <code>1</code>. There could be other occurrences of <code>1</code> in the equation but those will be different than the <code>1</code> which <code>x</code> was referring to. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/* The code below means x is 1 
 * So during execution, anywhere x appears after the line below, 
 * the complier replace x with 1.
 */</span>
<span class="hljs-keyword">let</span> x = <span class="hljs-number">1</span>;
<span class="hljs-keyword">let</span> y = <span class="hljs-number">1</span>; <span class="hljs-comment">// the value which y refers to is different from that of x</span>
<span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// This line will log 1 to the console.</span>
</code></pre>
<p>In the code snippet above, <code>x</code> refers to the value 1, and <code>y</code> It also refers to another value 1, but note that both values are distinct, just like you can have two different brands of bottled water even though they both contain water.</p>
<p>So, when we mention the variable name <code>x</code>, we get the value assigned to that variable.</p>
<h3 id="heading-what-is-a-variable-example-3"><strong>What is a Variable? Example #3</strong></h3>
<p>A variable can be conceptualized as a container. The variable's name serves as its identifier, its value represents the container's contents, and its type specifies the nature of those contents.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690903992237/a783721f-1fbc-4c84-8df6-24a49e7dddb3.jpeg" alt="Bottle of water" class="image--center mx-auto" width="1280" height="851" loading="lazy"></p>
<p>A popular water brand here in Nigeria is known as "Eva".</p>
<p>Let's say you bought Eva water, took it home, and placed it amongst other water brands. You can easily say to someone, "Please get me the Eva water over there" and because of the name, it becomes easy for the person to identify and get exactly what you need.</p>
<p>Just as you can easily distinguish your Eva water from other water brands by its name, a variable is uniquely identified by its name within a program. While there may be multiple variables storing data, the specific name of a variable allows you to reference its contents precisely.</p>
<p>In JavaScript, values are assigned a name and anytime we need that value, we simply mention the name to which it was assigned. When the code executes, the name of that variable is replaced by the value it refers to.</p>
<p>In the case of the analogy above, the content of the bottle is water and the type is a liquid. But assuming we have a variable <code>x</code> which refers to the value <code>1</code>, the type of the variable is <code>number</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Add the line of code below to the previous code snippet to</span>
<span class="hljs-comment">// find out the data type of x;</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> x)
</code></pre>
<p>In the code snippet above, <code>number</code> is printed to the console because variable x holds the value <code>1</code> which is a number.</p>
<p><strong>Variables exist in our program to help us hold values and be able to refer to them whenever we need to</strong>. <strong>Anywhere a variable is mentioned, the value of that variable is what's being used for the computation at the time</strong>.</p>
<h2 id="heading-how-to-declare-a-variable">How to Declare a Variable</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> score;
</code></pre>
<p>The program above declares/creates a variable called <code>score</code>.</p>
<p>In JavaScript, creating variables is that simple. The type of the variable is the type of the value stored in it. That is, if the variable <code>score</code> holds a value of <code>1</code>, the type for the <code>score</code> variable is <code>number</code>. So we can say, <code>score</code> is a number variable.</p>
<p>To create a variable, we have to do the following;</p>
<ol>
<li><p>Declare the variable using one of these keywords: <code>let</code>, <code>const</code> or <code>var</code>.</p>
</li>
<li><p>Determine a name to call the variable and write it on the same line as the keyword used in step 1.</p>
</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> score; <span class="hljs-comment">// creates variable 'score'</span>
</code></pre>
<p>Notice that this time, we did not give it a value. We just simply created a container that will store something. For now, it is empty. Although it has no content at the moment, we'll surely provide content for it.</p>
<h2 id="heading-variable-assignment-and-initialization">Variable Assignment and Initialization</h2>
<p>We can assign a value to a variable by using the assignment (<code>=</code>) operator—the variable name to the left of it, and the value to the right.</p>
<pre><code class="lang-javascript">score = <span class="hljs-number">1</span>;
</code></pre>
<p>The code snipped above assigns <code>1</code> as the value of <code>score</code> (this is called <strong>variable assignment</strong>).</p>
<p>When we combine variable declaration and assignment in one operation, it is called <strong>variable initialization</strong>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> score = <span class="hljs-number">1</span>;
</code></pre>
<p>As seen above, we declare the variable <code>score</code>, and immediately on the same line, assign the value <code>1</code> to it.</p>
<p>This means that we provided an initial value for the variable when it was created.</p>
<h2 id="heading-how-to-call-a-variable">How to Call a Variable</h2>
<p>If you want to use a variable for an operation at any time in your program, you can simply just "call" it. To <strong>call</strong> a variable is the same as <strong>mentioning</strong> or <strong>using</strong> it.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(score + <span class="hljs-number">1</span>) <span class="hljs-comment">// 2</span>
</code></pre>
<p>In the code snippet above, the variable <code>score</code> was <strong>used</strong> in the line of code. Therefore, It will be replaced with its actual value <code>1</code> during the code execution. This means we'd have <code>1 + 1</code> executed, resulting in <code>2</code>.</p>
<p>In the next section, let's learn how to properly name our variables in other to ensure our codes are neat and readable.</p>
<h2 id="heading-how-to-name-variables">How to Name Variables</h2>
<p>Just like naming a human or pet or labeling an object, we always put in much thought to ensure that the name tells a story and gives an idea of how we feel about the role of that pet, human, or object.</p>
<p>JavaScript is somewhat liberal when it comes to how variable naming can be done and also how long it could be.</p>
<p>For example, <code>pneumonoultramicroscopicsilicovolcanoconiosis</code> is a valid variable name in JavaScript even though it is long.</p>
<p>It is generally a good practice to give meaningful names to variables and they should be of a reasonable length.</p>
<p>Let your variables be simple and contextual. For example: <code>author</code>, <code>publishedDate</code>, <code>readTime</code>, <code>shouldCompress</code>, and so on.</p>
<p>It should be self-explanatory. Just avoid cryptic names where possible.</p>
<h3 id="heading-reserved-words-in-javascript">Reserved Words in JavaScript</h3>
<p>Even though we can create variables as we wish, some names are already being used within JavaScript to mean something specific. These names cannot be used by a developer to identify a variable. They are called reserved words.</p>
<p>For instance, the keyword <code>catch</code> is used to properly handle an error and prevent it from crashing an application. Hence, you cannot call a variable <code>catch</code> in your program.</p>
<p>Below are all the reserved words in JavaScript:</p>
<p><code>arguments</code> <code>await</code> <code>break</code> <code>case</code> <code>catch</code> <code>class</code> <code>const</code> <code>continue</code> <code>debugger</code> <code>default</code> <code>delete</code> <code>do</code> <code>else</code> <code>enum</code> <code>eval</code> <code>export</code> <code>extends</code> <code>false</code> <code>finally</code> <code>for</code> <code>function</code> <code>if</code> <code>implements</code> <code>import</code> <code>in</code> <code>Infinity</code> <code>instanceof</code> <code>interface</code> <code>let</code> <code>NaN</code> <code>new</code> <code>null</code> <code>package</code> <code>private</code> <code>protected</code> <code>public</code> <code>return</code> <code>static</code> <code>super</code> <code>switch</code> <code>this</code> <code>throw</code> <code>true</code> <code>try</code> <code>typeof</code> <code>undefined</code> <code>var</code> <code>void</code> <code>while</code> <code>with</code> <code>yield</code></p>
<p><strong>NOTE</strong>: You do not need to memorize these keywords. If you try to use them, you'll get an error and you'll learn to recognize and know them with experience.</p>
<p>Also, JavaScript has some rules that you must follow when naming variables as well as generally accepted conventions (best practices) that you should know about. Let's talk about them in the next section.</p>
<h3 id="heading-rules-for-naming-variables-in-javascript"><strong>Rules for Naming Variables in JavaScript</strong></h3>
<ul>
<li><p>Reserved words cannot be used as variable names.</p>
</li>
<li><p>The first letter of your variable name should be an alphabet, underscore (_), or a dollar sign ($). You cannot use a number as the first character of your variable name. Even though other kinds of special characters are allowed to start a variable name, as a way of good practice and avoiding complexities at the start, you should just always start with a letter. Using an underscore or dollar sign is symbolic by convention and we'll learn what they mean in the future.</p>
</li>
<li><p>The rest of the variable name may contain anything but symbols, punctuations, and reserved characters (+, -, *, and so on).</p>
</li>
<li><p>Variable names are case-sensitive. This means <code>Boy</code> and <code>boy</code> will be treated as different variables in your program.</p>
</li>
<li><p>A variable name can be as long as is necessary for it to make sense. There is no limit imposed by the language.</p>
</li>
<li><p>Spaces are not allowed in variable names.</p>
</li>
</ul>
<h3 id="heading-popular-variable-naming-conventions"><strong>Popular Variable Naming Conventions</strong></h3>
<ul>
<li><p>Variable names with multiple words should use <strong>camel casing.</strong> That is, the first word has to be all lowercase while the first letter of subsequent words should be uppercase: <code>studentRegistrationNumber</code></p>
</li>
<li><p>Use uppercase letters for constant variables: <code>const PI = 3.1432</code></p>
</li>
<li><p>If a constant variable is composed of multiple words, use snake casing (separation of words with an underscore): <code>const PROGRAM_NAME = "Vacation planner"</code></p>
</li>
<li><p>If a variable is meant to be private, prefix its name with an underscore: <code>let _memorySize = 2042</code>.<br>  <strong>Note</strong>: This is just to let the team (others working on the project) know that the author intends to use it as private. It doesn't prevent the value of the variable from being accessed (there are other ways to ensure this).</p>
</li>
<li><p>It is common practice to prefix Boolean variables with <code>is</code> or <code>has</code>: <code>let isMarked = true</code>.</p>
</li>
</ul>
<p>In the next section, we'll learn about different data types and how to work with them.</p>
<h2 id="heading-variable-data-types">Variable Data Types</h2>
<p>Data type simply means "type of data" 😉.</p>
<p>The word "data" in this context means a piece of information. We'll use the word "value<strong>"</strong> sometimes to mean data and vice versa.</p>
<p>In JavaScript, we store values of different types in variables. These values have different attributes/properties and the type of data a variable holds will determine the operations you can perform with that variable.</p>
<p>For example, if you have water (value) stored in a container (variable), you can use the water (value) to wash or drink, but if what is stored in the container are candies, you can eat them but you won't be able to use them for washing.</p>
<p>If you have a variable that holds numbers, you can use them to perform arithmetic operations. If the variable holds a Boolean, you cannot use it for arithmetic operations but it can be used for logical operations.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">The kind of value stored in the variable determines what you can do with it.</div>
</div>

<p>The data types in JavaScript are categorized into two primary groups, namely;</p>
<ul>
<li><p><strong>Primitive</strong>: Number, String, Boolean, Undefined, Null, BigInt, Symbol</p>
</li>
<li><p><strong>Reference</strong>: Object, Array, Function</p>
</li>
</ul>
<p>In this article, we will not talk about Symbols and BigInt to avoid complexities. The goal is to do our best to explain fundamental concepts to beginners in the most simple way possible.</p>
<p>Let's consider primitive data types.</p>
<h3 id="heading-primitive-data-types"><strong>Primitive Da</strong>ta Types</h3>
<p>Variables having these type of data are called primitives because they hold simple values. The word <a target="_blank" href="https://www.google.com/search?q=primitive&amp;rlz=1C5CHFA_enNG1050NG1050&amp;oq=primitive&amp;aqs=chrome..69i57j0i271.760j0j7&amp;sourceid=chrome&amp;ie=UTF-8">primitive</a> can be translated to mean non-complex.</p>
<p>Primitive values are usually a single unit like 1, "cup", null, undefined, true, and so on. Let's briefly consider how these data types are used and what kind of operations you can perform with them.</p>
<ul>
<li><strong>NUMBER:</strong> In JavaScript, all numbers are floating-point values. Whether they are numbers without decimal points like a whole number that can be negative, positive, zero, or values with a decimal point like 0.2, -0.5, 1, -2, 0. They are all of the <code>number</code> type.</li>
</ul>
<p>This type of value can be used in arithmetic operations like multiplication, division, subtraction, addition, modulus, and so on.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> score1 = <span class="hljs-number">2</span>;
<span class="hljs-keyword">let</span> score2 = <span class="hljs-number">5</span>;
<span class="hljs-keyword">let</span> averageScore = (score1 + score2) <span class="hljs-comment">// 2</span>
<span class="hljs-built_in">console</span>.log(averageScore) <span class="hljs-comment">// 3.5</span>
</code></pre>
<p>To check the data type of a variable's value, use the <code>typeof</code> operator like this: <code>typeof variableName</code>. That is: <code>typeof score1</code></p>
<p>In the code snippet above, <code>score1</code> is a variable which holds a value of <code>2</code>, <code>score2</code> holds a value of <code>5</code>, while the <code>averageScore</code> variable stores the result from dividing the sum of <code>score1</code> and <code>score2</code> by <code>2</code>, which evaluates to <code>3.5</code>.</p>
<p>Using the <code>typeof</code> operator on the <code>score1</code> variable will return <code>number</code>.</p>
<p><strong>Exercise</strong>: Copy the code in the snippet above and run it in your code editor to see how it works for you. You can play around with the values and use the <code>typeof</code> operator to check the variables' data type.</p>
<p>When performing arithmetic operations, you may run into other Number types like <code>Infinity</code>, <code>-Infinity</code> and <code>NaN</code>.</p>
<p><strong>Infinity</strong> means something without any limit. One way to reach infinity is to divide a number by 0.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> result = <span class="hljs-number">12</span> / <span class="hljs-number">0</span>;

<span class="hljs-built_in">console</span>.log(result) <span class="hljs-comment">// Infinity</span>
</code></pre>
<p>In the code above, we divided <code>12</code> by <code>0</code> and logged the result to the console which prints out <code>Infinity</code>.</p>
<p><strong>Negative Infinity</strong> is used to denote a number that is less than any natural number. To arrive at negative infinity, copy the code in the snippet below and run it in your coding environment.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Number</span>.NEGATIVE_INFINITY) <span class="hljs-comment">// -Infinity</span>
</code></pre>
<p><strong>NaN</strong> means Not <strong>a</strong> Number. This will occur when you try to carry out an impossible mathematical operation as shown below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> result = <span class="hljs-string">"Ella"</span> / <span class="hljs-number">2</span>; <span class="hljs-comment">// Trying to divide a string with a number</span>
<span class="hljs-built_in">console</span>.log(result) <span class="hljs-comment">// NaN</span>
</code></pre>
<p>The first line in the code above tries to divide a string by a number and the result is <code>NaN</code>.</p>
<p>You will not often reach infinity or -Infinity as a beginner doing basic/intermediate stuff, but it is something you should be aware of so that you do not get worked up when you see it occur in your code (this is something you do not want to cram in your head). <code>NaN</code> is will occur more often than the others. When you see it, just know something is wrong with the operation you are trying to perform.</p>
<ul>
<li><strong>STRING:</strong> In JavaScript, a string is a collection of characters enclosed in quotes: <code>"Cathy"</code>.</li>
</ul>
<p>The snippet below shows how a string can be used in a JavaScript program:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> author = <span class="hljs-string">"Sleekcodes"</span>;
<span class="hljs-keyword">let</span> publishedDate = <span class="hljs-string">"14 August 2023"</span>;

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Written by: "</span> + author); <span class="hljs-comment">// Written by: Sleekcodes</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Published on: "</span> + publishedDate); <span class="hljs-comment">// Published on: 14 August 2023"</span>
</code></pre>
<p>I am sure you noticed the + operator used with strings. When this occurs, the result is that the string on the right and that on the left will be joined together to become one. This is called string concatenation.</p>
<p>The code above is simply saying, "Create a variable called <code>author</code> and store the text <code>"sleekCodes"</code> as its value, create another variable <code>publishedDate</code> and store the text <code>"14 August 2023"</code> in it."</p>
<p>Then in line 4, we tell the JavaScript engine to log (print) the string "Written by: Sleekcodes<strong>"</strong> to the console. Line 5 also says log <strong>"</strong>Published on: 14 August 2023<strong>"</strong> to the console.</p>
<p>Notice that in the code above, during execution, <code>author</code> gets replaced with the value "Sleekcodes" and <code>publishedDate</code> gets replaced with "14 August 2023" where used.</p>
<p>Strings are used to depict or convey data in text/alphabetic format. A string can be made up of zero or more characters. A string that has no character in it is called an empty string. For example: <code>""</code>.</p>
<ul>
<li><strong>BOOLEAN</strong>: When we need to represent data in two possible states only like true/false, on/of, or yes/no, we use Boolean values. The value of a Boolean variable is either <code>true</code> or <code>false</code>.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> isQualified = <span class="hljs-literal">true</span>

<span class="hljs-keyword">if</span> (isQualified) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Tola is qualified"</span>); <span class="hljs-comment">// Tola is qualified</span>
}
</code></pre>
<p>The code above will print the statement "Tola is qualified", because the value of the variable <code>isQualified</code> is true. That operation is a type of conditional operation. This is where Boolean values shine.</p>
<p><strong>Exercise</strong>: Change the value of <code>isQualified</code> to be <code>false</code> and observe what happens.</p>
<ul>
<li><strong>UNDEFINED</strong>: This is both a value and a data type. <code>undefined</code> is used to indicate that a variable has no defined value. For instance, when a variable is declared (<code>let age</code>), and you try to access its value, the result would be <code>undefined</code>.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> age; <span class="hljs-comment">// note that there is no value assigned to the variable here</span>

<span class="hljs-built_in">console</span>.log(age); <span class="hljs-comment">// undefined</span>
</code></pre>
<p>In the code snippet above, because age isn't given any explicit value, the compiler assigns the value <code>undefined</code> to the variable by default.</p>
<p><strong>Exercise</strong>: Use the <code>typeof</code> operator on the variable <code>age</code> and see what you get. Also, assign the value <code>undefined</code> to <code>age</code> and use the <code>typeof</code> operator on it again to see the result.</p>
<ul>
<li><strong>NULL</strong>: Null is a value we can assign to a variable to indicate that it has no value. It is used to represent "empty" or "unknown".</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> age = <span class="hljs-literal">null</span>;

<span class="hljs-built_in">console</span>.log(age); <span class="hljs-comment">// null</span>
</code></pre>
<p>As seen in the code snippet above, instead of letting the compiler assign <code>undefined</code> for us, we explicitly indicate that the variable has no value by assigning the value <code>null</code> to it.</p>
<p>This means <code>age</code> is empty or unknown.</p>
<p>People often get confused about the difference between <code>undefined</code> and <code>null</code>. One is the default value assigned to a variable without an explicit value, while the other (<code>null</code>) is a value assigned to a variable by the programmer deliberately to indicate that the variable is empty. As a rule of thumb, do not assign <code>undefined</code> to a variable, instead use <code>null</code> (the compiler auto-assigns <code>undefined</code> where needed).</p>
<p>Primitive data types have no complexity. They are plain and simple (a single value). This statement will make more sense when you read about how reference types work in the next section.</p>
<p>Consider the image below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691169563292/8cd6a8de-e6c5-46fe-8271-c2a522b6c663.png" alt="primitive types concept" class="image--center mx-auto" width="1782" height="1447" loading="lazy"></p>
<p><strong>Part A</strong> above is the code you write, while <strong>Part</strong> <strong>B</strong> is what happens when the code runs. For primitive data types, the value is simply assigned to the variable (it is straightforward).</p>
<p>Primitive values are passed by value (they generate no reference). Do not worry about what this means yet because we'll explain in the next section.</p>
<h2 id="heading-reference-types-in-javascript">Reference Types in JavaScript</h2>
<p>Reference data types are data passed by "reference". A thorough understanding of this statement is crucial throughout your career as a JavaScript developer, so do well to pay close attention to the concept we are about to learn.</p>
<p>Consider the image below carefully.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691062567476/e31e1bfe-6b85-418e-a88a-e19810f11839.png" alt="Reference types concept" class="image--center mx-auto" width="2338" height="1633" loading="lazy"></p>
<p>In the image above, <strong>part A</strong> is the code you write, while <strong>part B</strong> is what happens "behind the scenes".</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Use the image above to follow through with the following explanation.sa</div>
</div>

<p>When you create a variable whose data type is in the reference category (objects, functions, arrays), instead of the value being directly assigned to the variable, a reference is generated for the value and that reference is what gets assigned to the variable<strong>.</strong></p>
<p>The reference gets assigned to the variable, but it points to the actual value.</p>
<p>This means that when you try to use the variable anywhere, you are working with the reference to the actual value and anything done to the reference affects the actual value.</p>
<p>Think of it like a middleman between the actual value and the variable name.</p>
<p>Consider the example below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> studentInfo = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">205</span>
}

<span class="hljs-keyword">let</span> staffInfo = studentInfo <span class="hljs-comment">//6. This means; assign the ref of studentInfo to staffInfo</span>

staffInfo.name = <span class="hljs-string">"Lorry Sante"</span> <span class="hljs-comment">//8. Change the value of name key in the reference which staffInfo holds.</span>

<span class="hljs-built_in">console</span>.log(studentInfo.name) <span class="hljs-comment">//9. Lorry Sante</span>
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong>Try this:</strong> In line 7 and 8, log the value of <a target="_blank" href="http://studentInfo.name"><code>studentInfo.name</code></a> and <a target="_blank" href="http://staffInfo.name"><code>staffInfo.name</code></a> to the console to see what they are.</div>
</div>

<p>You should notice that, changing <code>name</code> in <code>staffInfo</code> object (line 8), causes the name in <code>studentInfo</code> object to change too (as seen in the output of line 9).</p>
<p>In fact, both variables are pointing to the same value technically (see image below);</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691069171621/a53d4f52-6b86-4581-85fc-57452cbc90be.png" alt="reference types variable storage " class="image--center mx-auto" width="1114" height="269" loading="lazy"></p>
<p>When we say that a variable is passed by reference<strong>,</strong> it means that anywhere that variable is used, you are interacting with a reference (that points) to its actual value.</p>
<p>So in the code snippet above, when <code>studentInfo</code> was assigned to <code>staffInfo</code>, we just made <code>staffInfo</code> to store the reference of the <code>studentInfo</code> variable, effectively saying that both <code>staffInfo</code> and <code>studentInfo</code> variables are pointing to the same value.</p>
<p>Therefore, if the reference generated for <code>studentInfo</code> is <code>000xx2</code> and it is true that during execution, variables are replaced by whatever they hold, then <code>staffInfo = studentInfo</code> would become <code>staffInfo = 000xx2</code> during execution, while <code>staffInfo.name</code> would become <code>000xx2.name</code>.</p>
<p>If we had written <code>studentInfo.name</code>, then during execution, it becomes <code>000xx2.name</code>, it should be clear now that both <code>studentInfo</code> and <code>staffInfo</code> holds references to one value. They are like different roads to one destination.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">If this is your first time learning this concept, you should repeat the section above before you proceed. It will become clearer and when we start operating with reference types, you'll be glad you read this article.</div>
</div>

<p>There are three main reference data types that you'll mostly come across in your journey as a JavaScript developer: Object, Array, and Function. Let's look into them one after the other.</p>
<ul>
<li><strong>OBJECT</strong>: An object is a data structure used to store complex data in key/value pairs. The variable created in the previous session has an object type like this:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> studentInfo = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">205</span>
}
</code></pre>
<p>You can see that it isn't primitive (simple). Unlike primitive types with just simple values, an object can be used to store different information which can be made up of even primitive and reference types.</p>
<p>Objects store data in key/value pairs like so: <code>{key: value}</code></p>
<p>In the code snippet above, <code>name</code> is key, while <code>"John Doe"</code> is its value. Also, <code>age</code> is key, while <code>205</code> is its value.</p>
<p>If you notice, both <code>name</code> and <code>age</code> have primitive values (string and number).</p>
<p>To access the value of an object, we use the object name, dot (.) notation, and the key whose value we want to access. For example: <code>objectName.key</code>.</p>
<p>Objects can also contain nested objects like so:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> studentInfo = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">205</span>,
    <span class="hljs-attr">beneficiary</span>: {
       <span class="hljs-attr">name</span>: <span class="hljs-string">"Tira Doe"</span>,
       <span class="hljs-attr">age</span>: <span class="hljs-number">200</span>,
       <span class="hljs-attr">relationship</span>: <span class="hljs-string">"Wife"</span>
    }
}
</code></pre>
<p>In the above example, the <code>studentInfo</code> object has a nested object called <code>beneficiary</code>. <code>beneficiary</code> is a key whose value is an object (reference type). Objects can still hold arrays and functions too.</p>
<p>Accessing the value associated with a key in an object within another object (nested object) is natural. We simply use dot notation. Like so: <code>parentObjectName.nestedObjectName.key</code></p>
<p>For example, to access the name of the beneficiary in <code>studentInfo</code> object above, we simply write <code>studentInfo.beneficiary.name</code>.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">There's no limit to nesting objects in objects. However, ensure that nesting is necessary for what you want to achieve and too much nesting should be avoided for simplicity.</div>
</div>

<p>This is not all that you need to know about objects but it is a very sound way to start.</p>
<ul>
<li><strong>ARRAY</strong>: An array is a kind of object but stores data using automatically assigned indexes instead of keys.</li>
</ul>
<p>An array is created by writing a comma-separated list of values enclosed with square brackets: <code>[0, 1, 2, 3, "Tosin", "Mike", {name: "Abel Joe", age: 250}]</code></p>
<p>If you pay close attention to the values used in the array above, you'll notice that they are of different data types. Yes, arrays also allow you to store values of different types in one place but this is strongly discouraged (you shouldn't do it at all). The values in an array should all be of the same type<strong><em>.</em></strong></p>
<p>Example of a proper array: <code>let scores = [1, 3, 5, 6, 9, 12]</code></p>
<p>To access a value in an array, we simply specify the array name, followed by a square bracket <code>[]</code> without any space between the name and the bracket. Then inside the square bracket, provide the index of the value you wish to access. That is: <code>arrayName[index]</code>.</p>
<p>What's an index and how do we know what index refers to the value we want to access?</p>
<p>An index is simply a number automatically assigned to an array value<strong>.</strong> You can think of it as an address for values in the array. Arrays are <code>0</code> indexed (meaning they start counting from zero)<strong>.</strong></p>
<p>To determine the index of the value you wish to access, start counting from the start of the array and your count should start from 0.</p>
<p>Consider the image below;</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691072847798/ca5bc276-f024-40eb-b69e-b8e31f17314f.png" alt="array and indexes" width="483" height="183" loading="lazy"></p>
<p>To access the value <code>80</code> in the <code>scores</code> array depicted in the image above, we simply write <code>scores[3]</code></p>
<p>There is a lot you can do with arrays as a JavaScript developer. For now, this is a simple introduction to the array data type.</p>
<ul>
<li><strong>FUNCTION</strong>: A function is a different kind of variable and it's declared differently (using the <code>function</code> keyword instead of <code>let</code>, <code>const</code> or <code>var</code>). It is a construct used to carry out a specific task.</li>
</ul>
<p>For example, if you need to add two numbers together multiple times within your code, it's best practice to create a dedicated function for this task. By reusing this function, you avoid redundant code and improve code maintainability compared to repeatedly writing the addition logic. Wait!!! You are not lost. The example below will confirm this 😊</p>
<p>Scenario 1 (without function):</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> num1 = <span class="hljs-number">2</span>;
<span class="hljs-keyword">let</span> num2 = <span class="hljs-number">3</span>;
<span class="hljs-keyword">let</span> result = num1 + num2;

<span class="hljs-built_in">console</span>.log(result) <span class="hljs-comment">// 5</span>

<span class="hljs-keyword">let</span> num3 = <span class="hljs-number">3</span>;
<span class="hljs-keyword">let</span> num4 = <span class="hljs-number">8</span>;
<span class="hljs-keyword">let</span> result2 = num3 + num4;

<span class="hljs-built_in">console</span>.log(result2) <span class="hljs-comment">// 11</span>
</code></pre>
<p>Scenario 2 (with function):</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// function declaration.</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span> (<span class="hljs-params">num1, num2</span>) </span>{
    <span class="hljs-keyword">return</span> num1 + num2;
}

<span class="hljs-built_in">console</span>.log(addNumbers(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)); <span class="hljs-comment">// 5</span>
<span class="hljs-built_in">console</span>.log(addNumbers(<span class="hljs-number">3</span>, <span class="hljs-number">8</span>)); <span class="hljs-comment">// 11</span>
</code></pre>
<p>You will agree that, scenario 2 contains less code, looks neater, and even feels more natural.</p>
<p>Functions allow us write helpers that we can call to get a specific job done for us any time we want. We just have to tell it how to do the job once and call it anytime we need it to do that job (passing in any information required for the task as arguments) and it delivers.</p>
<p>Function Syntax:</p>
<p>To write a function, we use the <code>function</code> keyword, followed by the name of the function: <code>functionName</code>, a pair of brackets <code>()</code>, and a pair of curly braces <code>{}</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">functionName</span> (<span class="hljs-params"></span>) </span>{}
</code></pre>
<p>There are a few things/conventions you should have in mind when writing functions:</p>
<ul>
<li><p>Function names should follow the same naming rules as variables.</p>
</li>
<li><p>Function names should be verbs (to depict an action).</p>
</li>
<li><p>The code logic for the actual task should be written between the opening <code>{</code> and closing <code>}</code> curly braces.</p>
</li>
<li><p>If there are values required to carry out the task, they should be passed into the function as arguments. In this case, during the function declaration, parameters should be stated between the opening <code>(</code> and closing <code>)</code> brackets in a comma-separated fashion. That is: <code>function addNumbers(num1, num2)...</code>.</p>
</li>
<li><p>If no data is required to carry out the task, then the opening <code>(</code> and closing <code>)</code> brackets should be left empty: <code>function sayHi()...</code>.</p>
</li>
</ul>
<p>A parameter is a variable defined between the opening <code>(</code> and closing <code>)</code> of a function during its declaration: <code>function doSomething (param1, param2) {...}</code>.</p>
<p>An argument is the value passed into the function during its invocation/call: <code>doSomething(1, 2)</code></p>
<p>As seen above, to call/invoke a function, write the function name, followed by an opening and a closing bracket (without any whitespace). Required arguments should be provided between the opening and closing brackets (if any).</p>
<p>To drive this concept home, let's create a function to multiply two digits:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//        functionName   param1 param2</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiplyNumbers</span> (<span class="hljs-params">num1, num2</span>) </span>{
    <span class="hljs-keyword">return</span> num1 * num2; <span class="hljs-comment">// task to carry out.</span>
}
</code></pre>
<p>It's as simple as that.</p>
<p>Having done that, let's call/invoke the function.</p>
<pre><code class="lang-javascript">multiplyNumbers(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>) <span class="hljs-comment">// 6</span>
</code></pre>
<p>Notice that while creating the function, we declared two parameters: <code>num1</code> and <code>num2</code>. When calling the function, we assigned values to the two arguments: 1 and 2.</p>
<p><code>return</code> <strong>keyword</strong></p>
<p>Functions may return values or not.</p>
<p>If a function contains a <code>return</code> statement, like the <code>multiplyNumbers</code> function, then it will return a value if everything goes well. If there is no return statement for the function, it will return <code>undefined</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHi</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hi"</span>);
}
</code></pre>
<p>If we invoke <code>sayHi</code>, it would log the text <code>Hi</code> to the console and it will also return <code>undefined</code>.</p>
<p>Remember that functions are like helpers, when you send a helper to carry out an assignment, you may require them to give you feedback (the result of the task they carried out) or you may not need feedback.</p>
<p>If you need feedback, add a <code>return</code> statement about what feedback you need. Otherwise, do not add a <code>return</code> statement to the function.</p>
<p>There is still a lot to learn about every data type we have highlighted in this article so take your time to practice these basics and when you feel comfortable enough using them, you'll see the need to dive deeper.</p>
<h2 id="heading-summary">Summary</h2>
<p>Variables are "pointers" to values. When you mention (use) a variable anywhere in your code, the variable identifier (name) is replaced with the value it points to. It's just like calling someone's name. The name doesn't respond, the person (value) behind the name is what you hope to get as a response.</p>
<p>By way of retention, do not try to cram all these rules and conventions. Feel free to refer back to this article when programming and in a short amount of time, you'll be used to all of them and you won't need to refer to any article ever again to name your variables properly.</p>
<p>If you should have anything in mind, remember to start variables with a lowercase letter if the variable is made of multiple words, subsequent words should start with uppercase letters. That is: <code>age</code>, <code>dateOfBirth</code>.</p>
<p>To create a variable, use the keyword <code>let</code>, <code>const</code>, or <code>var</code>, followed by the variable name. If you wish to initialize the variable, then on the same line before the semi-colon, input the assignment operator and variable value after it.</p>
<p>For example: <code>let score;</code> or <code>let score = 3;</code> (if you wish to initialize during declaration).</p>
<p>If you wish to use a variable, just mention its name and the value will be used during the execution of your code.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-number">2</span>;
<span class="hljs-keyword">let</span> b = <span class="hljs-number">3</span>;
<span class="hljs-built_in">console</span>.log(a + b) <span class="hljs-comment">// 4</span>
</code></pre>
<p>This article also showed you the different data types in JavaScript and how to use them.</p>
<p>Did this post help? Let’s keep the conversation going. Feel free to share your thoughts or questions on Twitter (x) or LinkedIn. You can find me on Twitter (x) <a target="_blank" href="https://x.com/asoluka_tee">@asoluka_tee</a> and <a target="_blank" href="https://www.linkedin.com/in/tochukwu-austin-asoluka-415326155/">Tochukwu Austin Asoluka</a> on LinkedIn.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How To Use CSS Variables – Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ If you are building websites or web apps, you should already know that code repetition is considered a bad practice. That's why you should learn how to use CSS variables to reduce the amount of CSS code you write and take your styling to a new level.... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-css-variables/</link>
                <guid isPermaLink="false">66bc4d1860ad5c1520c1668d</guid>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ variables ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Matéu.sh ]]>
                </dc:creator>
                <pubDate>Tue, 02 Apr 2024 19:53:03 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/03/CSS-Variables.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you are building websites or web apps, you should already know that code repetition is considered a bad practice.</p>
<p>That's why you should learn how to use CSS variables to reduce the amount of CSS code you write and take your styling to a new level.</p>
<p>The most successful web apps have spectacular designs. Unfortunately, to reach the desired effects, web developers need to prepare large amounts of styles. This forces us to repeat values, such as colors, in many different elements. </p>
<p>Fortunately, modern stylesheets support CSS variables, which lets you reduce repetition in your codebase. You don't need external tools such CSS modules, Less or SASS to take advantage of it. </p>
<p>In this comprehensive guide, I'm going to show you how to effectively use CSS variables, covering basic examples in plain HTML and CSS to more advanced frameworks like React and Next.js.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>This guide is dedicated to beginners so you don't need any special knowledge to benefit from it. </p>
<p>I included a few examples in React and Next.js and they are dedicated to beginner React developers. Only those examples will require basic React knowledge to understand them. Feel free to skip them if you don't work with React.</p>
<h2 id="heading-what-are-css-variables">What are CSS Variables?</h2>
<p>CSS variables (officially called CSS custom properties) allow developers to manage and reuse values in CSS stylesheets. Web developers can define reusable variables that can use be used across many CSS files, making code easier to update. CSS variables make it super easy to implement features such as dark mode.</p>
<p>Modern websites require large amounts of styles and this results in repeated CSS values in many different stylesheets. The ecosystem was working hard to address this issue by inventing tools such as SASS, Less and CSS modules but all of those tools have a flaw – they need to be compiled to CSS files in the end.</p>
<p>Fortunately, thanks to CSS variables, we can simplify our stylesheets without sophisticated tools and build processes.</p>
<h2 id="heading-how-to-create-css-variables">How To Create CSS Variables</h2>
<p>Defining a CSS variable is quite simple. You can define a CSS variable using the <code>--</code> prefix followed by a name of your choice, then assigning it a value using the <code>var()</code> function. </p>
<p>Here's how you do it:</p>
<pre><code class="lang-css"><span class="hljs-selector-pseudo">:root</span> {
  <span class="hljs-comment">/* Backgrounds */</span>
  <span class="hljs-attribute">--primary-background</span>: <span class="hljs-number">#faf8ef</span>;
  <span class="hljs-comment">/* Colors */</span>
  <span class="hljs-attribute">--primary-text-color</span>: <span class="hljs-number">#776e65</span>;
}
</code></pre>
<p>As you can see, I defined CSS variables inside the <code>:root</code> pseudo-class to make them globally available. </p>
<p>Each variable started with <code>--</code>, followed by a name: <code>--primary-background</code> or <code>--primary-text-color</code>. Lastly, I assigned values to those variables.</p>
<p>Using this, I'll be able to change website colors just by modifying the values of those variables.</p>
<h2 id="heading-how-to-use-css-variables">How To Use CSS Variables</h2>
<p>Now let me show you how to use CSS variables to define global background and text color for your website:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">background</span>: <span class="hljs-built_in">var</span>(--primary-background);
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">var</span>(--primary-text-color);
}
</code></pre>
<p>To use a variable, you need to refer to them by using the <code>var()</code> function and passing the variable name as an argument.</p>
<p>That's it! Now your website is using CSS variables to render styles.</p>
<p><strong>Note</strong>: <code>var()</code> helper is a built-in CSS function so you don't need any libraries to use it.</p>
<h2 id="heading-how-to-use-css-variables-in-react">How To Use CSS Variables in React?</h2>
<p>Many web developers build their web apps in React so I will show you how you can get values and update CSS variables in React. Many modern web apps support dark mode and this feature can become one of a React developer's nightmares. </p>
<p>Next, I'll show you an easy method to add a dark mode in React apps just by using CSS variables. </p>
<h3 id="heading-how-to-set-the-value-of-css-variable-in-react">How To Set the Value of CSS Variable in React?</h3>
<p>Changing the value of CSS variables in React might be tricky since React doesn't offer any tools to directly interact with the DOM tree. That's why we'll use plain JavaScript to read and set CSS variables. </p>
<p>Here's how you can set a CSS Variable in React:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Example</span>(<span class="hljs-params"></span>) </span>{
  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">document</span>.documentElement.style.setProperty(<span class="hljs-string">'--primary-background'</span>, <span class="hljs-string">`black`</span>);
    <span class="hljs-built_in">document</span>.documentElement.style.setProperty(<span class="hljs-string">'--primary-text-color'</span>, <span class="hljs-string">`white`</span>);
  }, [])

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{color:</span> "<span class="hljs-attr">var</span>(<span class="hljs-attr">--primary-text-color</span>"}}&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
};
</code></pre>
<p>As you can see, I took advantage of the global <code>document</code> variable to get into the DOM tree and modify style properties. I used <code>setProperty</code> method that requires two arguments:</p>
<ul>
<li>CSS custom property (CSS variable) name.</li>
<li>The value of the variable.</li>
</ul>
<p><strong>Note</strong>: It doesn't matter if you work in React or plain JavaScript, you can always call <code>document.documentElement.style.setProperty</code> to modify CSS variable values. It's a JavaScript built-in function.</p>
<h3 id="heading-how-to-get-the-value-of-css-variables-in-react">How To Get the Value of CSS Variables in React?</h3>
<p>Sometimes you might need to read the value of a CSS variable and store it in React. In this case, I would suggest utilizing <code>useState</code> and <code>useEffect</code> hooks. </p>
<p>Here's how I would approach this issue:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useEffect, setState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Example</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [color, setColor] = useState(<span class="hljs-string">'black'</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> cssColor = <span class="hljs-built_in">document</span>.documentElement.style.getPropertyValue(<span class="hljs-string">'--primary-text-color'</span>);
    setColor(cssColor);
  }, [])

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{color:</span> <span class="hljs-attr">color</span>}}&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
};
</code></pre>
<p>As you can see, I retrieved the value of a <code>--primary-text-color</code> variable to the <code>cssColor</code> constant. In the next line, I updated component's state by using <code>setColor</code> helper created by <code>useState</code> hook. Using the method, my CSS variable can be used easily in React Components.</p>
<p>That's it. Now you can use this variable in your React app.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>CSS variables can be used in different kinds of websites and no JavaScript is needed to take advantage of them. Everybody can benefit of them – no matter their level of experience in web development. Understanding CSS variables can greatly improve your styling experience and make you more efficient.</p>
<p>I hope you liked this article. It would mean the world to me if you share it on your social media.</p>
<p>If you have any questions or just want to hear updates from me, you can find me on <a target="_blank" href="https://twitter.com/msokola">Twitter</a>.</p>
<h2 id="heading-learn-react">Learn React</h2>
<p>If you are still learning React or you want to learn more tricks like this one, you should join my course on Next.js. Next.js is the most popular React framework that powers the most of React app these days. I will teach you how to use it by building an awesome 2048 game with animations. No fluff. Tactics only.</p>
<p>🚀 <strong>Join m</strong>y <a target="_blank" href="https://www.mateu.sh/learn-nextjs">Next.js Crash <strong>Course</strong></a>.</p>
<p>This course includes:</p>
<ul>
<li>🎥 5.5 hours on-demand video</li>
<li>📱 Access on mobile and TV</li>
<li>🗓️ Full lifetime access</li>
<li>🎓 Certificate of completion</li>
</ul>
<p><a target="_blank" href="https://mateu.sh/learn-nextjs"><img src="https://assets.mateu.sh/assets/fcc-css-variables" alt="Click to join the Next.js Crash Course" width="600" height="400" loading="lazy"></a><br><em>Click to get started</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Declare Variables in JavaScript – var, let, and const Explained ]]>
                </title>
                <description>
                    <![CDATA[ Declaring variables is something you'll do all the time in JavaScript. And if you know the variable declaration process inside and out, you'll have the confidence to start writing great JS code. Through this article, you will learn how to declare and... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-declare-variables-in-javascript/</link>
                <guid isPermaLink="false">66ba122a07d2a5882dd9930d</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ variables ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Furkan Emin Can ]]>
                </dc:creator>
                <pubDate>Tue, 07 Nov 2023 22:16:57 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/11/Cover-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Declaring variables is something you'll do all the time in JavaScript. And if you know the variable declaration process inside and out, you'll have the confidence to start writing great JS code.</p>
<p>Through this article, you will learn how to declare and mutate variables using <code>var</code>, <code>let</code>, and <code>const</code>, and you'll get a better understanding of the differences between them.</p>
<p>I will explain each concept in two parts:</p>
<ul>
<li>Before ES6 (<code>var</code> statement)</li>
<li>After ES6 (<code>let</code> and <code>const</code> statements)</li>
</ul>
<p>Let's dive into these different ways of declaring variables in JavaScript so you know how they work and when to use each one.</p>
<h2 id="heading-how-to-declare-variables-in-javascript">How to Declare Variables in JavaScript</h2>
<p>When you declare variables in your app, the interpreter moves them to the top of their scope and allocates places in the memory before the execution starts. This process is called <strong>Hoisting</strong>.</p>
<h3 id="heading-1-how-to-declare-variables-with-var-in-javascript">1. How to declare variables with <code>var</code> in JavaScript:</h3>
<p>When you declare a variable with <code>var</code>, it is hoisted and initialized in the memory as <code>undefined</code> before the code execution. So, you can access the variable before declaring it, but it returns <code>undefined</code>. This is sometimes called <strong>Declaration hoisting</strong>.</p>
<p>When the execution starts and reaches the line where the variable is declared, it replaces the value in memory with the value of the variable.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(strawberry); <span class="hljs-comment">// undefined</span>

<span class="hljs-keyword">var</span> strawberry = <span class="hljs-string">'🍓'</span>;

<span class="hljs-built_in">console</span>.log(strawberry); <span class="hljs-comment">// 🍓</span>
</code></pre>
<p>Under the hood, the code above behaves like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> strawberry;

<span class="hljs-built_in">console</span>.log(strawberry); <span class="hljs-comment">// undefined</span>

strawberry = <span class="hljs-string">'🍓'</span>;

<span class="hljs-built_in">console</span>.log(strawberry); <span class="hljs-comment">// 🍓</span>
</code></pre>
<p>So we can use the <code>strawberry</code> variable before the declaration, but it returns <code>undefined</code>.</p>
<p>With this behavior, the program runs without errors. But in some cases, this can lead to unexpected results. We are only human, and on a busy day you might try to access a variable before declaring it. In a complex program, it can be hard to figure out where a strange <code>undefined</code> comes from.</p>
<h3 id="heading-2-how-to-declare-variables-with-let-and-const-in-javascript">2. How to declare variables with <code>let</code> and <code>const</code> in JavaScript:</h3>
<p>When you declare a variable with <code>let</code> or <code>const</code>, it is also hoisted but it's allocated in the memory as <strong>uninitialized</strong> in the <a target="_blank" href="https://www.freecodecamp.org/news/what-is-the-temporal-dead-zone/">temporal dead zone</a>. You cannot access variables in the temporal dead zone before you've declared them. So, if you try to access a variable before declaring it, the program throws a <code>ReferenceError</code>.</p>
<p>When the program reaches the line where the variable is declared, it initializes it with that value.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(cherry); <span class="hljs-comment">// ReferenceError</span>

<span class="hljs-keyword">const</span> cherry = <span class="hljs-string">"🍒"</span>;

<span class="hljs-built_in">console</span>.log(cherry); <span class="hljs-comment">// 🍒</span>
</code></pre>
<p>If you try to run this code snippet, you will see an error similar to the following one because we tried to access a variable in the temporal dead zone. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/error-1.png" alt="ReferenceError: Cannot access 'cherry' before initialization" width="600" height="400" loading="lazy">
<em>"ReferenceError: Cannot access 'cherry' before initialization"</em></p>
<p>This is a more predictable behavior than the behavior of the <code>var</code> statement.</p>
<h3 id="heading-so-what-do-var-let-and-const-have-in-common">So what do <code>var</code>, <code>let</code>, and <code>const</code> have in common?</h3>
<p>In the previous two sections, you learned the process for declaring <code>var</code>, <code>let</code>, and <code>const</code>. In this section, we will look at the common concepts.</p>
<ul>
<li>You can declare a variable with <code>let</code> and <code>var</code> without a value. In this case, the default value will be <code>undefined</code>.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> tomato;
<span class="hljs-keyword">let</span> potato;

<span class="hljs-built_in">console</span>.log(tomato); <span class="hljs-comment">// undefined</span>
<span class="hljs-built_in">console</span>.log(potato); <span class="hljs-comment">// undefined</span>
</code></pre>
<p>This behavior is not valid for <code>const</code> because an initial value is required for it. If there is no initial value, the program throws a <code>SyntaxError</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> avocado; <span class="hljs-comment">// SyntaxError</span>
</code></pre>
<p>For the code above, an error gets thrown  like this one:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/image-4.png" alt="&quot;SyntaxError: Missing initializer in const declaration&quot;" width="600" height="400" loading="lazy">
<em>SyntaxError: Missing initializer in const declaration</em></p>
<ul>
<li>You can declare a chain of variables using the same statement. Put the statement at the beginning and separate each variable with a comma. This is valid for <code>var</code>, <code>let</code>, and <code>const</code>.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> number1 = <span class="hljs-number">2</span>, number2 = <span class="hljs-number">23</span>, number3 = <span class="hljs-number">99</span>;

<span class="hljs-built_in">console</span>.log(number1); <span class="hljs-comment">// 2</span>
<span class="hljs-built_in">console</span>.log(number2); <span class="hljs-comment">// 23</span>
<span class="hljs-built_in">console</span>.log(number3); <span class="hljs-comment">// 99</span>
</code></pre>
<p>Nowadays, to declare variables, you'll want to use the ES6 statements <code>let</code> and <code>const</code>. You can think of <code>var</code> as the legacy method of doing this.</p>
<p>My recommendation is:</p>
<ul>
<li>Use <code>const</code> as the default.</li>
<li>Use <code>let</code> if the variable will change in the future.</li>
<li>Don't use <code>var</code> if there is no particular use case.</li>
</ul>
<h2 id="heading-javascript-variables-and-scope">JavaScript Variables and Scope</h2>
<p>According to <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Scope">MDN</a>:</p>
<blockquote>
<p>The <strong>scope</strong> is the current context of execution in which values and expressions are "visible" or can be referenced.</p>
</blockquote>
<p>In terms of variables, the scope is where certain variables are available. We can access variables that have been declared in a parent scope in a child scope, but it doesn't work the other way around.</p>
<h3 id="heading-global-scope">Global Scope</h3>
<p><strong>Global Scope</strong> is the main scope that covers all the scopes in a script. Variables declared in the global scope are available in all scopes.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Global Scope</span>

<span class="hljs-keyword">const</span> grapes = <span class="hljs-string">"🍇"</span>;

<span class="hljs-comment">// Functional Scope</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logGrapes</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(grapes); <span class="hljs-comment">// 🍇</span>

  <span class="hljs-comment">// Block Scope in a Functional Scope</span>
  {
    <span class="hljs-built_in">console</span>.log(grapes); <span class="hljs-comment">// 🍇</span>
  }
}

<span class="hljs-comment">// Block Scope</span>
{
  <span class="hljs-built_in">console</span>.log(grapes); <span class="hljs-comment">// 🍇</span>
}
</code></pre>
<p>In the example above, we can access the <code>grapes</code> variable from all child scopes because it is declared in the global scope.</p>
<h3 id="heading-functional-scope">Functional Scope</h3>
<p><strong>Functional scope</strong> is the scope created with a function declaration. Variables declared in a functional scope are only available in that scope and cannot be accessed outside of it. The behavior of <code>var</code>, <code>let</code>, and <code>const</code> are the same in this case. </p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Global Scope</span>

<span class="hljs-comment">// Functional Scope</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createVariables</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> apple = <span class="hljs-string">"🍎"</span>;
  <span class="hljs-keyword">const</span> cherry = <span class="hljs-string">"🍒"</span>;
  <span class="hljs-keyword">let</span> strawberry = <span class="hljs-string">"🍓"</span>;
}

<span class="hljs-built_in">console</span>.log(apple); <span class="hljs-comment">// ReferenceError</span>
<span class="hljs-built_in">console</span>.log(cherry); <span class="hljs-comment">// ReferenceError</span>
<span class="hljs-built_in">console</span>.log(strawberry); <span class="hljs-comment">// ReferenceError</span>
</code></pre>
<p>In the example above, all three variables are only accessible in the functional scope of the <code>createVariables</code> function. If you try to access them outside of the functional scope the program throws a <code>ReferenceError</code>.</p>
<h3 id="heading-block-scope">Block Scope</h3>
<p><strong>Block scope</strong> is the scope that is created with a pair of curly braces. Block scope is only valid for <code>let</code> and <code>const</code>, not <code>var</code>. When you declare a variable with <code>var</code> it is moved to the global scope or the nearest functional scope if it exists.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Block Scope</span>
{
  <span class="hljs-keyword">const</span> banana = <span class="hljs-string">"🍌"</span>;

  <span class="hljs-comment">// Block Scope in a Block Scope</span>
  {
    <span class="hljs-built_in">console</span>.log(banana); <span class="hljs-comment">// 🍌</span>

    <span class="hljs-keyword">var</span> carrot = <span class="hljs-string">"🥕"</span>;
    <span class="hljs-keyword">let</span> lemon = <span class="hljs-string">"🍋"</span>;
  }

  <span class="hljs-built_in">console</span>.log(carrot); <span class="hljs-comment">// 🥕</span>
  <span class="hljs-built_in">console</span>.log(lemon); <span class="hljs-comment">// ReferenceError</span>
}
</code></pre>
<p>In the example above:</p>
<ul>
<li>We can access the <code>banana</code> variable that we declared with <code>const</code> in the parent scope in the child scope.</li>
<li>We can access the <code>carrot</code> variable declared with <code>var</code> in the child scope in the parent scope because the program moves it to the global scope.</li>
<li>We can't access the <code>lemon</code> variable declared with <code>let</code> in the child scope in the parent scope because it cannot be accessed outside of the scope in which it's declared. If try to do that, the program throws a <code>ReferenceError</code>.</li>
</ul>
<h2 id="heading-how-to-mutate-variables-in-javascript">How to Mutate Variables in JavaScript</h2>
<p>In this section, we'll talk about the <code>var</code> and <code>let</code> statements together, and then discuss how the <code>const</code> statement behaves. This is because the variables declared with <code>var</code> and <code>let</code> are mutable (that is, they can be changed), while variables declared with <code>const</code> are immutable.</p>
<h3 id="heading-1-mutation-in-var-and-let-statements">1. Mutation in <code>var</code> and <code>let</code> statements</h3>
<p>As I said, the variables declared with <code>var</code> and <code>let</code> are mutable, which means that you can assign new values to them. Here's what I mean:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> pepper = <span class="hljs-string">"🌶️"</span>;
<span class="hljs-keyword">let</span> apple = <span class="hljs-string">"🍏"</span>;

pepper = <span class="hljs-string">"🫑"</span>;
apple = <span class="hljs-string">"🍎"</span>;

<span class="hljs-built_in">console</span>.log(pepper); <span class="hljs-comment">// 🫑</span>
<span class="hljs-built_in">console</span>.log(apple); <span class="hljs-comment">// 🍎</span>
</code></pre>
<p>In the example above, we mutated the <code>pepper</code> and <code>apple</code> variables, and they were assigned new values.</p>
<h3 id="heading-2-mutation-in-const-statement">2. Mutation in <code>const</code> statement</h3>
<p>Variables declared with <code>const</code> are immutable. So you cannot assign new values to them once you've declared them.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> strawberry = <span class="hljs-string">"🍓"</span>;

strawberry = <span class="hljs-string">"🍉"</span>; <span class="hljs-comment">// TypeError</span>
</code></pre>
<p>If you try to run the code snippet above, the program throws an error like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/error-3.png" alt="TypeError: Assignment to constant variable." width="600" height="400" loading="lazy">
<em>"TypeError: Assignment to constant variable."</em></p>
<p>Objects are an exception for the immutability of the <code>const</code> statement because they have properties and methods, unlike <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive">primitives</a>.</p>
<p>You cannot mutate them via assignment but can mutate them via their methods and property assignment. Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruits = [<span class="hljs-string">"🍎"</span>, <span class="hljs-string">"🍐"</span>];
<span class="hljs-keyword">const</span> fruitEmojiMap = {
  <span class="hljs-attr">apple</span>: <span class="hljs-string">"🍎"</span>,
  <span class="hljs-attr">pear</span>: <span class="hljs-string">"🍐"</span>,
};

fruits[<span class="hljs-number">2</span>] = <span class="hljs-string">"🍒"</span>; <span class="hljs-comment">// [ '🍎', '🍐', '🍒' ]</span>
fruits.push(<span class="hljs-string">"🍌"</span>); <span class="hljs-comment">// [ '🍎', '🍐', '🍒', '🍌' ]</span>

fruitEmojiMap.cherry = <span class="hljs-string">"🍒"</span>; <span class="hljs-comment">// { apple: '🍎', pear: '🍐', cherry: '🍒' }</span>
</code></pre>
<p>In the code example above,</p>
<ul>
<li>We added two new fruits to the <code>fruits</code> array via property assignment, and used the <code>push</code> method of the <code>Array</code> object.</li>
<li>We added a new fruit to the <code>fruitEmojiMap</code> object via property assignment.</li>
</ul>
<p>A little note: you can use the <code>[Object.freeze()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze)</code> method to achieve complete immutability for objects.</p>
<h2 id="heading-how-to-redeclare-variables-in-javascript">How to Redeclare Variables in JavaScript</h2>
<p>Redeclaring a variable with the same name in the same scope is likely something you don't want to do intentionally, and I've never found a real use case for it.</p>
<p>But strangely, we can redeclare variables declared with <code>var</code> using the same name in the same scope. This is another error-prone characteristic of the <code>var</code> statement. Fortunately, this behavior was changed with the <code>let</code> and <code>const</code> statements.</p>
<h3 id="heading-1-how-to-redeclare-variables-with-var"><strong>1.</strong> How to redeclare variables with <code>var</code></h3>
<p>You can redeclare a variable declared with <code>var</code> in the same scope or child-parent scopes. The variable will be affected in the global scope, or functional scope if it is declared in a function.</p>
<p>So even if you redeclare a variable in the child scope, the variable will change in all scopes where that variable is available.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Global Scope</span>
<span class="hljs-keyword">var</span> pepper = <span class="hljs-string">"🌶️"</span>;

<span class="hljs-built_in">console</span>.log(pepper); <span class="hljs-comment">// 🌶️</span>

<span class="hljs-comment">// Block Scope</span>
{
  <span class="hljs-keyword">var</span> pepper = <span class="hljs-string">"🥦"</span>;

  <span class="hljs-built_in">console</span>.log(pepper); <span class="hljs-comment">// 🥦</span>
}

<span class="hljs-built_in">console</span>.log(pepper); <span class="hljs-comment">// 🥦</span>
</code></pre>
<p>In the example above, we declared a new <code>pepper</code> variable in the block scope and assigned it a different value. This affects the variable in the global scope and we lose access to the previous variable.</p>
<p>This behavior tends to cause big problems. Because someone working in the same codebase may unintentionally declare a variable using the same name used before.</p>
<p>The process is a bit different if you make the redeclaration in a function. The variable outside of the function remains the same and the variable inside the function cannot affect it. As I said, variables declared with <code>var</code> in a function are in functional scope and don't affect the outside.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Global Scope</span>
<span class="hljs-keyword">var</span> onion = <span class="hljs-string">"🧅"</span>;

<span class="hljs-comment">// Functional Scope</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">redeclareOnion</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> onion = <span class="hljs-string">"🧄"</span>;

  <span class="hljs-built_in">console</span>.log(onion); <span class="hljs-comment">// 🧄</span>
}

<span class="hljs-built_in">console</span>.log(onion); <span class="hljs-comment">// 🧅</span>
</code></pre>
<p>In the example above, even though we declared a new variable using the same name as the <code>onion</code> variable inside a function, the <code>onion</code> variable declared in the global scope remained the same.</p>
<h3 id="heading-2-how-to-redeclare-variables-with-let-and-const">2. How to redeclare variables with <code>let</code> and <code>const</code></h3>
<p>You cannot redeclare variables declared with <code>let</code> or <code>const</code> in the same scope. If you try to do so, the program throws a <code>SyntaxError</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> eggplant = <span class="hljs-string">"🍆"</span>;

<span class="hljs-keyword">let</span> eggplant = <span class="hljs-string">"🥔"</span>; <span class="hljs-comment">// SyntaxError</span>
</code></pre>
<p>In the example above, we tried to redeclare the <code>eggplant</code> variable in the same scope, and the program threw the following error:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/image-17.png" alt="SyntaxError: Identifier 'eggplant' has already been declared" width="600" height="400" loading="lazy">
<em>"SyntaxError: Identifier 'eggplant' has already been declared"</em></p>
<p>But you can redeclare variables using <code>let</code> and <code>const</code> in child scopes. Because the variables declared with <code>let</code> and <code>const</code> are block scope and don't affect the parent scopes.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Global Scope</span>
<span class="hljs-keyword">const</span> carrot = <span class="hljs-string">"🥕"</span>;

<span class="hljs-comment">// Block Scope</span>
{
  <span class="hljs-keyword">const</span> carrot = <span class="hljs-string">"🍒"</span>;

  <span class="hljs-built_in">console</span>.log(carrot); <span class="hljs-comment">// 🍒</span>
}

<span class="hljs-built_in">console</span>.log(carrot); <span class="hljs-comment">// 🥕</span>
</code></pre>
<p>In the example above, we declared two <code>carrot</code> variables. The first one is in the global scope and the second one is in the block scope with a different value. The variable in the global scope remains the same and the variable in the block scope is a standalone new variable.</p>
<p>The downside is that we lost access to the <code>carrot</code> variable declared in the global scope, in the block scope. If we need this variable in the future we can't access the variable.</p>
<p>So, most of the time, it is better to declare a variable with a unique name.</p>
<h3 id="heading-3-how-to-redeclare-variables-by-mixing-statements">3. How to Redeclare Variables by Mixing Statements</h3>
<p>Briefly, you shouldn't mix statements. This section is intended to give you information rather than really show you how the process is done.</p>
<p>You cannot create variables by mixing statements using the same name in the same scope. If you try it, the program throws a <code>SyntaxError</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> banana = <span class="hljs-string">"🍌"</span>;

<span class="hljs-keyword">var</span> banana = <span class="hljs-string">"🍋"</span>; <span class="hljs-comment">// SyntaxError</span>
</code></pre>
<p>In the example above, we tried to redeclare the <code>banana</code> variable declared with <code>const</code> with <code>var</code>, but the program threw an error similar to the one below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/image-16.png" alt="SyntaxError: Identifier 'banana' has already been declared" width="600" height="400" loading="lazy">
<em>"SyntaxError: Identifier 'banana' has already been declared"</em></p>
<p>Also, you cannot declare a variable with <code>var</code> using the same name as one already declared in a parent scope using <code>let</code> or <code>const</code>. As I said, <code>var</code> is global scope and affects the variable declared in parent scopes unless it is inside a function.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Global Scope</span>
<span class="hljs-keyword">let</span> pineapple = <span class="hljs-string">"🍍"</span>;

<span class="hljs-comment">// Functional Scope</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">declarePineapple</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> pineapple = <span class="hljs-string">"🍏"</span>; <span class="hljs-comment">// This is okay</span>
}

<span class="hljs-comment">// Block Scope</span>
{
  <span class="hljs-keyword">var</span> pineapple = <span class="hljs-string">"🍎"</span>; <span class="hljs-comment">// SyntaxError</span>
}
</code></pre>
<p>In the example above, we tried to redeclare the <code>pineapple</code> variable in two places:</p>
<ul>
<li>In the function, which we did successfully.</li>
<li>But in the child block scope, the program threw the following error:</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/image-19.png" alt="SyntaxError: Identifier 'pineapple' has already been declared" width="600" height="400" loading="lazy">
<em>"SyntaxError: Identifier 'pineapple' has already been declared"</em></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>These days, <code>let</code> and <code>const</code> are the default choice for variable declaration in JavaScript. But you might still encounter the <code>var</code> statement, especially in older apps. So you'll need to know how to handle it.</p>
<p>In this guide, you have learned the differences between <code>var</code>, <code>let</code>, and <code>const</code>. We also talked about hoisting and scope in variable declaration.</p>
<p>See you in the next one!</p>
<h3 id="heading-stay-in-touch">Stay in Touch</h3>
<p>You can connect with me on <a target="_blank" href="https://twitter.com/femincan">Twitter</a>, and you can read more tutorials like this one <a target="_blank" href="https://femincan.dev">on my blog here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Variables – The Complete Beginner's Guide ]]>
                </title>
                <description>
                    <![CDATA[ Variables are an essential part of Python. They allow us to easily store, manipulate, and reference data throughout our projects. This article will give you all the understanding of Python variables you need to use them effectively in your projects. ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-variables/</link>
                <guid isPermaLink="false">66d037ae2b211a17e00e36f3</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ variables ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Reed ]]>
                </dc:creator>
                <pubDate>Wed, 22 Mar 2023 18:30:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/mugshotbot.com_customize_color-yellow-image-9820e115-mode-light-pattern-texture-theme-two_up-url-https___gifcoins.io.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Variables are an essential part of Python. They allow us to easily store, manipulate, and reference data throughout our projects.</p>
<p>This article will give you all the understanding of Python variables you need to use them effectively in your projects.</p>
<p>If you want the most convenient way to review all the topics covered here, I've put together a helpful cheatsheet for you right here:</p>
<p><strong><a target="_blank" href="https://reedbarger.com/resources/python-variables">Download the</a></strong> Python variables cheatsheet (it takes 5 seconds).</p>
<h2 id="heading-what-is-a-variable-in-python">What is a Variable in Python?</h2>
<p>So what are variables and why do we need them?</p>
<p>Variables are essential for holding onto and referencing values throughout our application. By storing a value into a variable, you can reuse it as many times and in whatever way you like throughout your project. </p>
<p>You can think of variables as boxes with labels, where the label represents the variable name and the content of the box is the value that the variable holds.</p>
<p>In Python, variables are created the moment you give or <strong>assign</strong> a value to them.</p>
<h2 id="heading-how-do-i-assign-a-value-to-a-variable">How Do I Assign a Value to a Variable?</h2>
<p>Assigning a value to a variable in Python is an easy process. </p>
<p>You simply use the equal sign <code>=</code> as an assignment operator, followed by the value you want to assign to the variable. Here's an example:</p>
<pre><code class="lang-python">country = <span class="hljs-string">"United States"</span>
year_founded = <span class="hljs-number">1776</span>
</code></pre>
<p>In this example, we've created two variables: <code>country</code> and <code>year_founded.</code> We've assigned the string value "United States" to the <code>country</code> variable and integer value 1776 to the <code>year_founded</code> variable.</p>
<p>There are two things to note in this example:</p>
<ol>
<li>Variables in Python are <strong>case-sensitive</strong>. In other words, watch your casing when creating variables, because <code>Year_Founded</code> will be a different variable than <code>year_founded</code> even though they include the same letters</li>
<li>Variable names that use multiple words in Python should be separated with an underscore <code>_</code><em>.</em> For example, a variable named "site name" should be written as "site<em>name"</em>._ This convention is called <strong>snake case</strong> (very fitting for the "Python" language).</li>
</ol>
<h2 id="heading-how-should-i-name-my-python-variables">How Should I Name My Python Variables?</h2>
<p>There are some rules to follow when naming Python variables. </p>
<p>Some of these are hard rules that must be followed, otherwise your program will not work, while others are known as <strong>conventions</strong>. This means, they are more like suggestions.</p>
<h3 id="heading-variable-naming-rules">Variable naming rules</h3>
<ol>
<li>Variable names must start with a letter or an underscore <code>_</code> character.</li>
<li>Variable names can only contain letters, numbers, and underscores.</li>
<li>Variable names cannot contain spaces or special characters.</li>
</ol>
<pre><code class="lang-python">user_age = <span class="hljs-number">20</span> <span class="hljs-comment"># valid</span>

website = <span class="hljs-string">'https://freecodecamp.org'</span> <span class="hljs-comment"># valid</span>

<span class="hljs-number">1</span>password = <span class="hljs-literal">True</span> <span class="hljs-comment"># invalid</span>
</code></pre>
<h3 id="heading-variable-naming-conventions">Variable naming conventions</h3>
<ol>
<li>Variable names should be descriptive and not too short or too long.</li>
<li>Use lowercase letters and underscores to separate words in variable names (known as "snake_case").</li>
</ol>
<h2 id="heading-what-data-types-can-python-variables-hold">What Data Types Can Python Variables Hold?</h2>
<p>One of the best features of Python is its flexibility when it comes to handling various data types.</p>
<p>Python variables can hold various data types, including integers, floats, strings, booleans, tuples and lists:</p>
<p><strong>Integers</strong> are whole numbers, both positive and negative.</p>
<pre><code class="lang-python">answer = <span class="hljs-number">42</span>
</code></pre>
<p><strong>Floats</strong> are real numbers or numbers with a decimal point.</p>
<pre><code class="lang-python">weight = <span class="hljs-number">34.592</span>
</code></pre>
<p><strong>Strings</strong> are sequences of characters, namely words or sentences.</p>
<pre><code class="lang-python">message = <span class="hljs-string">"Hello Python"</span>
</code></pre>
<p><strong>Booleans</strong> are True or False values.</p>
<pre><code class="lang-python">is_authenticated = <span class="hljs-literal">True</span>
</code></pre>
<p><strong>Lists</strong> are ordered, mutable collections of values.</p>
<pre><code class="lang-python">fruits = [<span class="hljs-string">'apple'</span>, <span class="hljs-string">'banana'</span>, <span class="hljs-string">'cherry'</span>]
</code></pre>
<p><strong>Tuples</strong> are ordered, immutable collections of values.</p>
<pre><code class="lang-python">point = (<span class="hljs-number">3</span>, <span class="hljs-number">4</span>)
</code></pre>
<p>There are more data types in Python, but these are the most common ones you will encounter while working with Python variables.</p>
<h2 id="heading-python-is-dynamically-typed">Python is Dynamically Typed</h2>
<p>Python is what is known as a <strong>dynamically-typed</strong> language. This means that the type of a variable can change during the execution of a program. </p>
<p>Another feature of dynamic typing is that it is not necessary to manually declare the type of each variable, unlike other programming languages such as Java.</p>
<p>You can use the <code>type()</code> function to determine the type of a variable. For instance:</p>
<pre><code class="lang-python">print(type(answer))  <span class="hljs-comment"># Output: &lt;class 'int'&gt;</span>
print(type(message))  <span class="hljs-comment"># Output: &lt;class 'str'&gt;</span>
</code></pre>
<h2 id="heading-what-operations-can-be-performed">What Operations Can Be Performed?</h2>
<p>Variables can be used in various operations, which allows us to transform them mathematically (if they are numbers), change their string values through operations like concatenation, and compare values using equality operators.</p>
<h3 id="heading-mathematic-operations">Mathematic Operations</h3>
<p>It's possible to perform basic mathematic operations with variables, such as addition, subtraction, multiplication, and division:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Arithmetic operations</span>
a = <span class="hljs-number">10</span>
b = <span class="hljs-number">5</span>

sum = a + b
difference = a - b
product = a * b
quotient = a / b

print(sum, difference, product, quotient)  <span class="hljs-comment"># Output: 15 5 50 2.0</span>
</code></pre>
<p>It's also possible to find the remainder of a division operation by using the modulus <code>%</code> operator as well as create exponents using the <code>**</code> syntax:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Modulus operation</span>
remainder = a % b
print(remainder)  <span class="hljs-comment"># Output: 0</span>

<span class="hljs-comment"># Exponentiation</span>
power = a ** b
print(power)  <span class="hljs-comment"># Output: 100000</span>
</code></pre>
<h3 id="heading-string-operators">String operators</h3>
<p>Strings can be added to one another or <strong>concatenated</strong> using the <code>+</code> operator.</p>
<pre><code class="lang-python"><span class="hljs-comment"># String concatenation</span>
first_name = <span class="hljs-string">"Guido"</span>
last_name = <span class="hljs-string">"van Rossum"</span>
full_name = first_name + <span class="hljs-string">" "</span> + last_name
print(full_name)  <span class="hljs-comment"># Output: Guido van Rossum</span>
</code></pre>
<h3 id="heading-equality-comparisons">Equality comparisons</h3>
<p>Values can also be compared in Python using the <code>&lt;</code>, <code>&gt;</code>, <code>==</code>, and <code>!=</code> operators. </p>
<p>These operators, respectively, compare whether values are less than, greater than, equal to, or not equal to each other.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Comparison operations</span>
x = <span class="hljs-number">15</span>
y = <span class="hljs-number">20</span>

print(x &lt; y)  <span class="hljs-comment"># Output: True</span>
print(x &gt; y)  <span class="hljs-comment"># Output: False</span>
print(x == y)  <span class="hljs-comment"># Output: False</span>
print(x != y)  <span class="hljs-comment"># Output: True</span>
</code></pre>
<p>Finally, note that when performing operations with variables, you need to ensure that the types of the variables are compatible with each other. </p>
<p>For example, you cannot directly add a string and an integer. You would need to convert one of the variables to a compatible type using a function like <code>str()</code> or <code>[int()](https://www.freecodecamp.org/news/python-string-to-int-convert-a-string-example/)</code>. </p>
<h2 id="heading-variable-scope">Variable Scope</h2>
<p>The scope of a variable refers to the parts of a program where the variable can be accessed and modified. In Python, there are two main types of variable scope:</p>
<p><strong>Global scope</strong>: Variables defined outside of any function or class have a global scope. They can be accessed and modified throughout the program, including within functions and classes.</p>
<pre><code class="lang-python">global_var = <span class="hljs-string">"I am a global variable"</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">access_global_var</span>():</span>
    print(global_var)

access_global_var()  <span class="hljs-comment"># Output: I am a global variable</span>
</code></pre>
<p><strong>Local scope</strong>: Variables defined within a function or class have a local scope. They can only be accessed and modified within that function or class.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">function_with_local_var</span>():</span>
    local_var = <span class="hljs-string">"I am a local variable"</span>
    print(local_var)

function_with_local_var()  <span class="hljs-comment"># Output: I am a local variable</span>
print(local_var)  <span class="hljs-comment"># Error: NameError: name 'local_var' is not defined</span>
</code></pre>
<p>In this example, attempting to access <code>local_var</code> outside of the <code>function_with_local_var</code> function results in a <code>NameError</code>, as the variable is not defined in the global scope.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Don't be afraid to experiment with different types of variables, operations, and scopes to truly grasp their importance and functionality. The more you work with Python variables, the more confident you'll become in applying these concepts.</p>
<p>Finally, if you want to fully learn all of these concepts, I've put together for you a super helpful cheatsheet that summarizes everything we've covered here.</p>
<p>Just click the link below to grab it for free. Enjoy!</p>
<p><strong><a target="_blank" href="https://reedbarger.com/resources/python-variables">Download the</a></strong> Python variables cheatsheet</p>
<h2 id="heading-become-a-professional-react-developer">Become a Professional React Developer</h2>
<p>React is hard. You shouldn't have to figure it out yourself.</p>
<p>I've put everything I know about React into a single course, to help you reach your goals in record time:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><strong>Introducing: The React Bootcamp</strong></a></p>
<p><strong>It’s the one course I wish I had when I started learning React.</strong></p>
<p>Click below to try the React Bootcamp for yourself:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><img src="https://reedbarger.nyc3.digitaloceanspaces.com/reactbootcamp/react-bootcamp-cta-alt.png" alt="Click to join the React Bootcamp" width="600" height="400" loading="lazy"></a>
<em>Click to get started</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Variable Data Types Explained ]]>
                </title>
                <description>
                    <![CDATA[ By Deborah Kurata Walking into a hardware store, it's not enough to say: "I need a tool". You need to be specific about the type of tool you need.  Each tool type has its particular purpose: A hammer to drive a nail into wood, a paint brush to paint,... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/variable-data-types-explained/</link>
                <guid isPermaLink="false">66d45e153a8352b6c5a2aa1d</guid>
                
                    <category>
                        <![CDATA[ arrays ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ variables ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 07 Mar 2023 16:54:47 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/data-types-thumbnail2.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Deborah Kurata</p>
<p>Walking into a hardware store, it's not enough to say: "I need a tool". You need to be specific about the type of tool you need. </p>
<p>Each tool type has its particular purpose: A hammer to drive a nail into wood, a paint brush to paint, and a wrench tightens or loosens nuts and bolts.</p>
<p>The same goes for the variables we use to hold data in our code. Regardless of the programming language you use, when building a website or app you'll want to use the appropriate type of variable for a particular purpose. We'll look at basic types and more complex types such as arrays (lists) and objects.</p>
<p>You can also watch the associated video here which walks through the key variable data types.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/8cTu_RrkiME" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-basic-data-types"><strong>Basic Data Types</strong></h2>
<p>The most common basic data types available in most programming languages include:</p>
<p><strong>numbers</strong>: we use this for any data that is numeric or should be worked with as a number for addition or other math operations. </p>
<p>In some programming languages, there are multiple data types for numbers, depending on whether the number is an integer, decimal, or currency, for example. </p>
<p>If we were building a number guessing game, we would hold the guessed number in a numeric data type, like this:</p>
<pre><code class="lang-code">usersGuess = 3
</code></pre>
<p><strong>string</strong>: we use this for any data that is text. For example, a name or address or message. In most programming languages, strings require quotes. Notice that the text inside of the quotes can include spaces and other special characters.</p>
<pre><code class="lang-code">usersName = "Jack Harkness"
</code></pre>
<p><strong>date</strong>: we use this for data that is a date or time, such as a birthday.</p>
<pre><code class="lang-code">usersBirthday = April 14, 2001
</code></pre>
<p><strong>Boolean</strong>: we use this for data that only has the value <code>true</code> or <code>false</code>. In a number guessing game, the user's guess was either correct or it wasn't. There is no other value.</p>
<pre><code class="lang-code">correctGuess = true
</code></pre>
<p>For programming languages that are considered to be "strongly typed", such as C# and TypeScript, the data type defines the kind of data that can be assigned to that variable. You'll see an error if you try to put the wrong type of data into a variable.</p>
<pre><code class="lang-typescript">pageTitle = <span class="hljs-string">'Pet List'</span>;    <span class="hljs-comment">// Variable is a string.</span>

pageTitle = <span class="hljs-number">42</span>;            <span class="hljs-comment">// Error</span>
                        <span class="hljs-comment">// Can't put a number into a string variable</span>
</code></pre>
<p>With "dynamically typed" languages such as JavaScript and Python, the data type defines the kind of data currently assigned to that variable. That type can change if you put a different type of data into that variable. So the type dynamically changes based on the currently assigned value.</p>
<pre><code class="lang-javascript">pageTitle = <span class="hljs-string">'Pet List'</span>;            <span class="hljs-comment">// Variable type is a string</span>

pageTitle = <span class="hljs-number">42</span>;                    <span class="hljs-comment">// Variable type is now a number</span>
</code></pre>
<h2 id="heading-array-list-data-type"><strong>Array (List) Data Type</strong></h2>
<p>Another important data type in programming is an array, which in some programming languages is called a list.</p>
<p>Let's say we add a feature to our website or app so the user can provide the name of each of their pets. We could hold each name in a separate variable like shown in Figure 1.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/array1.jpg" alt="Pictures of three cats with three variables to hold the name of each cat." width="600" height="400" loading="lazy">
<em>Figure 1. Using separate string variables to hold multiple items.</em></p>
<p>But we'd then have to limit how many pets we could allow based on how many variables we'd defined.</p>
<p>Arrays solve this problem. An <strong>array</strong> is a collection or set of data items. You can think of an array as a list of items.</p>
<p>The data items in an array are often of the same type, so you may have an array of numbers, of strings, or of dates.</p>
<p>In some programming languages, including C#, TypeScript, JavaScript, and Python, arrays are defined with square brackets: [ ] and each value in the array is separated with commas.</p>
<pre><code class="lang-code">petNames = ["Yoyo", "Vanny", "Cali"]
</code></pre>
<p>Here we define an array of strings. Recall that strings must be enclosed in quotation marks. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/array2.jpg" alt="Pictures of three cats with a single array to hold the name of each cat." width="600" height="400" loading="lazy">
<em>Figure 2. Using an array to hold multiple items.</em></p>
<p>With arrays, the user can have an almost limitless number of items, such as names, because we can keep appending to the array.</p>
<pre><code class="lang-code">petNames = ["Yoyo", "Vanny", "Cali", "Ben", "Maki"]
</code></pre>
<h2 id="heading-object-data-type-custom-data-type"><strong>Object Data Type (Custom Data Type)</strong></h2>
<p>What about data that represent things in our application? Things like those shown in Figure 3:</p>
<ul>
<li>A pet</li>
<li>A customer</li>
<li>A product</li>
<li>Or post, and I actually mean a social media post here, but close enough.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/object1.jpg" alt="Four icons representing pet, customer, product, and post" width="600" height="400" loading="lazy">
<em>Figure 3. Custom data type (object) examples.</em></p>
<p>We can hold detailed information about a thing, such as a pet or customer or blog post, in a set of string, number, and date variables. But to keep that set of variables for a particular thing together as one variable, we want a custom data type that describes that thing. </p>
<p>Think of an object as a custom data type that groups a set of related variables for a particular thing.</p>
<p>Let's walk through how to define an object as a custom data type.</p>
<h3 id="heading-step-1-identify-properties-characteristics">Step 1: Identify Properties (Characteristics)</h3>
<p>To define an object data type, we first identify the data we want to hold for the object. These are often characteristics of the object, like a pet's name, type, and age. In programming, we call each of these characteristics a <strong>property</strong> of the object.</p>
<p>Let's look at some examples.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/object2.jpg" alt="Four icons representing pet, customer, product, and post and their characteristics" width="600" height="400" loading="lazy">
<em>Figure 4. Identify the data to store (or hold) for each object.</em></p>
<p>For a customer, the properties might be the customer's name, shipping address, and default payment method. </p>
<p>A product may have a product name, description, and a Boolean value defining whether the product is currently in stock.</p>
<p>And for a blog post, we may want to hold the user's name, the post text, and the date.</p>
<p>Each of these are properties of our object.</p>
<p>At this point, we have the list of properties for the object. We want to hold data for each of these properties.</p>
<h3 id="heading-step-2-assign-a-property-name">Step 2: Assign a Property Name</h3>
<p>Once we have the properties defined, we assign a name to each property as shown in Figure 5. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/object3.jpg" alt="Four icons representing pet, customer, product, and post and their property names" width="600" height="400" loading="lazy">
<em>Figure 5. Define a variable name for each object property.</em></p>
<p>The names follow the conventions for the programming language you are using. In general, property names cannot have spaces or special characters in them. They are often defined using camel case, with the first letter lower case and each additional word capitalized.</p>
<p>Each property also has a basic data type. <code>petName</code>, <code>customerName</code>, <code>productName</code>, and <code>userName</code> are strings. <code>age</code> is a number, <code>inStock</code> is a Boolean value (true or false), and <code>postDate</code> is a date.</p>
<p>We could keep track of separate variables for each of these pet properties and each of these customer properties and each of these post properties. But we'd end up with lots of unorganized variables.</p>
<p>Let's instead group each set of related properties into an object.</p>
<h3 id="heading-step-3-group-the-properties-for-the-object">Step 3: Group the Properties for the Object</h3>
<p>We group the properties of an object together using object literal syntax. This keeps the data for an object together and makes it easier to work with it as a set.</p>
<p>The syntax used to group the properties depends on the programming language you use. In languages such as JavaScript, TypeScript, and C#, object properties are grouped within curly braces ({ }).</p>
<pre><code class="lang-code">pet = {
    petName: "Yoyo",
    petType: "cat",
    age: 11
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/object4.jpg" alt="Four icons representing pet, customer, product, and post and a sample object." width="600" height="400" loading="lazy">
<em>Figure 6. Group the properties for each object</em></p>
<p>For each object, the variable on the left of the equal sign is the object variable and represents a specific pet, customer, product, or post. On the right of the equal sign, inside the curly braces, we list each property name, a colon, and the data (often called a value). We separate properties with a comma.</p>
<p>To say that another way, you can think of an object as a collection of name and value pairs. The name is the property name and the value is the data you want to store for that property. </p>
<p>In Figure 6, we defined a pet object with a specific set of properties, and a value for each property. Same with the customer, and so on.</p>
<h2 id="heading-try-it-yourself">Try It Yourself!</h2>
<p>Let's stop here for a moment and think about objects. What's your favorite hobby? If you built a website or an app to support that hobby, what objects might you define?</p>
<p>Maybe you like to bake, so you'd build a recipe app with your favorite recipes. You work with the data for each recipe using an object with properties such as ingredients, recipe steps, baking temperature, and time.</p>
<p>Or say you like sports. You'd track the data for each player using an object with properties such as name, position, and stats. And you'd track the data for each game using another object with properties such as teams and score.</p>
<p>What objects did you define for your hobby?</p>
<h2 id="heading-wrapping-up"><strong>Wrapping Up</strong></h2>
<p>A variable has a data type such as number, string (for text), date, and Boolean (for true or false).</p>
<p>An array stores a set of data items, often of the same type.</p>
<p>An object represents something in the website or app, like a pet, a customer, or a blog post. The object groups related properties holding the data for the object.</p>
<p>Now that you know all about data types, you can create variables of the appropriate type to hold any data you need for your website or app.</p>
<p>If you are self-taught or new to programming and want more information about general programming concepts, check out this course:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/yO4JaMVMerA" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ var, let, and const in JavaScript – the Differences Between These Keywords Explained ]]>
                </title>
                <description>
                    <![CDATA[ By Dillion Megida In JavaScript, you can declare variables with the var, let, and const keywords. But what are the differences between them? That's what I'll explain in this tutorial. I have a video version of this topic you can check out as well. 😇... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/differences-between-var-let-const-javascript/</link>
                <guid isPermaLink="false">66d84ee839c4dccc43d4d486</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ variables ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 11 Jan 2023 22:48:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/15.-var-let-const.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Dillion Megida</p>
<p>In JavaScript, you can declare variables with the <code>var</code>, <code>let</code>, and <code>const</code> keywords. But what are the differences between them? That's what I'll explain in this tutorial.</p>
<p>I have a <a target="_blank" href="https://youtu.be/Gd_JG3e1g4A">video version of this topic</a> you can check out as well. 😇</p>
<p>If you're just starting out using JavaScript, a few things you may hear about these keywords are:</p>
<ul>
<li><code>var</code> and <code>let</code> create variables that can be reassigned another value.</li>
<li><code>const</code> creates "constant" variables that cannot be reassigned another value.</li>
<li>developers shouldn't use <code>var</code> anymore. They should use <code>let</code> or <code>const</code> instead.</li>
<li>if you're not going to change the value of a variable, it is good practice to use <code>const</code>.</li>
</ul>
<p>The first two points are likely pretty self-explanatory. But what about why we shouldn't use var, or when to use let vs const? As we go through this tutorial, hopefully this will all make sense to you.</p>
<h2 id="heading-var-vs-let-vs-const-whats-the-difference"><code>var</code> vs <code>let</code> vs <code>const</code> – What's the Difference?</h2>
<p>To analyze the differences between these keywords, I'll be using three factors:</p>
<ul>
<li>Scope of variables</li>
<li>Redeclaration and reassignment</li>
<li>Hoisting</li>
</ul>
<p>I'm also writing separate tutorials about variable scope, variable hoisting, and variable redeclaration and reassignment – so you can learn more about them as well. They'll be out soon. :)</p>
<p>Let's start by looking at how these factors apply to variables declared with <code>var</code>.</p>
<h2 id="heading-how-to-declare-variables-with-var-in-javascript">How to Declare Variables with <code>var</code> in JavaScript</h2>
<h3 id="heading-the-scope-of-variables-declared-with-var">The scope of variables declared with <code>var</code></h3>
<p>Variables declared with <code>var</code> can have a <strong>global</strong> or <strong>local</strong> scope. Global scope is for variables declared outside functions, while local scope is for variables declared inside functions.</p>
<p>Let's see some examples, starting from global scope:</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> number = <span class="hljs-number">50</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">print</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> square = number * number
  <span class="hljs-built_in">console</span>.log(square)
}

<span class="hljs-built_in">console</span>.log(number) <span class="hljs-comment">// 50</span>

print() <span class="hljs-comment">// 2500</span>
</code></pre>
<p>The <code>number</code> variable has a global scope – it's declared outside functions in the global space – so you can access it everywhere (inside and outside functions).</p>
<p>Let's see an example of local scope:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">print</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> number = <span class="hljs-number">50</span>
  <span class="hljs-keyword">var</span> square = number * number
  <span class="hljs-built_in">console</span>.log(square)
}

print() <span class="hljs-comment">// 2500</span>

<span class="hljs-built_in">console</span>.log(number)
<span class="hljs-comment">// ReferenceError: number is not defined</span>
</code></pre>
<p>Here, we declared the <code>number</code> variable in the function <code>print</code>, so it has a local scope. This means that the variable can only be accessed inside that function. Any attempt to access the variable outside the function where it was declared will result in a <strong>variable is not defined</strong> reference error.</p>
<h3 id="heading-how-to-redeclare-and-reassign-variables-declared-with-var">How to redeclare and reassign variables declared with <code>var</code></h3>
<p>Variables declared with <code>var</code> can be redeclared and reassigned. I'll explain what I mean with examples.</p>
<p>Here's how to declare a variable with <code>var</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> number = <span class="hljs-number">50</span>
</code></pre>
<p>You have the <code>var</code> keyword, the name of the variable <code>number</code>, and an initial value <strong>50</strong>. If an initial value is not provided, the default value will be <strong>undefined</strong>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> number

<span class="hljs-built_in">console</span>.log(number)
<span class="hljs-comment">// undefined</span>
</code></pre>
<p>The <code>var</code> keyword allows for redeclaration. Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> number = <span class="hljs-number">50</span>
<span class="hljs-built_in">console</span>.log(number) <span class="hljs-comment">// 50</span>

<span class="hljs-keyword">var</span> number = <span class="hljs-number">100</span>
<span class="hljs-built_in">console</span>.log(number) <span class="hljs-comment">// 100</span>
</code></pre>
<p>As you can see, we have redeclared the variable <code>number</code> using the <code>var</code> keyword and an initial value of <strong>100</strong>.</p>
<p>The <code>var</code> keyword also allows for reassignment. In the code <code>var number = 50</code>, we assigned the <strong>50</strong> value to <code>number</code>. We can reassign another value anywhere in the code since it was declared with <code>var</code>. Here's what I mean:</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> number = <span class="hljs-number">50</span>
<span class="hljs-built_in">console</span>.log(number) <span class="hljs-comment">// 50</span>

number = <span class="hljs-number">100</span>
<span class="hljs-built_in">console</span>.log(number) <span class="hljs-comment">// 100</span>

number = <span class="hljs-number">200</span>
<span class="hljs-built_in">console</span>.log(number) <span class="hljs-comment">// 200</span>
</code></pre>
<p>Here, we're not redeclaring – rather, we're reassigning. After declaring the first time with an initial value of <strong>50</strong>, we reassign a new value of <strong>100</strong> and later on with a new value of <strong>200</strong>.</p>
<h3 id="heading-how-to-hoist-variables-declared-with-var">How to hoist variables declared with <code>var</code></h3>
<p>Variables declared with <code>var</code> are hoisted to the top of their global or local scope, which makes them accessible before the line they are declared. Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(number) <span class="hljs-comment">// undefined</span>

<span class="hljs-keyword">var</span> number = <span class="hljs-number">50</span>

<span class="hljs-built_in">console</span>.log(number) <span class="hljs-comment">// 50</span>
</code></pre>
<p>The <code>number</code> variable here has a global scope. Since it is declared with <code>var</code>, the variable is hoisted. This means that we can access the variable before the line where it was declared without errors. </p>
<p>But the variable is hoisted with a default value of <strong>undefined</strong>. So that's the value returned from the variable (until the line where the variable is declared with an initial value gets executed).</p>
<p>Let's see a local scope example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">print</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> square1 = number * number
  <span class="hljs-built_in">console</span>.log(square1)

  <span class="hljs-keyword">var</span> number = <span class="hljs-number">50</span>

  <span class="hljs-keyword">var</span> square2 = number * number
  <span class="hljs-built_in">console</span>.log(square2)
}

print()
<span class="hljs-comment">// NaN</span>
<span class="hljs-comment">// 2500</span>
</code></pre>
<p>In the <code>print</code> function, <code>number</code> has a local scope. Due to hoisting, we can access the <code>number</code> variable before the line of declaration. </p>
<p>As we see in <code>square1</code>, we assign <strong>number * number</strong>. Since <code>number</code> is hoisted with a default value of <strong>undefined</strong>, <code>square1</code> will be <strong>undefined * undefined</strong> which results in <strong>NaN</strong>.</p>
<p>After the line of declaration with an initial value is executed, <code>number</code> will have a value of <strong>50</strong>. So in <code>square2</code>, <strong>number * number</strong> will be <strong>50 * 50</strong> which results in <strong>2500</strong>.</p>
<p>There are some problems with <code>var</code>, which we'll discuss at the end. Just know that it's generally not advisable to use it in your modern JavaScript projects. </p>
<h2 id="heading-how-to-declare-variables-with-let-in-javascript">How to Declare Variables with <code>let</code> in JavaScript</h2>
<h3 id="heading-the-scope-of-variables-declared-with-let">The scope of variables declared with <code>let</code></h3>
<p>Variables declared with <code>let</code> can have a <strong>global</strong>, <strong>local</strong>, or <strong>block scope</strong>. Block scope is for variables declared in a block. A block in JavaScript involves opening and closing curly braces:</p>
<pre><code class="lang-js">{
  <span class="hljs-comment">// a block</span>
}
</code></pre>
<p>You can find blocks in <code>if</code>, <code>loop</code>, <code>switch</code>, and a couple of other statements. Any variables declared in such blocks with the <code>let</code> keyword will have a block scope. Also, you can't access these variables outside the block. Here's an example showing a global, local, and block scope:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> number = <span class="hljs-number">50</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">print</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> square = number * number

  <span class="hljs-keyword">if</span> (number &lt; <span class="hljs-number">60</span>) {
    <span class="hljs-keyword">var</span> largerNumber = <span class="hljs-number">80</span>
    <span class="hljs-keyword">let</span> anotherLargerNumber = <span class="hljs-number">100</span>

    <span class="hljs-built_in">console</span>.log(square)
  }

  <span class="hljs-built_in">console</span>.log(largerNumber)
  <span class="hljs-built_in">console</span>.log(anotherLargerNumber)
}

print()
<span class="hljs-comment">// 2500</span>
<span class="hljs-comment">// 80</span>
<span class="hljs-comment">// ReferenceError: anotherLargerNumber is not defined</span>
</code></pre>
<p>In this example, we have a global scope variable <code>number</code> and a local scope variable <code>square</code>. There's also block scope variable <code>anotherLargerNumber</code> because it is declared with <code>let</code> in a block. </p>
<p><code>largerNumber</code>, on the other hand – though declared in a block – does not have a block scope because it is declared with <code>var</code>. So <code>largerNumber</code> has a local scope as it is declared in the function <code>print</code>.</p>
<p>We can access <code>number</code> everywhere. We can only access <code>square</code> and <code>largerNumber</code> in the function because they have local scope. But accessing <code>anotherLargerNumber</code> outside the block throws an <strong>anotherLargerNumber is not defined</strong> error.</p>
<h3 id="heading-how-to-redeclare-and-reassign-variables-declared-with-let">How to redeclare and reassign variables declared with <code>let</code></h3>
<p>Just like <code>var</code>, variables declared with <code>let</code> can be reassigned to other values, but they cannot be redeclared. Let's see a reassignment example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> number = <span class="hljs-number">50</span>
<span class="hljs-built_in">console</span>.log(number) <span class="hljs-comment">// 50</span>

number = <span class="hljs-number">100</span>
<span class="hljs-built_in">console</span>.log(number) <span class="hljs-comment">// 100</span>
</code></pre>
<p>Here, we reassigned another value <strong>100</strong> after the initial declaration of <strong>50</strong>.</p>
<p>But redeclaring a variable with <code>let</code> will throw an error:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> number = <span class="hljs-number">50</span>

<span class="hljs-keyword">let</span> number = <span class="hljs-number">100</span>
<span class="hljs-comment">// SyntaxError: Identifier 'number' has already been declared</span>
</code></pre>
<p>You see we get a syntax error: <strong>Identifier 'number' has already been declared</strong>.</p>
<h3 id="heading-how-to-hoist-variables-declared-with-let">How to hoist variables declared with <code>let</code></h3>
<p>Variables declared with <code>let</code> are hoisted to the top of their global, local, or block scope, but their hoisting is a little different from the one with <code>var</code>.</p>
<p><code>var</code> variables are hoisted with a default value of <strong>undefined</strong>, which makes them accessible before their line of declaration (as we've seen above).</p>
<p>But, <code>let</code> variables are hoisted without a default initialization. So when you try to access such variables, instead of getting <strong>undefined</strong>, or <strong>variable is not defined</strong> error, you get <strong>cannot access variable before initialization</strong>. Let's see an example:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(number)
<span class="hljs-comment">// ReferenceError: Cannot access 'number' before initialization</span>

<span class="hljs-keyword">let</span> number = <span class="hljs-number">50</span>
</code></pre>
<p>Here, we have a global variable, <code>number</code> declared with <code>let</code>. By trying to access this variable before the line of declaration, we get <strong>ReferenceError: Cannot access 'number' before initialization</strong>.</p>
<p>Here's another example with a local scope variable:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">print</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> square = number * number

  <span class="hljs-keyword">let</span> number = <span class="hljs-number">50</span>
}

print()
<span class="hljs-comment">// ReferenceError: Cannot access 'number' before initialization</span>
</code></pre>
<p>Here we have a local scope variable, <code>number</code>, declared with <code>let</code>. By accessing it before the line of declaration again, we get the <strong>cannot access 'number' before initialization</strong> reference error</p>
<h2 id="heading-how-to-declare-variables-with-const-in-javascript">How to Declare Variables with <code>const</code> in JavaScript</h2>
<h3 id="heading-the-scope-of-variables-declared-with-const">The scope of variables declared with <code>const</code></h3>
<p>Variables declared with <code>const</code> are similar to <code>let</code> in regards to <strong>scope</strong>. Such variables can have a <strong>global</strong>, <strong>local</strong>, or <strong>block</strong> scope.</p>
<p>Here is an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> number = <span class="hljs-number">50</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">print</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> square = number * number

  <span class="hljs-keyword">if</span> (number &lt; <span class="hljs-number">60</span>) {
    <span class="hljs-keyword">var</span> largerNumber = <span class="hljs-number">80</span>
    <span class="hljs-keyword">const</span> anotherLargerNumber = <span class="hljs-number">100</span>

    <span class="hljs-built_in">console</span>.log(square)
  }

  <span class="hljs-built_in">console</span>.log(largerNumber)
  <span class="hljs-built_in">console</span>.log(anotherLargerNumber)
}

print()
<span class="hljs-comment">// 2500</span>
<span class="hljs-comment">// 80</span>
<span class="hljs-comment">// ReferenceError: anotherLargerNumber is not defined</span>
</code></pre>
<p>This is from our previous example, but I've replaced <code>let</code> with <code>const</code>. As you can see here, the <code>number</code> variable has a global scope, <code>square</code> has a local scope (declared in the <code>print</code> function), and <code>anotherLargeNumber</code> has a block scope (declared with <code>const</code>).</p>
<p>There's also <code>largeNumber</code>, declared in a block. But because it is with <code>var</code>, the variable only has a local scope. Therefore, it can be accessed outside the block.</p>
<p>Because <code>anotherLargeNumber</code> has a block scope, accessing it outside the block throws an <strong>anotherLargerNumber is not defined</strong>.</p>
<h3 id="heading-how-to-redeclare-and-reassign-variables-declared-with-const">How to redeclare and reassign variables declared with <code>const</code></h3>
<p>In this regard, <code>const</code> is different from <code>var</code> and <code>let</code>. <code>const</code> is used for declaring <strong>constant</strong> variables – which are variables with values that cannot be changed. So such variables cannot be redeclared, and neither can they be reassigned to other values. Attempting such would throw an error.</p>
<p>Let's see an example with redeclaration:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> number = <span class="hljs-number">50</span>

<span class="hljs-keyword">const</span> number = <span class="hljs-number">100</span>

<span class="hljs-comment">// SyntaxError: Identifier 'number' has already been declared</span>
</code></pre>
<p>Here, you can see the <strong>Identifier has already been declared</strong> syntax error.</p>
<p>Now, let's see an example with reassignment:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> number = <span class="hljs-number">50</span>

number = <span class="hljs-number">100</span>

<span class="hljs-comment">// TypeError: Assignment to constant variable</span>
</code></pre>
<p>Here, you can see the <strong>Assignment to constant variable</strong> type error.</p>
<h3 id="heading-how-to-hoist-variables-declared-with-const">How to hoist variables declared with <code>const</code></h3>
<p>Variables declared with <code>const</code>, just like <code>let</code>, are hoisted to the top of their global, local, or block scope – but without a default initialization.</p>
<p><code>var</code> variables, as you've seen earlier, are hoisted with a default value of <strong>undefined</strong> so they can be accessed before declaration without errors. Accessing a variable declared with <code>const</code> before the line of declaration will throw a <strong>cannot access variable before initialization</strong> error.</p>
<p>Let's see an example:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(number)
<span class="hljs-comment">// ReferenceError: Cannot access 'number' before initialization</span>

<span class="hljs-keyword">const</span> number = <span class="hljs-number">50</span>
</code></pre>
<p>Here, <code>number</code> is a globally scoped variable declared with <code>const</code>. By trying to access this variable before the line of declaration, we get <strong>ReferenceError: Cannot access 'number' before initialization</strong>. The same will occur if it was a locally scoped variable.</p>
<p>Here's an article to learn more about <a target="_blank" href="https://www.freecodecamp.org/news/javascript-let-and-const-hoisting/">Hoisting in JavaScript with let and const – and How it Differs from var</a>.</p>
<h2 id="heading-wrap-up">Wrap up</h2>
<p>Here's a table summary showing the differences between these keywords:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Keyword</td><td>Scope</td><td>Redeclaration &amp; Reassignment</td><td>Hoisting</td></tr>
</thead>
<tbody>
<tr>
<td><code>var</code></td><td>Global, Local</td><td>yes &amp; yes</td><td>yes, with default value</td></tr>
<tr>
<td><code>let</code></td><td>Global, Local, Block</td><td>no &amp; yes</td><td>yes, without default value</td></tr>
<tr>
<td><code>const</code></td><td>Global, Local, Block</td><td>no &amp; no</td><td>yes, without default value</td></tr>
</tbody>
</table>
</div><p>These factors I've explained, play a role in determining how you declare variables in JavaScript. </p>
<p>If you never want a variable to change, <code>const</code> is the keyword to use.</p>
<p>If you want to reassign values:</p>
<ul>
<li>and you want the hoisting behavior, <code>var</code> is the keyword to use</li>
<li>if you don't want it, <code>let</code> is the keyword for you</li>
</ul>
<p>The hoisting behavior can cause unexpected bugs in your application. That's why developers are generally advised to avoid <code>var</code> and stick to <code>let</code> and <code>cost</code>.</p>
<p>I hope you learned something from this article.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is the Difference Between an Independent Variable and a Dependent Variable? ]]>
                </title>
                <description>
                    <![CDATA[ The meaning of the word "variable" depends on the field where it's being used.  In programming, a variable is a particular piece of data that holds a value. Depending on the configuration, that value can change or remain fixed.  For instance, in Java... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/independent-variable-vs-dependent-variable/</link>
                <guid isPermaLink="false">66adf1867550d4f37c2019b7</guid>
                
                    <category>
                        <![CDATA[ research ]]>
                    </category>
                
                    <category>
                        <![CDATA[ statistics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ variables ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Thu, 15 Dec 2022 17:32:36 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/12/snowy-4689675_1280.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The meaning of the word "variable" depends on the field where it's being used. </p>
<p>In programming, a variable is a particular piece of data that holds a value. Depending on the configuration, that value can change or remain fixed. </p>
<p>For instance, in JavaScript, you can implement a variable to change over time with the "var" and "let" keywords. But if you want, you can implement a variable so it doesn't change with the "const" keyword.</p>
<p>In this article, the kind of variable we’ll be looking at is not the one in programming but the one you'll deal with in research. Precisely, we’ll look at the differences between the two main types of variables in research – dependent and independent variables.</p>
<p>But before we look at the differences between dependent and independent variables, we need to understand what a variable is first.</p>
<h2 id="heading-what-well-cover">What We'll Cover</h2>
<ul>
<li><a class="post-section-overview" href="#heading-what-is-a-variable-in-research">What is a Variable in Research?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-dependent-and-independent-variables">What are Dependent and Independent Variables?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-the-differences-between-dependent-and-independent-variables">What are the Differences between Dependent and Independent Variables?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-identify-a-dependent-variable-from-an-independent-variable">How to Identify a Dependent Variable from an Independent Variable</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
<li><a class="post-section-overview" href="#morereadings">More Readings</a></li>
</ul>
<h2 id="heading-what-is-a-variable-in-research">What is a Variable in Research?</h2>
<p>If you’re conducting research, you’ll be measuring a lot of values. So, in research, a variable is anything you’re trying to measure. It could be age, temperature, length, height, mass, weight, or any other thing that can have a value.</p>
<p>In addition, you’ll be measuring those variables in different units – centimeters (cm), meters (m), grams (g), kilograms (kg), and many more. </p>
<p>These units can’t be neglected, but as far as variables are concerned, whether dependent or independent, the values are what really matter.</p>
<h2 id="heading-what-are-dependent-and-independent-variables">What are Dependent and Independent Variables?</h2>
<p>Dependent and independent variables depend on whether one variable determines the outcome of the other or not.</p>
<p>A dependent variable is a variable whose changes and its outcome depend on another variable. On almost all occasions, the variable the dependent variable depends on is an independent variable.</p>
<p>Dependent variables are also called the response or outcome variables because they represent the outcome of the values you're measuring. That is, what you record after manipulating the independent variables.</p>
<p>An independent variable is a variable whose outcome or changes do not depend on another variable. It is the exact opposite of the dependent variable, at least according to what the name implies.</p>
<p>Independent variables are also called predictor variables because you can use them to predict the outcome of a dependent variable. That is, when you manipulate independent variables, they can give you the outcome of a dependent variable.</p>
<h2 id="heading-what-are-the-differences-between-dependent-and-independent-variables">What are the Differences between Dependent and Independent Variables?</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Basis</strong></td><td><strong>Dependent Variable</strong></td><td><strong>Independent Variable</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Type</strong></td><td>It is the "response" variable</td><td>It is the "effect" variable</td></tr>
<tr>
<td><strong>Outcome</strong></td><td>Outcome depends on another variable (usually the independent variable)</td><td>Outcome does not depend on another variable</td></tr>
<tr>
<td><strong>Changes</strong></td><td>This variable changes over time. Consider the dependent variable as a variable you declare with the "let" or "var" keyword in JavaScript. You can later change it.</td><td>This variable never changes. Consider the independent variable as the variable you declare with the "const" keyword in JavaScript. It is fixed unless you explicitly change the value.</td></tr>
<tr>
<td><strong>Manipulation</strong></td><td>Dependent variables cannot be manipulated because their value depends on the independent variable.</td><td>Independent variables can be manipulated to determine the outcome of a dependent variable.</td></tr>
<tr>
<td><strong>Position on a Graph</strong></td><td>Dependent variables are placed on the y-axis (vertical axis) on a graph</td><td>Independent variables are placed on the x-axis (horizontal axis) on a graph</td></tr>
</tbody>
</table>
</div><h2 id="heading-how-to-identify-a-dependent-variable-from-an-independent-variable">How to Identify a Dependent Variable from an Independent Variable</h2>
<p>We've taken a look at what variables are, what dependent and independent variables are, and the exact differences between dependent and independent variables. </p>
<p>But how exactly would you differentiate a dependent variable from an independent variable? We are going to look at two experiments or examples:</p>
<ul>
<li><p>how Vitamin A helps mothers produce milk</p>
</li>
<li><p>the level of light nocturnal insects (insects active at night) are attracted to</p>
</li>
</ul>
<p>For the first experiment, the sources of vitamin A the mother takes in from foods like fish oil and green vegetables are the independent variable. That's because the researcher can change [decrease or increase] the amount given to the mothers. How the body of the mother responds in producing more milk is the dependent variable.</p>
<p>For the second experiment, the level of light is the independent variable because the researcher can change it. How nocturnal insects react to that level of light is the dependent variable.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned about the differences between dependent and independent variables. We looked at:</p>
<ul>
<li><p>what a variable is in research</p>
</li>
<li><p>the two main types of variables (dependent and independent variables)</p>
</li>
<li><p>what dependent and independent variables are</p>
</li>
<li><p>and how to differentiate a dependent variable from an independent variable.</p>
</li>
</ul>
<p>I hope this article gives you a knowledge of what research variables are and how to differentiate a dependent variable from an independent variable.</p>
<p>Thank you for reading.</p>
<h3 id="heading-further-reading">Further Reading</h3>
<ul>
<li><a target="_blank" href="https://www.scribbr.com/methodology/types-of-variables/">Types of Variables in Research and Statistics</a></li>
<li><a target="_blank" href="https://www.scribbr.com/methodology/independent-and-dependent-variables/">Independent Variables v Dependent Variables</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Global Variable in Python – Non-Local Python Variables ]]>
                </title>
                <description>
                    <![CDATA[ In Python and most programming languages, variables declared outside a function are known as global variables. You can access such variables inside and outside of a function, as they have global scope.  Here's an example of a global variable: x = 10 ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/global-variable-in-python-non-local-python-variables/</link>
                <guid isPermaLink="false">66b0a2b5675b17049e0b4bef</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ variables ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Fri, 10 Jun 2022 21:21:45 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/06/kevin-ku-w7ZyuGYNpRQ-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In Python and most programming languages, variables declared outside a function are known as global variables. You can access such variables inside and outside of a function, as they have global scope. </p>
<p>Here's an example of a global variable:</p>
<pre><code class="lang-python">x = <span class="hljs-number">10</span> 

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">showX</span>():</span>
    print(<span class="hljs-string">"The value of x is"</span>, x)

showX()
<span class="hljs-comment"># The value of x is 10</span>
</code></pre>
<p>The variable <code>x</code> in the code above was declared outside a function: <code>x = 10</code>. </p>
<p>Using the <code>showX()</code> function, we were still able to access <code>x</code> because it was declared in a global scope. </p>
<p>Let's take a look at another example that shows what happens when we declare a variable inside a function and try to access it elsewhere.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">X</span>():</span>
    x = <span class="hljs-number">10</span> 

X()

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">showX</span>():</span>
    print(<span class="hljs-string">"The value of x is"</span>, x)

showX()
NameError: name <span class="hljs-string">'x'</span> <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> defined
</code></pre>
<p>In the example above, we declared <code>x</code> inside a function and tried to access it in another function. This resulted in a NameError because <code>x</code> was not defined globally. </p>
<p>Variables defined inside functions are called local variables. Their value can only be used within the function where they are declared. </p>
<p>You can change the scope of a local variable using the <code>global</code> keyword – which we'll discuss in the next section.</p>
<h2 id="heading-what-is-the-global-keyword-used-for-in-python">What is the <code>global</code> Keyword Used for in Python?</h2>
<p>The global keyword is mostly used for two reasons:</p>
<ul>
<li>To modify the value of a global variable.</li>
<li>To make a local variable accessible outside the local scope. </li>
</ul>
<p>Let's look at some examples for each scenario to help you understand better. </p>
<h3 id="heading-example-1-modifying-a-global-variable-using-the-global-keyword">Example #1 - Modifying a Global Variable Using the <code>global</code> Keyword</h3>
<p>In the last section where we declared a global variable, we did not try to change the value of the variable. All we did was access and print its value in a function. </p>
<p>Let's try and change the value of a global variable and see what happens:</p>
<pre><code class="lang-python">x = <span class="hljs-number">10</span> 

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">showX</span>():</span>
    x = x + <span class="hljs-number">2</span>
    print(<span class="hljs-string">"The value of x is"</span>, x)

showX()
<span class="hljs-comment"># local variable 'x' referenced before assignment</span>
</code></pre>
<p>As you can see above, when we tried to add 2 to the value of <code>x</code>, we got an error. This is because we can only access but not modify <code>x</code>. </p>
<p>To fix that, we use the <code>global</code> variable. Here's how:</p>
<pre><code class="lang-python">x = <span class="hljs-number">10</span> 

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">showX</span>():</span>
    <span class="hljs-keyword">global</span> x
    x = x + <span class="hljs-number">2</span>
    print(<span class="hljs-string">"The value of x is"</span>, x)

showX()
<span class="hljs-comment"># The value of x is 12</span>
</code></pre>
<p>Using the <code>global</code> keyword in the code above, we were able to modify <code>x</code> and add 2 to its initial value. </p>
<h3 id="heading-example-2-how-to-make-a-local-variable-accessible-outside-the-local-scope-using-the-global-keyword">Example #2 - How to Make a Local Variable Accessible Outside the Local Scope Using the <code>global</code> Keyword</h3>
<p>When we created a variable inside a function, it wasn't possible to use its value inside another function because the compiler did not recognize the variable.</p>
<p>Here's how we can fix that using the <code>global</code> keyword:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">X</span>():</span>
    <span class="hljs-keyword">global</span> x
    x = <span class="hljs-number">10</span> 

X()

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">showX</span>():</span>
    print(<span class="hljs-string">"The value of x is"</span>, x)

showX()
<span class="hljs-comment"># The value of x is 10</span>
</code></pre>
<p>To make it possible for <code>x</code> to be accessible outside its local scope, we declared it using the <code>global</code> keyword: <code>global x</code>. </p>
<p>After that, we assigned a value to <code>x</code>. We then called the function we used to declare it: <code>X()</code></p>
<p>When we called the <code>showX()</code> function, which prints the value of <code>x</code> declared in the <code>X()</code> function, we did not get an error because <code>x</code> has a global scope. </p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we talked about global and local variables in Python.</p>
<p>The examples showed how to declare both global and local variables. </p>
<p>We also talked about the <code>global</code> keyword which lets you modify the value of a global variable or make a local variable accessible outside its scope. </p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Global Variables – How to Define a Global Variable Example ]]>
                </title>
                <description>
                    <![CDATA[ In this article, you will learn the basics of global variables. To begin with, you will learn how to declare variables in Python and what the term 'variable scope' actually means. Then, you will learn the differences between local and global variable... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-global-variables-examples/</link>
                <guid isPermaLink="false">66b1e48296a9e0a75592bbd4</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ variables ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Dionysia Lemonaki ]]>
                </dc:creator>
                <pubDate>Thu, 12 May 2022 18:46:34 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/05/fernando-cferdophotography-tNDYN8jWyfM-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, you will learn the basics of global variables.</p>
<p>To begin with, you will learn how to declare variables in Python and what the term 'variable scope' actually means.</p>
<p>Then, you will learn the differences between local and global variables and understand how to define global variables and how to use the <code>global</code> keyword.</p>
<p>Here is what we will cover:</p>
<ol>
<li><a class="post-section-overview" href="#intro">An introduction to variables in Python</a><ol>
<li><a class="post-section-overview" href="#scope">Variable scope explained</a></li>
</ol>
</li>
<li><a class="post-section-overview" href="#local">How to create variables with local scope</a></li>
<li><a class="post-section-overview" href="#global">How to create variables with global scope</a><ol>
<li><a class="post-section-overview" href="#keyword">The <code>global</code> keyword</a></li>
</ol>
</li>
</ol>
<h2 id="heading-what-are-variables-in-python-and-how-do-you-create-them-an-introduction-for-beginners">What Are Variables in Python and How Do You Create Them? An Introduction for Beginners <a></a></h2>
<p>You can think of variables as <strong>storage containers</strong>.</p>
<p>They are storage containers for holding data, information, and values that you would like to save in the computer's memory. You can then reference or even manipulate them at some point throughout the life of the program.</p>
<p>A variable has a symbolic <strong>name</strong>, and you can think of that name as the <strong>label</strong> on the storage container that acts as its identifier.</p>
<p>The variable name will be a reference and pointer to the data stored inside it. So, there is no need to remember the details of your data and information – you only need to reference the variable name that holds that data and information.</p>
<p>When giving a variable a name, make sure that it is descriptive of the data it holds. Variable names need to be clear and easily understandable both for your future self and the other developers you may be working with.</p>
<p>Now, let's see how to actually create a variable in Python.</p>
<p>When declaring variables in Python, you don't need to specify their data type.</p>
<p>For example, in the C programming language, you have to mention explicitly the type of data the variable will hold. </p>
<p>So, if you wanted to store your age which is an integer, or <code>int</code> type, this is what you would have to do in C:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-keyword">void</span>)</span>
</span>{
  <span class="hljs-keyword">int</span> age = <span class="hljs-number">28</span>;
  <span class="hljs-comment">// 'int' is the data type</span>
  <span class="hljs-comment">// 'age' is the name </span>
  <span class="hljs-comment">// 'age' is capable of holding integer values</span>
  <span class="hljs-comment">// positive/negative whole numbers or 0</span>
  <span class="hljs-comment">// '=' is the assignment operator</span>
  <span class="hljs-comment">// '28' is the value</span>
}
</code></pre>
<p>However, this is how you would write the above in Python:</p>
<pre><code class="lang-python">age = <span class="hljs-number">28</span>

<span class="hljs-comment">#'age' is the variable name, or identifier</span>
<span class="hljs-comment"># '=' is the assignment operator</span>
<span class="hljs-comment">#'28' is the value assigned to the variable, so '28' is the value of 'age'</span>
</code></pre>
<p>The variable name is always on the left-hand side, and the value you want to assign goes on the right-hand side after the assignment operator.</p>
<p>Keep in mind that you can change the values of variables throughout the life of a program:</p>
<pre><code class="lang-python">my_age = <span class="hljs-number">28</span>

print(<span class="hljs-string">f"My age in 2022 is <span class="hljs-subst">{my_age}</span>."</span>)

my_age = <span class="hljs-number">29</span>

print(<span class="hljs-string">f"My age in 2023 will be <span class="hljs-subst">{my_age}</span>."</span>)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#My age in 2022 is 28.</span>
<span class="hljs-comment">#My age in 2023 will be 29.</span>
</code></pre>
<p>You keep the same variable name, <code>my_age</code>, but only change the value from <code>28</code> to <code>29</code>.</p>
<h3 id="heading-what-does-variable-scope-in-python-mean">What Does Variable Scope in Python Mean? <a></a></h3>
<p>Variable scope refers to the parts and boundaries of a Python program where a variable is available, accessible, and visible.</p>
<p>There are four types of scope for Python variables, which are also known as the <strong>LEGB rule</strong>:</p>
<ul>
<li><strong>L</strong>ocal,</li>
<li><strong>E</strong>nclosing,</li>
<li><strong>G</strong>lobal,</li>
<li><strong>B</strong>uilt-in.</li>
</ul>
<p>For the rest of this article, you will focus on learning about creating variables with global scope, and you will understand the difference between the local and global variable scopes.</p>
<h2 id="heading-how-to-create-variables-with-local-scope-in-python">How to Create Variables With Local Scope in Python <a></a></h2>
<p>Variables defined inside a function's body have <em>local</em> scope, which means they are accessible only within that particular function. In other words, they are 'local' to that function.</p>
<p>You can only access a local variable by calling the function.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">learn_to_code</span>():</span>
    <span class="hljs-comment">#create local variable</span>
    coding_website = <span class="hljs-string">"freeCodeCamp"</span>
    print(<span class="hljs-string">f"The best place to learn to code is with <span class="hljs-subst">{coding_website}</span>!"</span>)

<span class="hljs-comment">#call function</span>
learn_to_code()


<span class="hljs-comment">#output</span>

<span class="hljs-comment">#The best place to learn to code is with freeCodeCamp!</span>
</code></pre>
<p>Look at what happens when I try to access that variable with a local scope from outside the function's body:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">learn_to_code</span>():</span>
    <span class="hljs-comment">#create local variable</span>
    coding_website = <span class="hljs-string">"freeCodeCamp"</span>
    print(<span class="hljs-string">f"The best place to learn to code is with <span class="hljs-subst">{coding_website}</span>!"</span>)

<span class="hljs-comment">#try to print local variable 'coding_website' from outside the function</span>
print(coding_website)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#NameError: name 'coding_website' is not defined</span>
</code></pre>
<p>It raises a <code>NameError</code> because it is not 'visible' in the rest of the program. It is only 'visible' within the function where it was defined.</p>
<h2 id="heading-how-to-create-variables-with-global-scope-in-python">How to Create Variables With Global Scope in Python <a></a></h2>
<p>When you define a variable <em>outside</em> a function, like at the top of the file, it has a global scope and it is known as a global variable.</p>
<p>A global variable is accessed from anywhere in the program.</p>
<p>You can use it inside a function's body, as well as access it from outside a function:</p>
<pre><code class="lang-python"><span class="hljs-comment">#create a global variable</span>
coding_website = <span class="hljs-string">"freeCodeCamp"</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">learn_to_code</span>():</span>
    <span class="hljs-comment">#access the variable 'coding_website' inside the function</span>
    print(<span class="hljs-string">f"The best place to learn to code is with <span class="hljs-subst">{coding_website}</span>!"</span>)

<span class="hljs-comment">#call the function</span>
learn_to_code()

<span class="hljs-comment">#access the variable 'coding_website' from outside the function</span>
print(coding_website)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#The best place to learn to code is with freeCodeCamp!</span>
<span class="hljs-comment">#freeCodeCamp</span>
</code></pre>
<p>What happens when there is a global and local variable, and they both have the same name?</p>
<pre><code class="lang-python"><span class="hljs-comment">#global variable</span>
city = <span class="hljs-string">"Athens"</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">travel_plans</span>():</span>
    <span class="hljs-comment">#local variable with the same name as the global variable</span>
    city = <span class="hljs-string">"London"</span>
    print(<span class="hljs-string">f"I want to visit <span class="hljs-subst">{city}</span> next year!"</span>)

<span class="hljs-comment">#call function - this will output the value of local variable</span>
travel_plans()

<span class="hljs-comment">#reference global variable - this will output the value of global variable</span>
print(<span class="hljs-string">f"I want to visit <span class="hljs-subst">{city}</span> next year!"</span>)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#I want to visit London next year!</span>
<span class="hljs-comment">#I want to visit Athens next year!</span>
</code></pre>
<p>In the example above, maybe you were not expecting that specific output.</p>
<p>Maybe you thought that the value of <code>city</code> would change when I assigned it a different value inside the function. </p>
<p>Maybe you expected that when I referenced the global variable with the line <code>print(f" I want to visit {city} next year!")</code>, the output would be <code>#I want to visit London next year!</code> instead of <code>#I want to visit Athens next year!</code>.</p>
<p>However, when the function was called, it printed the value of the local variable. </p>
<p>Then, when I referenced the global variable outside the function, the value assigned to the global variable was printed.</p>
<p>They didn't interfere with one another.</p>
<p>That said, using the same variable name for global and local variables is not considered a best practice. Make sure that your variables don't have the same name, as you may get some confusing results when you run your program.</p>
<h3 id="heading-how-to-use-the-global-keyword-in-python">How to Use the <code>global</code> Keyword in Python <a></a></h3>
<p>What if you have a global variable but want to change its value inside a function?</p>
<p>Look at what happens when I try to do that:</p>
<pre><code class="lang-python"><span class="hljs-comment">#global variable</span>
city = <span class="hljs-string">"Athens"</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">travel_plans</span>():</span>
    <span class="hljs-comment">#First, this is like when I tried to access the global variable defined outside the function. </span>
    <span class="hljs-comment"># This works fine on its own, as you saw earlier on.</span>
    print(<span class="hljs-string">f"I want to visit <span class="hljs-subst">{city}</span> next year!"</span>)

    <span class="hljs-comment">#However, when I then try to re-assign a different value to the global variable 'city' from inside the function,</span>
    <span class="hljs-comment">#after trying to print it,</span>
    <span class="hljs-comment">#it will throw an error</span>
    city = <span class="hljs-string">"London"</span>
    print(<span class="hljs-string">f"I want to visit <span class="hljs-subst">{city}</span> next year!"</span>)

<span class="hljs-comment">#call function</span>
travel_plans()

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#UnboundLocalError: local variable 'city' referenced before assignment</span>
</code></pre>
<p>By default Python thinks you want to use a local variable inside a function.</p>
<p>So, when I first try to print the value of the variable and <em>then</em> re-assign a value to the variable I am trying to access, Python gets confused.</p>
<p>The way to change the value of a global variable inside a function is by using the <code>global</code> keyword:</p>
<pre><code class="lang-python"><span class="hljs-comment">#global variable</span>
city = <span class="hljs-string">"Athens"</span>

<span class="hljs-comment">#print value of global variable</span>
print(<span class="hljs-string">f"I want to visit <span class="hljs-subst">{city}</span> next year!"</span>)

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">travel_plans</span>():</span>
    <span class="hljs-keyword">global</span> city
    <span class="hljs-comment">#print initial value of global variable</span>
    print(<span class="hljs-string">f"I want to visit <span class="hljs-subst">{city}</span> next year!"</span>)
    <span class="hljs-comment">#assign a different value to global variable from within function</span>
    city = <span class="hljs-string">"London"</span>
    <span class="hljs-comment">#print new value</span>
    print(<span class="hljs-string">f"I want to visit <span class="hljs-subst">{city}</span> next year!"</span>)

<span class="hljs-comment">#call function</span>
travel_plans()

<span class="hljs-comment">#print value of global variable</span>
print(<span class="hljs-string">f"I want to visit <span class="hljs-subst">{city}</span> next year!"</span>)
</code></pre>
<p>Use the <code>global</code> keyword before referencing it in the function, as you will get the following error: <code>SyntaxError: name 'city' is used prior to global declaration</code>.</p>
<p>Earlier, you saw that you couldn't access variables created inside functions since they have local scope.</p>
<p>The <code>global</code> keyword changes the visibility of variables declared inside functions.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">learn_to_code</span>():</span>
   <span class="hljs-keyword">global</span> coding_website
   coding_website = <span class="hljs-string">"freeCodeCamp"</span>
   print(<span class="hljs-string">f"The best place to learn to code is with <span class="hljs-subst">{coding_website}</span>!"</span>)

<span class="hljs-comment">#call function</span>
learn_to_code()

<span class="hljs-comment">#access variable from within the function</span>
print(coding_website)

<span class="hljs-comment">#output</span>

<span class="hljs-comment">#The best place to learn to code is with freeCodeCamp!</span>
<span class="hljs-comment">#freeCodeCamp</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>And there you have it! You now know the basics of global variables in Python and can tell the differences between local and global variables.</p>
<p>I hope you found this article useful.</p>
<p>To learn more about the Python programming language, check out freeCodeCamp's <a target="_blank" href="https://www.freecodecamp.org/learn/scientific-computing-with-python/">Scientific Computing with Python Certification</a>.</p>
<p>You'll start from the basics and learn in an interactive and beginner-friendly way. You'll also build five projects at the end to put into practice and help reinforce what you've learned.</p>
<p>Thanks for reading and happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ CSS Variables Definition – What are CSS Vars and How to Use Them? ]]>
                </title>
                <description>
                    <![CDATA[ CSS variables are custom variables that you can create and reuse throughout your stylesheet.  In this article, I will show you how to create CSS variables on the :root pseudo selector and show you how to access them using the var() function.  How to ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-are-css-variables-and-how-to-use-them/</link>
                <guid isPermaLink="false">66b8da5c98b552b8a8592b31</guid>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ variables ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jessica Wilkins ]]>
                </dc:creator>
                <pubDate>Mon, 25 Apr 2022 22:47:25 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/pankaj-patel-6JVlSdgMacE-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>CSS variables are custom variables that you can create and reuse throughout your stylesheet. </p>
<p>In this article, I will show you how to create CSS variables on the <code>:root</code> pseudo selector and show you how to access them using the <code>var()</code> function. </p>
<h2 id="heading-how-to-create-a-css-custom-variable">How to Create a CSS Custom Variable</h2>
<p>Here is the basic syntax for defining a custom CSS variable:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">--css-variable-name</span>: <span class="hljs-selector-tag">css</span> <span class="hljs-selector-tag">property</span> <span class="hljs-selector-tag">value</span>;
</code></pre>
<p>It is best practice to define all of your variables at the top of your stylesheet. For larger projects, it is common to create a separate file just for your custom color variables so you can reuse them throughout other stylesheets. </p>
<p>If you want to access that variable, then you would use the <code>var()</code> function. Here is the basic syntax.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">css</span> <span class="hljs-selector-tag">property</span>: <span class="hljs-selector-tag">var</span>(<span class="hljs-selector-tag">--css-variable-name</span>);
</code></pre>
<p>In this example, I want to create custom background and text color variables that I can reuse throughout the stylesheet. I am going to name these variables <code>--main-bg-color</code> and <code>--main-text-color</code>. </p>
<pre><code class="lang-css">  <span class="hljs-selector-tag">--main-bg-color</span>: <span class="hljs-selector-id">#000080</span>;
  <span class="hljs-selector-tag">--main-text-color</span>: <span class="hljs-selector-id">#fff</span>;
</code></pre>
<p>I am going to place these variables inside of the <code>:root</code> pseudo selector which represents the root element in my HTML document. </p>
<pre><code class="lang-css"><span class="hljs-selector-pseudo">:root</span> {
  <span class="hljs-attribute">--main-bg-color</span>: <span class="hljs-number">#000080</span>;
  <span class="hljs-attribute">--main-text-color</span>: <span class="hljs-number">#fff</span>;
}
</code></pre>
<p>In my <code>body</code> selector, I am going to reference those variables using the <code>var()</code> function.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--main-bg-color);
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">var</span>(--main-text-color);
}
</code></pre>
<p>Here is a working example:</p>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/jessica-wilkins/embed/LYeoOmP?editors=1100" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p>If I wanted to add more content to the page then I could reuse those variables throughout the rest of the stylesheet and avoid unnecessary repetition like this:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.example-class-1</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#000080</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-direction</span>: column;
}

<span class="hljs-selector-class">.example-class-2</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">2.1rem</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
}

<span class="hljs-selector-class">.example-class-3</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#000080</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> solid black;
}
</code></pre>
<p>In this second example, I have 6 red, green, and blue boxes on the page. I first created the HTML markup for the boxes.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box-container"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box red-box"</span>&gt;</span>Box 1<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box green-box"</span>&gt;</span>Box 2<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box blue-box"</span>&gt;</span>Box 3<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box-container"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box blue-box"</span>&gt;</span>Box 4<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box green-box"</span>&gt;</span>Box 5<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box red-box"</span>&gt;</span>Box 6<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p> I then created a set of custom red, green, and blue variables.</p>
<pre><code class="lang-css"><span class="hljs-selector-pseudo">:root</span> {
  <span class="hljs-attribute">--maroon-red</span>: <span class="hljs-number">#800000</span>;
  <span class="hljs-attribute">--dark-green</span>: <span class="hljs-number">#013220</span>;
  <span class="hljs-attribute">--navy-blue</span>: <span class="hljs-number">#000080</span>;
  <span class="hljs-attribute">--white</span>: <span class="hljs-number">#fff</span>;
}
</code></pre>
<p>Lastly, I applied those variables to my boxes using the <code>var()</code> function.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.red-box</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--maroon-red);
}

<span class="hljs-selector-class">.green-box</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--dark-green);
}

<span class="hljs-selector-class">.blue-box</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--navy-blue);
}
</code></pre>
<p>Here is what the complete code and final result looks like:</p>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/jessica-wilkins/embed/WNdBXXZ?editors=1100" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<h2 id="heading-how-to-name-css-variables">How to Name CSS Variables</h2>
<p>When it comes to naming variables, you want to choose short descriptive names so other developers know what those variables are. </p>
<p>This would be an example of a bad variable name:</p>
<pre><code class="lang-css"> <span class="hljs-selector-tag">background-color</span><span class="hljs-selector-pseudo">:var(--color)</span>;
</code></pre>
<p>What is <code>--color</code>?</p>
<p>Is it some shade of red? Green? Blue? Something else?</p>
<p>Is it a main background color or main text color? </p>
<p>You don't want other developers to have to go back and look at the CSS definition to figure out what it should be. </p>
<p>Another example is if you were creating custom CSS variables for different shades of colors, then you could choose to name them this way:</p>
<pre><code class="lang-css"><span class="hljs-selector-pseudo">:root</span> {
  <span class="hljs-attribute">--maroon-red</span>: <span class="hljs-number">#800000</span>;
  <span class="hljs-attribute">--light-red</span>: <span class="hljs-number">#ff0000</span>;
  <span class="hljs-attribute">--crimson-red</span>: <span class="hljs-number">#e32636</span>;
}
</code></pre>
<p>Every developer will have their own way of naming variables. The important thing to remember is to provide descriptive names for your variables. </p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>CSS variables are custom variables that you can create and reuse throughout your stylesheet.  </p>
<p>Here is the basic syntax for defining a custom CSS variable.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">--css-variable-name</span>: <span class="hljs-selector-tag">css</span> <span class="hljs-selector-tag">property</span> <span class="hljs-selector-tag">value</span>;
</code></pre>
<p>If you want to access that variable, then you would use the <code>var()</code> function. Here is the basic syntax.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">css</span> <span class="hljs-selector-tag">property</span>: <span class="hljs-selector-tag">var</span>(<span class="hljs-selector-tag">--css-variable-name</span>);
</code></pre>
<p>Every developer will have their own way of naming variables but it is best practice to create short descriptive names.</p>
<p>I hope you enjoyed this article and best of luck on your CSS journey.   </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Print Type of Variable – How to Get Var Type ]]>
                </title>
                <description>
                    <![CDATA[ If you're a Python beginner, becoming familiar with all its various data types can be confusing at first. After all, there are a lot of them available to you in the language. In this article, I'm going to show you how to get the type of various data ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-print-type-of-variable-how-to-get-var-type/</link>
                <guid isPermaLink="false">66adf1e311a28b6eb378d2c6</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ variables ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Wed, 16 Feb 2022 18:16:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/02/typeinpython.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you're a Python beginner, becoming familiar with all its various data types can be confusing at first. After all, there are a lot of them available to you in the language.</p>
<p>In this article, I'm going to show you how to get the type of various data structures in Python by assigning them to a variable, and then printing the type to the console with the <code>print()</code> function.</p>
<h2 id="heading-how-to-print-the-type-of-a-variable-in-python">How to Print the Type of a Variable in Python</h2>
<p>To get the type of a variable in Python, you can use the built-in <code>type()</code> function. </p>
<p>The basic syntax looks like this:</p>
<pre><code class="lang-py">type(variableName)
</code></pre>
<p>In Python, everything is an object. So, when you use the <code>type()</code> function to print the type of the value stored in a variable to the console, it returns the class type of the object. </p>
<p>For instance, if the type is a string and you use the <code>type()</code> on it, you'd get <code>&lt;class ‘string‘&gt;</code> as the result.</p>
<p>To show you the <code>type()</code> function in action, I'm going to declare some variables and assign to them the various data types in Python. </p>
<pre><code class="lang-py">name = <span class="hljs-string">"freeCodeCamp"</span>

score = <span class="hljs-number">99.99</span>

lessons =  [<span class="hljs-string">"RWD"</span>, <span class="hljs-string">"JavaScript"</span>, <span class="hljs-string">"Databases"</span>, <span class="hljs-string">"Python"</span>]

person = {
    <span class="hljs-string">"firstName"</span>: <span class="hljs-string">"John"</span>,
    <span class="hljs-string">"lastName"</span>: <span class="hljs-string">"Doe"</span>,
    <span class="hljs-string">"age"</span>: <span class="hljs-number">28</span>
}

langs = (<span class="hljs-string">"Python"</span>, <span class="hljs-string">"JavaScript"</span>, <span class="hljs-string">"Golang"</span>)

basics = {<span class="hljs-string">"HTML"</span>, <span class="hljs-string">"CSS"</span>, <span class="hljs-string">"JavaScript"</span>}
</code></pre>
<p>I will then print the types to the console by wrapping <code>print()</code> around some strings and the <code>type()</code> function. </p>
<pre><code class="lang-py">print(<span class="hljs-string">"The variable, name is of type:"</span>, type(name))
print(<span class="hljs-string">"The variable, score is of type:"</span>, type(score))
print(<span class="hljs-string">"The variable, lessons is of type:"</span>, type(lessons))
print(<span class="hljs-string">"The variable, person is of type:"</span>, type(person))
print(<span class="hljs-string">"The variable, langs is of type:"</span>, type(langs))
print(<span class="hljs-string">"The variable, basics is of type:"</span>, type(basics))
</code></pre>
<p><strong>Here are the outputs:</strong></p>
<pre><code># Outputs:
# The variable, name is <span class="hljs-keyword">of</span> type:  &lt;class 'str'&gt;
# The variable, score is of type: &lt;class 'float'&gt;  
# The variable, lessons is of type:  &lt;class 'list'&gt;
# The variable, person is of type:  &lt;class 'dict'&gt; 
# The variable, langs is of type:  &lt;class 'tuple'&gt; 
# The variable, basics is of type:  &lt;class 'set'&gt;
</code></pre><h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>The <code>type()</code> function is a valuable built-in function of Python with which you can get the data type of a variable.</p>
<p>If you're a beginner, you should save yourself the hassle of cramming data types by using the <code>type()</code> function to print the type of a variable to the console. This will save you some time.</p>
<p>You can also use the <code>type()</code> function for debugging because in Python, variables are not declared with data types. So, the <code>type()</code> function was built into the language for you to check for data types of variables.</p>
<p>Thank you for reading.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Manage Directory-Scoped Variables with direnv in POSIX Systems ]]>
                </title>
                <description>
                    <![CDATA[ By Otavio Ehrenberger A common practice in software projects is to keep certain information separated but accessible from the codebase which uses it. Developers usually do this with secrets such as passwords or private keys, or with user or context-s... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-manage-directory-scoped-envs-with-direnv-in-posix-systems/</link>
                <guid isPermaLink="false">66d851f3a2a6d73be8613879</guid>
                
                    <category>
                        <![CDATA[ Productivity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ unix ]]>
                    </category>
                
                    <category>
                        <![CDATA[ variables ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 22 Nov 2021 21:39:20 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/11/pexels-aleksejs-bergmanis-681335.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Otavio Ehrenberger</p>
<p>A common practice in software projects is to keep certain information separated but accessible from the codebase which uses it. Developers usually do this with secrets such as passwords or private keys, or with user or context-specific info pieces. </p>
<p>But managing environment variables can be a pain. There are a number of solutions to ease that pain, and there are even built-in ones such as <a target="_blank" href="https://www.baeldung.com/linux/bashrc-vs-bash-profile-vs-profile">bash_profile</a>.</p>
<p>One solution I've discovered recently and found particularly convenient is <a target="_blank" href="https://github.com/direnv/direnv">direnv</a>. It's a shell extension which lets you define environment variables scoped by directory. </p>
<p>After installing and hooking the extension to your shell, <code>direnv</code> will execute every time you change directories, looking for an <code>.envrc</code> file in the same or in a superior directory tree level. It will then load the defined variables to the current environment, and unload them if it ceases to detect the same <code>.envrc</code>.</p>
<p>Note that <code>direnv</code> will load the first detected <code>.envrc</code> file, which means that <em>the environment will</em> <strong>not</strong> <em>inherit values from a</em> <code>.envrc</code> <em>in a parent directory</em>.</p>
<p>It is also important to keep in mind that the environment variables <em>will only be loaded to your shell session once you move to a directory affected by a</em> <code>.envrc</code> <em>file</em>. So if you try something like running a script which loads an environment defined in a directory below your current level, the variables won't be accessible.</p>
<h2 id="heading-how-to-install-direnv">How to Install <code>direnv</code></h2>
<p>Here's a <a target="_blank" href="https://direnv.net/docs/installation.html">list of supported systems</a>. It is very likely that your UNIX-based system's main open source package manager has it available. </p>
<p>Suppose we are on Debian, we can install <code>direnv</code> by running the standard external package install command in the terminal:</p>
<pre><code class="lang-bash">sudo apt-get install direnv
</code></pre>
<h2 id="heading-how-to-setup-direnv">How to Setup <code>direnv</code></h2>
<p>After you install it, you need to hook <code>direnv</code> to your shell. If you're using bash, you can do this by appending this line to the end of your shell startup config file:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">'eval "$(direnv hook bash)"'</span> &gt;&gt; ~/.bashrc
</code></pre>
<p>It's almost the same for ZShell:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">'eval "$(direnv hook zsh)"'</span> &gt;&gt; ~/.zshrc
</code></pre>
<p>Direnv also supports FISH, TCSH, and Elvish. <a target="_blank" href="https://direnv.net/docs/hook.html">Here are the hooking instructions for each supported shell</a>.</p>
<h2 id="heading-how-to-use-direnv">How to Use <code>direnv</code></h2>
<p>Now we must create an <code>.envrc</code> file for the directory we would like to scope the environment variables to.</p>
<p>Say we create it for the directory <code>~/project</code>.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-built_in">export</span> FOO=<span class="hljs-string">'I love Linux!'</span> &gt;&gt; ~/project/.envrc
</code></pre>
<p>You will then receive a warning that the current <code>.envrc</code> wasn't read. <code>direnv</code> will block loading <code>.envrc</code> every time it detects changes which were not explicitly allowed. So now run:</p>
<pre><code class="lang-bash">direnv allow ~/project
</code></pre>
<p>and voilà!, you now have a directory-scoped environment.</p>
<p>Remember when I told you that '<code>direnv</code> will block loading <code>.envrc</code> every time it detects changes which were not explicitly allowed'? This isn't limited to newly introduced changes – the whole file will be unauthorized. So when you do this:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-built_in">export</span> BAR=<span class="hljs-string">'It is actually called GNU/Linux!'</span> &gt;&gt; ~/project/.envrc
</code></pre>
<p>you will have to run <code>direnv allow ~/project</code> again, even to access <code>$FOO</code>. Kinda boring, but biased towards safety.</p>
<p>Every time an <code>.envrc</code> is loaded, direnv will output a message with the file path and also the names of the variables loaded, so you don't need to worry about forgetting your setup. It will also tell you whenever an environment was unloaded.</p>
<h3 id="heading-thanks-for-reading">Thanks for reading!</h3>
<p>That's it! It's pretty straightforward, and I hope you find it as convenient as I did.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Variable Scope in C – Local and Global Scope Explained ]]>
                </title>
                <description>
                    <![CDATA[ In programming, you'll often have to deal with the scope of a variable. The scope of a variable determines whether or not you can access and modify it inside a specific block of code. In this tutorial, you'll learn about variable scope in the C progr... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/scope-of-variables-in-c-local-and-global-scope-explained/</link>
                <guid isPermaLink="false">66bb8b5ccaaeb78feb348940</guid>
                
                    <category>
                        <![CDATA[ c programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ variables ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Bala Priya C ]]>
                </dc:creator>
                <pubDate>Wed, 08 Sep 2021 16:40:21 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/09/Scope-of-variables-in-c.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In programming, you'll often have to deal with the scope of a variable. The scope of a variable determines whether or not you can access and modify it inside a specific block of code.</p>
<p>In this tutorial, you'll learn about variable scope in the C programming language. You'll see some code examples to help you understand the differences between local and global variables.</p>
<h2 id="heading-what-is-the-scope-of-a-variable">What is the Scope of a Variable?</h2>
<p>Before going ahead to learn about local and global variable scope, let's understand what <em>scope</em> means. </p>
<blockquote>
<p>In simple terms, scope of a variable is its <em>lifetime</em> in the program.</p>
</blockquote>
<p>This means that the scope of a variable is the block of code in the entire program where the variable is declared, used, and can be modified. </p>
<p>In the next section, you'll learn about local scope of variables</p>
<h2 id="heading-local-scope-of-variables-in-c-nested-blocks">Local Scope of Variables in C – Nested Blocks</h2>
<p>In this section, you'll learn how local variables work in C. You'll first code a couple of examples, and then you'll generalize the scoping principle.</p>
<p>▶ Here's the first example:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> 
</span>{
    <span class="hljs-keyword">int</span> my_num = <span class="hljs-number">7</span>;
    {
        <span class="hljs-comment">//add 10 my_num</span>
        my_num = my_num +<span class="hljs-number">10</span>;
        <span class="hljs-comment">//or my_num +=10 - more succinctly</span>
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"my_num is %d"</span>,my_num);
    }

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Let's understand what the above program does. </p>
<p>In C, you delimit a block of code by <code>{}</code> . The opening and closing curly braces indicate the beginning and the end of a block, respectively.</p>
<ul>
<li>The <code>main()</code> function has an integer variable <code>my_num</code> that's initialized to 7 in the <em>outer</em> block.</li>
<li>There's an <em>inner</em> block that tries to add 10 to the variable <code>my_num</code>.</li>
</ul>
<p>Now, compile and run the above program. Here's the output:</p>
<pre><code><span class="hljs-comment">//Output</span>

my_num is <span class="hljs-number">17</span>
</code></pre><p>You can see the following:</p>
<ul>
<li>The inner block is able to access the value of <code>my_num</code> that's declared in the outer block, and modify it by adding 7 to it. </li>
<li>The value of <code>my_num</code> is now 17, as indicated in the output.</li>
</ul>
<h2 id="heading-local-scope-of-variables-in-c-nested-blocks-example-2">Local Scope of Variables in C – Nested Blocks Example 2</h2>
<p>▶ Here's another related example:</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> 
</span>{
    <span class="hljs-keyword">int</span> my_num = <span class="hljs-number">7</span>;
    {
        <span class="hljs-keyword">int</span> new_num = <span class="hljs-number">10</span>;
    } 
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"new_num is %d"</span>,new_num); <span class="hljs-comment">//this is line 9</span>
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<ul>
<li>In this program, the <code>main()</code> function has an integer variable <code>my_num</code> in the <em>outer</em> block.</li>
<li>Another variable <code>new_num</code> is initialized in the <em>inner</em> block. The inner block is nested inside the outer block.</li>
<li>We're trying to access and print the value of inner block's <code>new_num</code> in the <em>outer</em> block.</li>
</ul>
<p>If you try compiling the above code, you'll notice that it doesn't compile successfully. And you'll get the following error message:</p>
<pre><code>Line   Message
<span class="hljs-number">9</span>      error: <span class="hljs-string">'new_num'</span> undeclared (first use <span class="hljs-keyword">in</span> <span class="hljs-built_in">this</span> <span class="hljs-function"><span class="hljs-keyword">function</span>)</span>
</code></pre><blockquote>
<p>This is because the variable <code>new_num</code> is declared in the <em>inner</em> block and its <em>scope</em> is limited to the inner block. In other words, it is <em>local</em> to the inner block and <em>cannot</em> be accessed from the <em>outer</em> block.</p>
</blockquote>
<p>Based on the above observations, let's write down the following generic principle for local scoping of variables:</p>
<pre><code>{
    <span class="hljs-comment">/*OUTER BLOCK*/</span>

      {


        <span class="hljs-comment">//contents of the outer block just before the start of this block</span>
        <span class="hljs-comment">//CAN be accessed here</span>

        <span class="hljs-comment">/*INNER BLOCK*/</span>


      }

       <span class="hljs-comment">//contents of the inner block are NOT accessible here</span>
 }
</code></pre><h2 id="heading-local-scope-of-variables-in-c-different-blocks">Local Scope of Variables in C – Different Blocks</h2>
<p>In the previous example, you learned how variables inside the nested inner block cannot be accessed from outside the block. </p>
<p>In this section, you'll understand the local scope of variables declared in different blocks.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">int</span> my_num = <span class="hljs-number">7</span>;
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d"</span>,my_num);
    my_func();
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">my_func</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%d"</span>,my_num);
}
</code></pre>
<p>In the above example,</p>
<ul>
<li>The integer variable <code>my_num</code> is declared inside the <code>main()</code> function.</li>
<li>Inside the <code>main()</code> function, the value of <code>my_num</code> is printed out.</li>
<li>There's another function <code>my_func()</code> that tries to access and print the value of <code>my_num</code>.</li>
<li>As program execution starts with the <code>main()</code> function, there's a call to <code>my_func()</code> inside the <code>main()</code> function.</li>
</ul>
<p>▶ Now compile and run the above program. You'll get the following error message:</p>
<pre><code>Line   Message
<span class="hljs-number">13</span>     error: <span class="hljs-string">'my_num'</span> undeclared (first use <span class="hljs-keyword">in</span> <span class="hljs-built_in">this</span> <span class="hljs-function"><span class="hljs-keyword">function</span>)</span>
</code></pre><p>If you notice, on <code>line 13</code>, the function <code>my_func()</code> tried accessing the <code>my_num</code> variable that was declared and initialized inside the <code>main()</code> function.</p>
<blockquote>
<p>Therefore, the scope of the variable <code>my_num</code> is confined to the <code>main()</code> function, and is said to be <em>local</em> to the <code>main()</code> function.</p>
</blockquote>
<p>We can represent this notion of local scope generically as follows:</p>
<pre><code>{

    <span class="hljs-comment">/*BLOCK 1*/</span>
    <span class="hljs-comment">// contents of BLOCK 2 cannot be accessed here</span>

}


{

    <span class="hljs-comment">/*BLOCK 2*/</span>
    <span class="hljs-comment">// contents of BLOCK 1 cannot be accessed here</span>

}
</code></pre><h2 id="heading-global-scope-of-variables-in-c">Global Scope of Variables in C</h2>
<p>So far, you've learned about local scope of C variables. In this section, you'll learn how you can declare global variables in C.</p>
<p>▶ Let's start with an example.</p>
<pre><code class="lang-c"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;stdio.h&gt;</span></span>
<span class="hljs-keyword">int</span> my_num = <span class="hljs-number">7</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"my_num can be accessed from main() and its value is %d\n"</span>,my_num);
    <span class="hljs-comment">//call my_func</span>
    my_func();
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">my_func</span><span class="hljs-params">()</span>
</span>{
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"my_num can be accessed from my_func() as well and its value is %d\n"</span>,my_num);
}
</code></pre>
<p>In the above example,</p>
<ul>
<li>The variable <code>my_num</code> is declared outside the functions <code>main()</code> and <code>my_func()</code>.</li>
<li>We try to access <code>my_num</code> inside the <code>main()</code> function, and print its value.</li>
<li>We call the function <code>my_func()</code> inside the <code>main()</code> function.</li>
<li>The function <code>my_func()</code> also tries to access the value of <code>my_num</code>, and print it out.</li>
</ul>
<p>This program compiles without any error, and the output is shown below:</p>
<pre><code><span class="hljs-comment">//Output</span>
my_num can be accessed <span class="hljs-keyword">from</span> main() and its value is <span class="hljs-number">7</span>
my_num can be accessed <span class="hljs-keyword">from</span> my_func() <span class="hljs-keyword">as</span> well and its value is <span class="hljs-number">7</span>
</code></pre><p>In this example, there are two functions – the <code>main()</code> and <code>my_func()</code>. </p>
<p>However, the variable <code>my_num</code> is <em>not local</em> to any function in the program. Such a variable that is <em>not local</em> to any function is said to have <em>global</em> scope and is called a <em>global</em> variable.</p>
<p>This principle of global scope of variables can be summarized as shown below:</p>
<pre><code><span class="hljs-comment">//all global variables are declared here</span>
function1()
    {

    <span class="hljs-comment">// all global variables can be accessed inside function1</span>

    }
function2()
    {

    <span class="hljs-comment">// all global variables can be accessed inside function2</span>

    }
</code></pre><h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this tutorial, you've learned the differences between local and global scope. This is an introductory tutorial on variable scope in C. </p>
<p>In C, there are certain access modifiers to control the level of access that the variables have. You can change access by using the corresponding keywords when you declare variables. </p>
<p>See you all in the next tutorial. Until then, happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Variables – A Beginner's Guide to var, const, and let ]]>
                </title>
                <description>
                    <![CDATA[ By Madison Kanna Variables are a fundamental concept in any programming language. In JavaScript, you can declare variables by using the keywords var, const, or let. In this article, you’ll learn why we use variables, how to use them, and the differen... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-variables-beginners-guide/</link>
                <guid isPermaLink="false">66d8519029e30bc0ad477596</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ variables ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 30 Nov 2020 18:24:36 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/11/Screen-Shot-2020-11-22-at-8.51.01-PM.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Madison Kanna</p>
<p>Variables are a fundamental concept in any programming language. In JavaScript, you can declare variables by using the keywords var, const, or let.</p>
<p>In this article, you’ll learn why we use variables, how to use them, and the differences between const, let and var.</p>
<h2 id="heading-what-are-variables-used-for-in-javascript"><strong>What are variables used for in JavaScript?</strong></h2>
<p>In the context of coding, data is information that we use in our computer programs. For example, your Twitter username is a piece of data.</p>
<p>Much of programming is about manipulating or displaying data. In order to do this, programmers need a way of storing and keeping track of data. Let's demonstrate this with an example.</p>
<p>First we’ll open up our JavaScript console. To launch your JavaScript console on Chrome, you can use the shortcut Ctrl + Shift + J on Windows and Linux. For Mac, use Cmd + Option + J.  </p>
<p>Once the console has launched, think of your dog or cat’s current age (or any similar number if you don't have pets) and enter it into the console.</p>
<pre><code class="lang-js"><span class="hljs-number">4</span>
</code></pre>
<p>Now what if we want to refer to that number again? We’ll have to type it out for a second time.</p>
<p>We need a way to refer to this piece of data so we can reuse it throughout our program.</p>
<h2 id="heading-introducing-variables-in-javascript"><strong>Introducing variables in JavaScript</strong></h2>
<p>A helpful analogy is to think of variables as labels for our values. Think of a container of blueberries with a label on it marked blueberries. In this example, the variable, <em>blueberries</em>, points to a value, which is the blueberries themselves.</p>
<p>Let's declare a variable, age, and use the assignment operator (the equals sign) to assign our value, 4, to this variable. We’ll use the var keyword.</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> age = <span class="hljs-number">4</span>
</code></pre>
<p>Variables are how programmers give a name to a value so that we can reuse it, update it, or simply keep track of it. Variables can be used to store any JavaScript type.</p>
<p>Now that we’ve assigned this value to the variable age, we can refer back to this value later. If you now type in the variable age in your console, you’ll have the value of 4 returned back to you.</p>
<h2 id="heading-how-to-use-the-var-keyword-in-javascript">How to use the var keyword in JavaScript</h2>
<p>Keywords in JavaScript are reserved words. When you use the var keyword, you’re telling JavaScript you’ll be declaring a variable.</p>
<p>When using the var keyword, variables can be reassigned. We’ll demonstrate this by first declaring a new variable, name, and assigning it to the value of Madison.</p>
<pre><code><span class="hljs-keyword">var</span> name = <span class="hljs-string">'Madison'</span>
</code></pre><p>Next, we’ll reassign this variable to point to the value of a different name, Ben.</p>
<pre><code>name = <span class="hljs-string">'Ben'</span>
</code></pre><p>Now if you run <code>console.log(name)</code> you’ll get the output of Ben.</p>
<p>When using the var keyword, variables can also be declared with no initial value.</p>
<pre><code><span class="hljs-keyword">var</span> year
</code></pre><p>Here, we’ve declared a variable <code>year</code> but it does not point to any value. Later on if we want it to point to a value, we can use the assignment operator to do so.</p>
<pre><code>year = <span class="hljs-number">2020</span>
</code></pre><p>Now our variable year will point to the value of 2020.</p>
<p>When JavaScript was first created, the only way to declare a variable was with the var keyword.</p>
<p>In recent updates to JavaScript (ECMAScript2015), <code>const</code> and <code>let</code> were created as other keywords to declared variables. </p>
<p>To explain why they were needed, we’ll look at problems with the var keyword. In order to look at these problems, we’ll learn about what scope is.</p>
<h2 id="heading-what-is-scope">What is scope?</h2>
<p>Scope refers to where in our code variables are available for use. When a variable is <em>globally scoped</em>, that means it is available anywhere in your program. Let’s look at an example. </p>
<p>Take the following code and enter it into your console.</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> name = ‘Bob’
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printName</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(name)
}
printName()
</code></pre>
<p>Here we’ve created and called a function, printName, that will print the value of the name var, <code>Madison</code>. You’ll see this printed in your console.</p>
<p>Because our var was created outside of the function, it is globally scoped. This means that it is available anywhere in your code, including inside of any function. This is why our function, printName, has access to the name var.</p>
<p>Let’s now create a variable that is function-scoped. This means that the variable is only accessible inside the function it was created in. This next example will be very similar to the code above, but with a different placement of the variable. </p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printYear</span>(<span class="hljs-params"></span>) </span>{
 <span class="hljs-keyword">var</span> year = <span class="hljs-number">2020</span>
}
<span class="hljs-built_in">console</span>.log(year)
</code></pre>
<p>Now in our console we’ll get an error: <code>year is not defined.</code> This is because the var year is function-scoped. That is, it only exists inside of the function it was created in. We don’t have access to it outside of the function, which is where we’re trying to access it when we run our console.log.</p>
<p>Function-scoped variables are helpful to programmers because we often want to create variables that are only useful or needed inside a certain function. Creating global variables can also lead to errors or mistakes.</p>
<p>Now that we have a basic understanding of scope, we can return to our discussion of problems with the var keyword.</p>
<h2 id="heading-problems-with-the-var-keyword-in-javascript">Problems with the var keyword in JavaScript</h2>
<p>Let's look at another example. </p>
<p>We'll create a variable, <code>age</code>. Next we’ll write an if statement that checks if age has a value, and if it does, returns a console.log of the number that is double that age. </p>
<p>This is a simplified example, but we’ll first check if age has a value because we want to make sure we are adding to a valid value. </p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> age = <span class="hljs-number">27</span>
If (age) {
 <span class="hljs-keyword">var</span> doubleAge = age + age
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Double your current age is <span class="hljs-subst">${yearPlusTwenty}</span>`</span>)
}
</code></pre>
<p>Now in our console, you’ll see <code>Double your current age is 47</code>.</p>
<p>Our variable, <code>doubleAge</code>, is now a global variable. If you enter <code>doubleAge</code> into your console, you’ll see that you have access to it.</p>
<pre><code class="lang-js">doubleAge
<span class="hljs-number">47</span>
</code></pre>
<p>As previously discussed, variables created with the var keyword are function-scoped. Function-scoped variables only exist inside of the function they were created in. </p>
<p>But since the <code>doubleAge</code> variable is not inside a function, that means it has been scoped globally. That is, the <code>doubleAge</code> variable is now available anywhere in our code.</p>
<p>The problem is, <code>doubleAge</code> is just a variable we used once inside of our <code>if statement</code>, and we don’t necessarily need it available everywhere in our code. It has “leaked” outside of the if statement it was created in, even though we didn’t need it to.</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> age = <span class="hljs-number">27</span>
<span class="hljs-keyword">if</span> (age) {
 <span class="hljs-comment">//We need our doubleAge var only in this block of code in between our curley brackets. </span>
    <span class="hljs-keyword">var</span> doubleAge = age + age
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Double your current age is <span class="hljs-subst">${yearPlusTwenty}</span>`</span>)

}

doubleAge
<span class="hljs-number">47</span>
<span class="hljs-comment">//our doubleAge var is available outside of these curly brackets, on the global sbope.</span>
</code></pre>
<p>It would be great if we had a way of creating a variable that <em>only</em> existed inside the if statement it was created in. In other words, the block of code that exists in between the curly brackets. </p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> age = <span class="hljs-number">27</span>
If (age) {
 <span class="hljs-comment">//We want our variable to only exist here, where we will use it</span>
 <span class="hljs-keyword">var</span> doubleAge = age + age
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Double your current age is <span class="hljs-subst">${yearPlusTwenty}</span>`</span>)
}
</code></pre>
<p>To help fix this problem, the const and let keywords were introduced in JavaScript.</p>
<h2 id="heading-how-to-use-the-const-keyword-in-javascript">How to use the const keyword in JavaScript</h2>
<p><code>const</code> works similarly to var, but with a few big differences.</p>
<p>First, <code>const</code> is <em>block</em>-scoped, whereas var is <em>function</em>-scoped.</p>
<p>What is a <strong>block</strong>? </p>
<p>A <em>block</em> refers to any space between an opening and closing bracket. This might seem confusing at first. Let's write out our previous example, but this time using const instead of let when declaring our <code>doubleAge</code> variable.</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> age = <span class="hljs-number">27</span>
If (age) {
 <span class="hljs-keyword">const</span> doubleAge = age + age
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Double your current age is <span class="hljs-subst">${yearPlusTwenty}</span>`</span>)
}
</code></pre>
<p>Now, type <code>doubleAge</code> into your console and hit enter. You should get an error, <code>doubleAge is not defined.</code> This is because const is block-scoped: <em>it only exists in the block it was defined.</em> </p>
<p>The  <code>doubleAge</code> variable is ‘trapped’ inside the two curly brackets it was defined in. Code that is also inside those brackets can access doubleAge, but no code outside of it can.</p>
<p>By using <code>const</code> instead of <code>var</code>, our previous problem is fixed. Our <code>doubleAge</code> var is no longer “leaking” into our global scope unnecessarily. Instead, it only exists inside of the block it was created in. </p>
<p>How do block-scoped variables work within the context of functions? To learn about this, let's create and then call a function, <code>returnX.</code></p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">returnX</span>(<span class="hljs-params"></span>) </span>{
 <span class="hljs-keyword">const</span> x = <span class="hljs-number">1</span>
 <span class="hljs-keyword">return</span> x
}
returnX()
</code></pre>
<p>By calling this function <code>returnX</code>, we can see that our function returns the value of x, which is 1.</p>
<p>If we next type in <code>x</code>, we’ll get back <code>referenceError: x is not defined</code>. This is because functions are also considered blocks, so our const <code>x</code> will exist only within the function.</p>
<p>The next thing to know about const is that it can only ever be declared once. Type this code into your console:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> y = <span class="hljs-number">1</span>
<span class="hljs-keyword">const</span> y = <span class="hljs-number">2</span>
</code></pre>
<p>You should see an error,  <code>Identifier 'x' has already been declared.</code></p>
<p>This is a difference between var and const. While const will give you an error, letting you know that you’ve already declared this variable, the var keyword won’t.</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> x = <span class="hljs-number">1</span>
<span class="hljs-keyword">var</span> x = <span class="hljs-number">2</span>
</code></pre>
<p>The variable <code>x</code> will point to the value of <code>2</code> without an error. This can cause bugs for you as a programmer, as perhaps you did not mean to reassign your value to a new variable. Thus, using const can help you as you’ll receive an error if you accidentally try to reassign a variable.</p>
<p>This is a strength of the <code>const</code> keyword that was introduced as an updated and better way of creating variables in JavaScript. However, what about the times when you <em>do</em> want to update your variable? </p>
<p>Let's look at an example that shows why we would want to do this.</p>
<p>Let's declare a variable, <code>adult</code>, and set it to <code>false</code>. We’ll also create an <code>age</code> variable and set it to <code>20</code>.</p>
<p><code>const adult = false</code></p>
<p><code>const age = 20.</code></p>
<p>Say we want to check a user’s age, and set our adult variable to false if age is over 18. We can write an if statement to do this.</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (age &gt; <span class="hljs-number">18</span>) {
 adult = <span class="hljs-literal">true</span>   
}
</code></pre>
<p>What happens when we run this code?</p>
<p>Here we’ll see <code>Error: Assignment to constant variable.</code></p>
<p>This is because, in accordance with the rules of <code>const</code>, we cannot redeclare this variable. That is, our variable <code>age</code> is already pointing to the value of true, and we cannot now point it to something else.  </p>
<p>If we print out <code>adult</code> again, we can see that it has stayed the same and still holds the value of <code>false</code>.</p>
<p>We cannot reassign our <code>age</code> variable, and <code>const</code> is working as expected. However, what if we <em>do</em> want to reassign this variable?</p>
<p>Often times programmers will want to be able to redeclare their variables. </p>
<p>This is where our third keyword, let, comes in.</p>
<h2 id="heading-how-to-use-the-let-keyword-in-javascript">How to use the let keyword in JavaScript</h2>
<p>First let’s go over how <code>let</code> is similar to <code>const</code>.</p>
<p><code>Let</code>, like <code>const</code>, is block-scoped. If you replaced const with let in our above <code>doubleAge</code> example, it would work the same.</p>
<p>However, <code>let</code> differs from <code>const</code> in a fundament way. Variables declared with the <code>let</code> keyword can be redeclared, while variables created with the <code>const</code> keyword cannot. Let’s go over an example.</p>
<p>Using our same example above, replace const with let. We’ll keep our age variable as a <code>const</code> with the value of <code>20</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> adult = <span class="hljs-literal">false</span>
<span class="hljs-keyword">const</span> age = <span class="hljs-number">20</span>
<span class="hljs-keyword">if</span> (age &gt; <span class="hljs-number">18</span>) {
    adult = <span class="hljs-literal">true</span>
}
</code></pre>
<p>Now if we type out <code>adult</code>, instead of getting an error as we previously did, we’ll see the output of <code>true</code>. </p>
<p>By using the <code>let</code> keyword, we’ve updated our variable to point to the value of <code>true</code> as we wanted to. Sometimes in programming we’ll want to update our variable depending on certain data that we receive. We can use <code>let</code> to do this.</p>
<h2 id="heading-wrapping-up">Wrapping up</h2>
<p>In summary, we’ve learned that variables are used to keep track of and reuse data in our computer programs. Scope refers to where in our code variables are available for use.</p>
<p>Variables can be declared using var, const, or let. Var is function-scoped, while const and let are block-scoped. Const variables cannot be reassigned, while let variables can be.  </p>
<p>Var, const, and let can be confusing at first. It can help to read different tutorials on them, as well as test out your own code in different ways to solidify your understanding. </p>
<p>Having a strong foundation of var, const, and let will help you not just at the start of your JavaScript career but throughout its entirety.</p>
<h3 id="heading-thank-you-for-reading">Thank you for reading!</h3>
<p>If you enjoyed this post, sign up for <a target="_blank" href="https://madisonkanna.us14.list-manage.com/subscribe/post?u=323fd92759e9e0b8d4083d008&amp;id=033dfeb98f">my email list</a> where I send out my latest articles and announce meetings for my coding book club.</p>
<p>If you have feedback or questions on this post, feel free to Tweet me @<a target="_blank" href="https://twitter.com/Madisonkanna">madisonkanna.</a></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
