Posted in All Posts, Semester 2

JavaScript Basics – Variables & Arrays

Variables in JS

Variable is a storage unit that has a value attached to it.
In JS variables are declared using the var keyword by giving the name of the variable.
Below is an example for the same –

var temp;

In JS, you need not specify the type of the variable, it will have the type of the value stored in it.

Rules for naming variables –

  • Name starts with alphabet or an underscore.
  • Except the dollar sign ($) and underscore (_), no special characters are allowed.
  • Numbers are allowed.
  • Variables are case sensitive.

Initializing a variable

A variable can be initialized in the following two ways –

Arrays in JS

The main difference between an array and variable is that an array can store multiple values at one time.
In JS, an array is declared in the following way –
var myarray = new Array();
Here new Array() is a registered method in JS that indicates that a new array called myarray is created.

Three ways to create an array

Initialize an array

Suppose you don’t want to initialize an array at time of declaration.
Here’s the way to initialize an array after its declaration.

Variables and Arrays Example

Try It Yourself

Stay connected for our series of JavaScript Basics.

We hope that you found this article to be helpful.
Please share your thoughts in the Comments Section.

If you liked this article, then please like our Facebook page.

Suggested Reading

Comment your thoughts

This site uses Akismet to reduce spam. Learn how your comment data is processed.