JavaScript 7

JavaScript 7

Chapter 7 with Examples

Hi everyone, My name is Arinze Calistus the purpose of this blog is to teach you all you need to know about JavaScript.

JavaScript Variables

In programming or even in algebra, we use variables to hold values. In JS, variables are used to store data. The data stored could be a text, a number, or others.

Making use of variables in JS is very easy. Here is how:

var firstName = "John";
var lastName = "Doe";
var age = 30;
// printing values
document.write(firstName + " " + lastName + "<br>");
document.write(age);

As you can expect:

  • The text "John" is stored/assigned to firstName.

  • The text "Doe" is stored/assigned to lastName.

  • The number 30 is stored/assigned to age.

Declaring a Variable

The var statement creates or declares a variable. In the example below, the variable x is declared and is initialized to to the value 21.

var x = 21;
document.write(x); // prints the value of x

We can also declare or create a variable first, then assign a value(initialize) later.

var x; // declares or creates variable x
x = 5; // assigns a value to variable x
document.write(x); // prints the value of x

Declaring Multiple Variables in One Statement

It is possible to declare multiple variables at once, using a single statement. Simply separate the variables with a comma( , ).

var firstName = "John", lastName = "Doe", age =30; //declares three variables at once
// printing values
document.write(firstName + " " + lastName + "<br>");
document.write(age);

The Equal Sign

As you may notice, we used the equal sign to assign values or data to the variables. The equal sign ( = ) is called the assignment operator.

Naming Variables

JS variables should be identified with unique names. These unique names are called identifiers. Identifiers can be as short as single letters like a,b,x,y,z. They could also be descriptive like firstName or lastName.

Rules for Naming Variables

  • A name should start with a letter, an underscore or a dollar sign

  • A name cannot start with a number

  • A name is case-sensitive

  • A name can only contain letters, digits, underscores and dollar signs

  • JavaScript reserved keywords(like var ,function, if, else, etc.) cannot be used as variable names.