0% Complete
0/0 Steps

Participants 0

      JavaScript Data Types

      JavaScript Data Types

      JavaScript variables can hold many data types: numbers, strings, objects and more:

      var length = 16;                               // Number
      var lastName = "Johnson";                      // String
      var x = {firstName:"John", lastName:"Doe"};    // Object

      The Concept of Data Types

      In programming, data types is an important concept.

      To be able to operate on variables, it is important to know something about the type.

      Without data types, a computer cannot safely solve this:

      var x = 16 + "Volvo";

      Does it make any sense to add “Volvo” to sixteen? Will it produce an error or will it produce a result?

      JavaScript will treat the example above as:

      var x = "16" + "Volvo";

      When adding a number and a string, JavaScript will treat the number as a string.

      Example

      var x = 16 + "Volvo";

      Example

      var x = "Volvo" + 16;

      JavaScript evaluates expressions from left to right. Different sequences can produce different results:

      JavaScript:

      var x = 16 + 4 + "Volvo";

      Result:

      20Volvo

      JavaScript:

      var x = "Volvo" + 16 + 4;

      Result:

      Volvo164

      In the first example, JavaScript treats 16 and 4 as numbers, until it reaches “Volvo”.

      In the second example, since the first operand is a string, all operands are treated as strings.


      JavaScript Types are Dynamic.

      JavaScript has dynamic types. This means that the same variable can be used to hold different data types:

      Example

      var x;           // Now x is undefined
      x = 5;           // Now x is a Number
      x = "John";      // Now x is a String

      Welcome to the Digital Strategy Hub

      We are in beta and please email support @ centerfordigitalstrategy.com with any issues or features that would make your experience better.


      We have a feedback call to hear what would be most useful to you:

      Thursday April at 1 ET / 10am PT