Quantcast
Channel: Hacking Nomad
Viewing all articles
Browse latest Browse all 12

JavaScript Variable Declaration and Initialization

$
0
0

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 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 a boxes or a 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 wrong, since the value is not really inside that ‘box’. Two or more variables can point to that same value in memory, so not just an identical value or copy. It’s probably best to presume that a variable points to a certain value and will hand us the value when we ask for it.

Creating A Variable

Declaring a variable without initialization

We start with the JavaScript syntax for creating variables. We use the “var” keyword, short for variable. 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: var score;. We can still assign the value later on.

Variable declaration and initialize it

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: var score = 5;

The var 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;.

var firstScore;
firstScore // results in undefined

var secondScore;
secondScore = 1000;
secondScore // evaluates 1000

var thirdScore = 1200;
thirdScore // 1200

var otherVariable = 1600;
var fourthScore = otherVariable;
fourthScore // 1600

var fifthScore = 3000;
fifthScore = fifthScore + 1000;
fifthScore // 4000

var lastScore = 10 * 9 + 5;
lastScore // 95

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 var keyword and then the variable name with assignment of value. Continue with a comma and the next variable name with 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
var firstScore, secondScore;

// declaration and initialization on one line
var thirdScore = 4444, fourthScore = 1666;

// Multiple lines but still in one statement
var fifthScore = 1111,
    sixthScore = 3333,
    lastScore = 7777;

Declaration with or without var keyword

If we assign a value directly to a variable without using the var keyword JavaScript will not complain. 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 a value 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 var 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 var keyword and local scope as much as possible.

score = 500;
var 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 (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 is using camel-case (for object-oriented programming), 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
var bankAccountNumber = 12378998989;
var scenario2 = 'the second scenario';

// used to denote private variables, that only should be accessed from inside an object
var _myFirstName = 'Mike';

// seen this mostly used with jQuery when the variable refers to an object from the DOM
var $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 var keyword, a valid variable name and semicolon for declaration without initialization.

var entries;
var message;
var 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.

var lastScore = 1200;
var 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.

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


Viewing all articles
Browse latest Browse all 12

Latest Images

Trending Articles



Latest Images