Theme images by Storman. Powered by Blogger.

Saturday 18 March 2017

JavaScript : Data types and operation between data.

     

              JavaScript is the language, which is becoming the universal programming language for the web and currently, it is not only popular for front-end but back-end as well.

When starting with JavaScript people generally get confused with JavaScript data types.In this tutorial, I am going to share how JavaScript data type works.

These are the few key points to mention

  • JavaScript is a loosely typed or a dynamic language.
  • You don't have to declare the type of a variable ahead of time, it will get determined automatically while the program is being processed.
Data types

The latest ECMAScript standard defines seven data types: 
Six data types that are primitives, primitives are immutable values (values, which are incapable of being changed): 
  • Boolean
  •  Null
  •  Undefined
  •  Number
  •  String 
  • Symbol (new in ECMAScript 6) 
and Object

See the example

Var test  =  "Mark"; // test is a String
Var test  =  123; // test is a Number
Var test  =  true; // test is a Boolean

        Here you can see, I reassigned variable with different type and based on the given value JavaScript will dynamically identify what will the type of the data.Until this stage, everything is perfectly fine but you start getting into the trouble when JavaScript decides the type of the variable based on how that variable is used.

Let see the example:

        '43' - 3  // 40
3 - '43' //-40
'4' - '6'//-2
'er' - 6 // NaN
6 - 'er' // NaN
53 + 'y'// "53y"
'y' + 53 // "y53"
'4' + '6'// "46"
'43' + 3 // "433"
3 + '43' // "343"
3 + 43 // 46
'6' * 3 // 18
'6' * 'b' //NaN
6 * 'b' //NaN

One way to fix this problem is to be explicit about the variables.check the example


   // previous code

   '43' + 3 // "433"

   // explicit

   var num = "43";

   console.log(parseInt(num, 10) + 3); // 46



In this example, I am using parseInt which is saying to the JS, whatever in the num variable parse that as the integer before performing any operation.This is the one way to get rid of such kind of problem where JavaScript dynamically decides type of data.

Now I feel you understood some basics of the concept, so it's time to give it try.To find more you can check here.
 JavaScript data types and data structures

Happy Learning :-)



0 on: "JavaScript : Data types and operation between data."