Begin Web Programming with PHP & MySQL

Advertisements



JavaScript Variables

JavaScript is a dynamically typed (loosely typed) language. It means that JavaScript variables can receive different data types over time.

Datatypes

JavaScript data types are:-
  • Numbers, eg. 1, 2.5 etc.
  • Strings e.g. "This is a string".
  • Boolean (true or false) type
  • Object: It is the most important data-type of JavaScript (composite data type).

JavaScript also defines two more data types, null and undefined, each of which defines only a single value. JavaScript does not make a distinction between integer values and floating-point values. All numbers in JavaScript are represented as floating-point values (no distinction between integer and floating point values).

Variables

There are 4 ways to declare JavaScript variables.
  • Using var
  • Using let
  • Using const
  • Do not declare

You need not declare a variable in JavaScript to assign values. Assume variables as containers for storing data.

Examples

var mynum = 10;
let mynum = 10;
mynum = 10;
All the above three methods do the same thing; assigning a value of 10 to the variable "mynum".

Some more examples
var myname = "Ram";
var price = 500.50;
x = 5; y = 10;
var total = x + y;
let name = "Ram", hobby = "bird watching", height = 6;

Scope of Variables

Scope refers to the visibility of variables. The scope of a variable is the region of your program in which it is defined. JavaScript variables have two scopes.
Global Variables: Global variables can be defined anywhere in a JavaScript program.
Local Variables: Local variables are defined inside a function and its scope limited to that function.
Like other programming languages, reserved keywords can not be used as a variable name.

Keywords in JavaScript

abstract boolean break byte
case catch char class
const continue debugger default
delete do double else
enum export extends false
final finally float for
function goto if implements
importininstanceofint
interface long native new
null package private protected
publicreturn short static
super switch synchronized this
throw throws transient true
try typeof var void
volatile while with