JavaScript – Data Types and Variables

JavaScript is a multi-paradigm, dynamic language with types and operators, standard built-in objects, and methods. Its syntax is based on the Java and C languages — many structures from those languages apply to JavaScript as well. JavaScript supports object-oriented programming with object prototypes, instead of classes. JavaScript also supports functional programming — functions are objects, giving functions the capacity to hold executable code and be passed around like any other object.

TYPES

If you are exposed to other languages, you may have seen a language variable in which you need to declare the variable type when you create a new variable. JavaScript, on the other hand, a dynamically typed language. You declare the variables without a type and you can change the values of the time variables you want. JavaScript programs manipulate values, and those values all belong to a type. JavaScript’s types are:

  • Number
  • String
  • Boolean
  • Object
    • Function
    • Array
    • Date
    • RegExp
  • null
  • Undefined
  • Error

JavaScript has a ‘typeof’ operator that you can use to check the type of a value. 

typeof unseenVar 
//> undefined

typeof 3 
//> "number" 

typeof "test" 
//> "string" 

typeof true 
//> "Boolean"

if (typeof x == "number") { alert("x is a number!"); } 

VARIABLES

JavaScript variables are containers for storing data values.

  • var is the most common declarative keyword. It does not have the restrictions that the other two keywords have. This is because it was traditionally the only way to declare a variable in JavaScript. A variable declared with the var keyword is available from the function it is declared in.

An important difference between JavaScript and other languages like Java is that in JavaScript, blocks do not have scope; only functions have a scope. So if a variable is defined using var in a compound statement (for example inside an if control structure), it will be visible to the entire function.

var x = 5;
//> undefined
x;
//> 5

var y = 6;
//> undefined
y;
//> 6

var z = x + y;
//> undefined
z;
//> 11

var person = "John Doe", carName = "Volvo", price = 200;
//> undefined