Variables in JavaScript-JavaScript tutorials for beginners

by

Posted on 22 March 2017

A variable represents or holds a value, value of a variable can be changed at any time, to understand let us consider a simple example

Recommended Read : Introduction to JavaScript-JavaScript tutorials for beginners

x = 3

x is the name of the variable and the value assign to it is 3, to change the value of x you simply assign a new value to x

x = 2

now x holds the value 2 while the name of the variable stays the same but it represent a different value thats why it is called as a variable because it can vary.

Uses of Variables

Variables offer several advantages such as

  • They can be used in place where the value they represent is unknown.
  • They can save time in writing and updating the script.

Now let us take an simple example, you have to calculate the area of a square which is (side * side) now if you do not use variables, every time you have to update the script and enter new values but if you use variable you just need to change the value of the variable instead of updating the whole script.

Area = side * side

side = 3

Area = 9

side = 4

Area = 16

We just updated the variables value to get the answer, this is how vaiables save your time and make a code an effiecient one.

Variables in JavaScript

Now you know about variables and why we use them, now to use variables in our JavaScript code we need to follow some principles or syntax so lets discuss them

Declaring variables

We use the "var" keyword to declare a variable, var tells a web browser that the text to follow will be the name of the new variable. For example

var x;

var carName;

var _name123

all above variables are javaScript variables,now we will see some important principles which you need to keep in mind while naming a variable.

  • JavaScript variables are case sensitive for example var hello, var HELLO , var Hello and var HeLLo are four different variables.
  •  An important rule to remember is that a variable name must begin with either an underscore( _ ) or with an alphabet, special characters other then underscore are not allowed while name a variable and no spaces are allowed while naming a variable.

_hello (valid)

123hello(invalid)

hello123(valid)

hello_123(valid)

#hello(invalid)

  • Avoid reserve keywords, JavaScript keywords are special words use to perform a special task for instance you used var which is used to declare a variable in javaScript now if you name your variable as var then this will create numerous problems in your script, so better avoid reserved keywords.

Assigning value to a Variable

You can assign a value to your variable using an assignment operator(=), for example

var x = 10; //assignment and declaration

or you can do the same as

var x; //declaration

x = 10; //assignment

Both ways can be used to assign value to your variable

Variable Types

So far you have seen variables holding values of type number, in JavaScript variables can hold value of type number, string, boolean and null.

Unlike other languages such as C, C++, Java Javascript does not force you to declare the type of variable when you define it, JavaScript gives you flexibility in coding but beware it can create problems too.

Number

JavaScript does not require any number to be declared as integer, floating point or any other number type, Instead any number is seen just any other number whether is -7, 10, 2.3456 or anything else.

*Tip : Practise all the given examples directly in your web browser's console, you can open your web browser console by pressing ctrl+shift+i(while in your web browser window)

Let's try some examples for number variables

var x =10;

var y = 2.33;

x + y ; //output 12.33

x – y; //output 7.67

Now you can see in the above example we have produced a floating output

x = -7; // x value changed from 10 to -7

x + y //output -4.67

*Try yourself : Try the division( / ) and multiplication( * ) operations yourself on the variables.

String

String is a collection of characters which represent a certain text, a string may contain letters, words, spaces, numbers and special characters. Strings are enclosed inside " ", for example: "Hello world","123", "123#5%" are all strings.

Storing strings in variables

var x = "Hello World";

var myConfig = "CORE-i7, 8gb RAM , 1TB HDD";

Matching the quotation marks

let us see some more examples

var x = "Hello wolrd'; //Incorrect way string ending with single quote

var y = 'Hello world"; //incorrect way string starting with single quote

var z = 'Hello world'; //correct string starting and ending with single quotes

var a = "Hello world"; //correct string starting and ending with double quotes

Quotation marks are very important while dealing with strings ending and starting quotation marks must match.

Strings are case sensitive, "hello world" and "Hello world" are two different strings, you will see the importance of this while comparing two strings.

Using special characters inside the string

Special characters enable you to add things inside a string that could not be added otherwise for example you can add "tab" inside your string using "\t" for example

<script>
document.write("3*3\tadded a tab");
</script>

please refer part-1 of this series to know more about document.write() function

The above script will produce the output as : 3*3          added a tab

lets try printing a simple string

<script>
document.write("C:\games\ac3");
</script>

The above code will produce output as : C:gamesac3

Now you must be thinking that where all those slashes were gone, the answer is a single backslash is not supported in a string because it used to escape special characters so to solve this problem we use the special code for it which is "\\", now let's try printing the above string again.

<script>
document.write("C:\\games\\ac3");
</script>

The above code will produce output as : C:\games\ac3

Below is the list for all the output characters and their special codes

Output Character Special Code

Backslash( \ ) - \\

Double Quote(") - \"

Single Quote ( ' ) - \'

BackSpace - \b

Newline - \n

Tab - \t

Vertical tab - \v

What if you want to use a " inside your string, the simple way is to use the above code for double quotes inside your string. See the below example

<script>
document.write("He says \"Hello world\"");
</script>

The above script will produce the output as : He says "Hello world"

Boolean

A Boolean is a datatype which holds only two values either true(1) or false(0)

Notice : words true and false do not need to be enclosed in quotes.

You can declare boolean variables in JavaScript as shown below

var iAmAngry = true;

var iAmAngry = false;

var iAmAngry = 0; //same as false

var iAmAngry = 1; //same as true

We will learn more about booleans in the upcoming chapters.

Null

Null means nothing it is not a space not it is a zero, it is imply nothing, if you want to define a variable with null you simply need to assign your variable as shown below

var variableName = null;

Using variables in Script

We have seen a lot about variables in this tutorial, now we are going to see how to use them inside our JavaScript scripts. let's start with an example

<script>
var x = 10;
document.write(x); //calling the variable x
</script>

Guess the output : Run the above script yourself and find the output(but before that make a guess).

let's see another example

<script>
var x = "Let\' make some noise";
document.write(x); //calling the variable x
</script>

The above code will produce the output as : Let's make some noise

Tip : You can use the variables in between the html tags inside the document.write() function

Concatinate Two strings

To concatenate two strings we use the "+" operator it simple combines two or more string together, see below example to know more.

<script>
var x = "Let\' make some noise";
document.write("<span style=\"color:red\">"+x+"</span>"); //calling the variable x
</script>

The above code will produce the output as : Let's make some noise

Do it yourself : Try creating a number variable and concatenate it with a string variable and see the output.

That's it for now, if you have any queries then feel free to comment down below or you can contact us on any of our social media page.

Thank you for reading.

Tweet your queries and feedback to @PsychoCodes or leave a message on our Facebook page. You can also comment your questions below.

Also, don't forget to subscribe to our Newsletter.

If you like this article, then please share it and help us grow.


If You Love this article, You Should Consider:

  • Like us on Facebook
  • Follow us on Instagram
  • Follow us on Twitter
  • Subscribe to our Newsletter.
  • Let us know your suggestions and queries in the comments below.

Thank you for your Love and Support

Share your thoughts

Search
Adverstisement
Adverstisement