JavaScript Variable Declaration and Initialization

Updated on August 21, 2019
Sam Shepards profile image

I'm a software developer with a great interest in data analysis and statistics.

Why Do We Use Variables?

A variable is one of the most important concepts in programming. Variables in JavaScript and in programming languages in general are a means to store and keep track of information in an application. For example, we need variables to keep track of a player’s score in a game. If we store a value in a data structure we call it a variable.

This is still in the application code and in memory. We can also write data to files and databases for later retrieval, but that is another topic.

Variables and State

Without variables, it is difficult to impossible to store things, keep track of a history or do complex manipulations and computations. In programming, we often describe this as programs having some form of internal state. In that sense, a variable holds a value and this variable or wide set of variables is that state. The value itself is more ephemeral.

The box or container analogy

It is said that variables are like boxes or containers. We can take an empty box then fill it with anything we want. Although this is a possible way to look at it, it can also give the wrong impression. Different variables can ‘have’ or hold the same value, or more precise, point to the same value.

In this sense, the box analogy can be somewhat misleading, since the value is not really inside that ‘box’. Two or more variables can point to that same value in memory, not just an identical value or copy. It’s probably best to presume that a variable points to a certain value and will give us the value when we ask for it.

Creating A Variable

Declaring a Variable Without Initializing

We start with the JavaScript syntax for creating variables. We can use the let keyword. We use the let keyword when variables are mutable. That means we can change or set the value later on in the program. When the value of the variable will never change, when it stays constant, we use the keyword const. These keywords are available since ECMAScript 6 standard.

Before ES6 there was the var keyword, but this one has some problems were we don't go in this article. When possible avoid the var keyword, but you'll see it in older programs.

We follow it with a whitespace and a name for our variable. Next, we can decide to assign it an initial value or leave it unassigned. Declaration without initialization:

let score;

We can still assign the value later on.

Variable Declaration and Initialization

We initialize our variable by assigning it a value. We can use a literal value, another variable(s) or the result of some computation or expression. Don’t forget a semicolon at the end of the expression. Declaration with initialization:

let score = 5; 

or

const pi = 3.14;

The let keyword is only used for the declaration part. If we want to initialize or change a value of our variables after the declaration, just assign (equals symbol “=”) the value without using the keyword var before the variable name score = 10;.

With the const keyword declaration and initialization always need to happen together, because a const cannot be changed afterwards.

let firstScore;
firstScore // results in undefined
   
let secondScore;
secondScore = 1000;
secondScore // evaluates 1000
   
let thirdScore = 1200;
thirdScore // 1200
   
let otherVariable = 1600;
let fourthScore = otherVariable;
fourthScore // 1600
   
let fifthScore = 3000;
fifthScore = fifthScore + 1000;
fifthScore // 4000
   
let lastScore = 10 * 9 + 5;
lastScore // 95

const maxScore = 1500;
maxScore // 1500

const maxScore = 1500;
maxScore = 2000 // error you can't change a constant value

Declaring Multiple Variables

We can declare multiple variables on one line separating the names by commas and ending the statement with a semicolon. We can also do declaration and initialization on one line. Start with let keyword and then the variable name with the assignment of value. Continue with a comma and the next variable name with a value assignment. End the series with a semicolon.

Beware of the risk of forgetting a comma between the variables. See our next part on the var keyword and global vs local variables.

// declaration on one line
let firstScore, secondScore;
   
// declaration and initialization on one line
let thirdScore = 4444, fourthScore = 1666;
   
// Multiple lines but still in one statement
let fifthScore = 1111,
    sixthScore = 3333,
    lastScore = 7777;

Declaration With or Without let Keyword

If we assign a value directly to a variable without using the let keyword JavaScript will not complain if you are not using strict mode ES6. What it will do is look for a variable with that name to which it can assign the value. Presuming it could have been declared somewhere before or up the scope chain.

If we are just assigning a new value to an existing variable then this can be what we want. If we wanted a new variable then this can mess things up. We could be changing the value of a var we use somewhere else. This could cause unexpected behavior all over the program.

If the variable is not found up or higher in the scope hierarchy a new variable will be created in the global scope. This new global scoped variable will be assigned the value. Best practice for us is using the let keyword for doing declaration + assignment, else we have to be cautious in what we do.

In a basic coding example you’ll not notice a difference in a development console. Everything still acts as you would expect. Prefer using the let keyword and local scope and ECMAScript 6 strict mode.

score = 500;
let lastScore = 2950;
score // evaluates 500
lastScore //evaluaties 2950

Variable Names JavaScript

We need to consider valid names for variables in JavaScript and good practices.

  • Cannot start with a digit or solely consist of digits
  • Cannot be a JavaScript reserved keyword such as (let, const, var, for, which, etc.). Find the list here.
  • Cannot contain punctuation or special characters besides _ and $
  • The $ is sometimes used for starting variable names in JavaScript (convention)
  • The _ is sometimes used for starting variable names to denote it is private (convention)
  • Good practice and convention are using camel-case, every word inside the variable name starts with a capitalization except the first word. Example : myFirstNameAndLastName
  • Good practice to use descriptive names, especially when they are used in the larger scope. Using a short value such as “i” for a counter in a for loop is common, but using these variables in larger parts can make programs difficult to read. For example use bankAccountNumber instead of bn.

// most commonly encountered
const bankAccountNumber = 12378998989;
let scenario2 = 'the second scenario';
   
// used to denote private variables, that only should be accessed from inside an object
const _myFirstName = 'Mike';
   
// seen this mostly used with jQuery when the variable refers to an object from the DOM
let $startButton = $("#startButton");

Declaration and Initialization

A small recap on declaration vs initialization, the basics for beginners. Before we use a variable, we should declare it. We use the let keyword, a valid variable name and semicolon ; for declaration without initialization. Multiple declarations in one statement are separated by a comma.

let entries;
let message;
let title, description;

We can do declaration and initialization at once by assigning a value right after declaration with the equals sign = followed by the value or an expression that will result in a value.

let lastScore = 1200;
let title = "This is an awesome title";

If we just declare a variable without assigning an initial value, the value of the variable will be undefined.

let entries;
console.log(entries); // undefined

© 2019 Sam Shepards

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://owlcation.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)