Next Previous

JS Variables

What are variables?

Variables are just containers that store data values.

Just like a bag with some fruits.

They can be declared using the following reserved keywords:

  • var
  • const
  • let

Skeleton of a JavaScript variable

var title = 'JavaScript Tutorial';

Use varkeyword to create a variable.

The title is the variable name that could be anything, such as i, first_name, lastName, etc.

The equals = operator assigns a value on the right, to the variable on the left, and it’s called an assignment operator.

Finally, 'JavaScript Tutorial' is an actual data value which is a String data type as it’s wrapped within single quotes.

In a nutshell, the title variable stores the string value ‘JavaScript Tutorial’

JavaScript Variable Rules

👉 Variable names can be a short name (a, b) or descriptive (title, first_name).

👉 They can be a combination of letters, numbers, underscores (_) & dollar signs ($).

👉 The first letter of a variable name can’t start with numbers.

👉 They are case sensitive and the title and Title are NOT the same variables.

👉 No reserver keywords can be used as a variable name such as var etc.

JavaScript Variable Declaration

var title = 'JavaScript Tutorial' ;

The title variable declared with an initial value ‘JavaScript Tutorial’.

var author;  // var author = undefined

The author variable declared without initial value will have a value of undefined.

Re-assign JavaScript Variable

Re-assign a new value to the variable title without var keyword after initialization.

var title = 'JavaScript Tutorial' ;
title = 'The Best JavaScript Tutorial';

The value of the title will be preserved when creating a same variable without an initial value after it’s initialized.

var title = 'JavaScript Tutorial' ;
var title; // 'JavaScript Tutorial'

JavaScript Data Types

JavaScript variables can store many types such as number, string, etc.

The value of string type is just a text wrapped with single or double-quotes such as ‘Front-end Developer’, or ‘HTML5 Tutorial’.

The value of number type is a digit without quotes such as 100, 8.14, etc.

var title = 'JavaScript Tutorials'; // String type
var students = 1000; // Number type

A value of Number type inside quotes considered String type as well.

var students = '1000'; // String type NOT Number type

Next Previous