Tutorials On Declaring And Functioning Of Variable In JavaScript

imgJune 7, 2017
 

In our first tutorial we have learnt how to write a program in JavaScript. Next we need to discover how to create variables and then fill them with different values and then use functions for finding out the type of data which is there in the variable, convert right between various data types and then manipulate the various data present in the variables.

Understanding Variables

Variables are usually representative names present in the program. Take the example like X may certainly stand for any unknown value in algebra, variables which are used in programming for representing something else. Variables are like containers which usually contain data. You can give names to containers and later change the data in a variable right by using the name.

Without variables, each and every computer program certainly should have one purpose. In any one-line program, there is no use of variables:

alert(3 + 7);

The purpose is certainly to add together the numbers 3 and 7 and then to print the result in the popup window of a browser. There is not much use of the program unless one needs to recall the sum of 3 and 7 on daily basis. With variables, there can be a general purpose program which can add any two numbers together and then print out the result like:

var firstNumber = 3;
var secondNumber = 7;
var total = Number(firstNumber) + Number(secondNumber);
alert (total);

The program can also be modified by expanding the program asking the user for two numbers and then adding them together like:

var firstNumber = prompt("Enter the first number");
var secondNumber = prompt("Enter the second number");
var total = Number(firstNumber) + Number(secondNumber);
alert (total);

The Document Will Read As Follows:

<html>
<head></head>
<body>
<script>
var firstNumber = prompt("Enter the first number");
var secondNumber = prompt("Enter the second number");
var total = Number(firstNumber) +
Number(secondNumber);
alert (total);
</script>
</body>
</html>

How To Declare A Variable

Declaring a variable is certainly a technical term which can be used to describe the process of creating a variable in the program. This may also be called initialization. In other words, creating, declaring or initializing a variable usually refers to the same thing. There are two ways to create variables in JavaScript which are as follows:

  • With the use of var keyword: var myName; a variable created with var keyword will surely have an initial value of undefined unless one give a value when created such as varmyName= “ Tara”;
  • Without the use of var keyword: myName = “Tara”; When a variable is created without a var keyword then it becomes a global variable.

Just note the quotes around the value in the above examples. These quotes will indicate that value will be treated as text not as number, a JavaScript keyword or another variable.

Idea About The Global And Local Scope

How and where one declares a variable, determines how and where the program can make use of that variable. This is termed as variable scope. JavaScript usually have two types of scope:

  • Global variables which can be used anywhere inside the program
  • Local (function) variable are again variables which can be created right inside of protected program well within the program termed as function.

Local variables are usually preferable to using globals as limiting scope of the variables will reduce the chance of accidentally overwriting the value of a variable with another variable of the same name. Using globals can create problems in the program making it difficult to track it down and fix. It is advisable never to create variables without the use of var keyword. Global variable can also be created with the use of a var keyword and can be done in that way.

Creating Constants With The Use Of Const Keyword

In some occasion, the program may have need for variables which cannot be changed. In those cases, one can declare the variable with the use of const keyword. For example:

const heightOfTheEmpireStateBuilding = 1454;
const speedOfLight = 299792458;
const numberOfProblems = 99;
const meanNumberofBooksReadIn2014 = 12;

In most cases, constants usually abide the same rules like other variables but once one can create a constant then its value cannot be changed right during the lifetime which will last during lifetime.

Working With Data Types

Data type is usually the kind of data which the variable can hold and what operations certainly can be done with the value of the variable. Take the simple example, number 10 which is used in a sentence is usually different than the number 10 which is used in the equation. With the data types, JavaScript can distinguish between the values which are meant to be words and the values which are treated as mathematical expressions. JavaScript is a loosely typed language by which you do not need to tell JavaScript or know whether the variable one is holding contains a word, paragraph or number or different data types.

Loosely typed surely does not mean that JavaScript will not distinguish numbers and words. JavaScript is friendly and handles the work of figuring out the type of data which is stored in the variables behind the scenes. JavaScript usually recognizes five basic or primitive types of data.

Number Data Type

Usually numbers in JavaScript are stored as 64-bit or floating point values. In simple English language, it will mean that numbers can range from 5e-324 which means -5 followed by 324 zeroes to 1.7976931348623157e+30. Any number may have decimal points or not. Very unlike programming language, JavaScript does not separate data types for integers ( positive or negative numbers without the fractional part) or floating points ( decimals).

Number Functions

JavaScript includes a proper built-in Number function for converting values right to numbers. To use the Number function, just insert the value( or a variable holding the value) which one want to convert right to the number between parentheses right after the Number Function. Usually Number function surely produces four kinds of output:

  • Numbers which are formatted as text strings are usually converted right to numbers which can be used for calculations like:
Number("42") // returns the number 42

parseInt() function

In case of JavaScript, all numbers are usually floating point numbers. One can use the parseInt() function to tell JavaScript to certainly consider the nonfractional part of the number( the integer) which discards everything right after the decimal point.

To JavaScript, all numbers are actually floating point numbers. However, you can use the parseInt() function to tell JavaScript to consider only the non-fractional part of the number (the integer), discarding everything after the decimal point.

parseInt (100.33);?// will return 100 parseFloat(): one can use parseFloat() to tell JavaScript for treating number as a float. Or, one can even use it for converting a string to a number. Take the example:

parseFloat("10"); // returns 10
parseFloat(100.00); //returns 100.00
parseFloat("10"); //returns 10

String functions

JavaScript will include various helpful functions used for working with and converting strings. Here is the list of frequently used built-in string functions:

  • charAt () will produce the character right at a specified position. Always remember that counting the characters usually start with (0).
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var myString = 'JavaScript is Fun!';
document.getElementById("demo").innerHTML = myString.charAt(4);
</script>
</body>
</html>
  • concat () will combine one or more strings and then return the incorporated string.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var myString = 'JavaScript is Fun!';
document.getElementById("demo").innerHTML = myString.concat('<br> Webskitters');
</script>
</body>
</html>
  • indexOf () will search and then return the position right at the first occurrence of the right searched character or substring right within the string.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var myString = 'JavaScript is Fun!';
document.getElementById("demo").innerHTML = myString.indexOf('Fun');</script>
</body>
</html>
  • split() will splits strings into various array of substrings:
<script>
var myString = 'JavaScript is Fun!';
document.getElementById("demo").innerHTML = myString.split('i');
</script>
  • substr() will extract a portion of the string right from the “start” through a specified length:
<script>
var myString = 'JavaScript is Fun!';
document.getElementById("demo").innerHTML = myString.substr(4,6);
</script>
  • substring() will extract characters within a string between two particular specified positions:
<script>
var myString = 'JavaScript is Fun!';
document.getElementById("demo").innerHTML = myString.substring(4,10);
</script>
  • toLowerCase() will give you string with all the characters converted to lowercase:
<script>
var myString = 'JavaScript is Fun!';
document.getElementById("demo").innerHTML = myString.toLowerCase();
</script>
  • toUpperCase() will give you the string with all of the characters which are converted to uppercase:
<script>
var myString = 'JavaScript is Fun!';
document.getElementById("demo").innerHTML = myString.toUpperCase();
</script>

Boolean Data Type

Boolean data type or Boolean variables store one of the two possible values which can be either true or false. This term Boolean is named after George Boole (1815- 1864) creating an algebraic system of logic. Since it is the name of the person, so it is written with initial capital letter.

<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var isItGreater = Boolean (20 > 2);
document.getElementById("demo").innerHTML = isItGreater; </script>
</body>
</html>

NaN data type usually stands for Not a Number. It is usually the result one can get when they try to do math with a string or when calculation fails or it cannot be done. Take the example like it is impossible to calculate the square root of a negative number.

<script>
var areTheySame = Boolean ("tiger" === "tiger");
document.getElementById("demo").innerHTML = areTheySame;
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *