JAVASCRIPT

THE BASICS


Types

Values

Variables


III

Type
conversion

JavaScript

is very flexible about the types of values it requires


when

JavaScript

expects a certain value
no matter the value supplied
it will try to convert it as needed



type conversions summary

Value Converted to
String Number Boolean Object
undefined "undefined" NaN false throws TypeError
null "null" 0 false throws TypeError
true "true" 1   new Boolean(true)
false "false" 0   new Boolean(false)
"" (empty string)   0 false new String("")
"1.2" (nonempty, numeric)   1.2 true new String("1.2")
"one" (nonempty, non-numeric)   NaN true new String("one")
0 "0"   false new Number(0)
-0 "0"   false new Number(-0)
NaN "NaN"   false new Number(NaN)
Infinity "Infinity"   true new Number(Infinity)
-Infinity "-Infinity"   true new Number(-Infinity)
1 (finite, non-zero) "1"   true new Number(1)
{} (any object) read more read more true  
[] (empty array) "" 0 true  
[1] (one numeric element) "9" 9 true  
['str'] (any other array) use join() method NaN true  
function(){} (any function) read more NaN true  

Primitive to primitive

conversions



undefined / null / 0 / -0 / NaN / "" (empty string)
all convert to falsy values

all other primitives values convert to truthy values
1 + ' string'         //=> "1 string"    -> Number becomes a string
"1" / "2"             //=> 0.5           -> both strings become numbers
1 / "two"             //=> NaN           -> string can't be converted to number
NaN + ' string'       //=> "NaN string"  -> NaN becomes a string
true + 1 + null       //=> 2             -> true becomes 1, null becomes 0 (1 + 1 + 0 = 2)
1 / false             //=> Infinity      -> false becomes 0 (1 / 0 = Infinity)
['Java'] + 'Script'   //=> "JavaScript"  -> array values become a string

PRIMITIVE TO OBJECT

CONVERSIONs


primitives convert to their wrapper object

as if by calling the 

String()Number()Boolean()

constructor functions


BUT

null & undefined are an exception
they raise a TypeError if used where an object is expected

OBJECT TO PRIMITIVE

CONVERSIONs


object-to-boolean conversions are trivial
all objects convert to true


even

wrapper objects

var obj = new Boolean(false);

if (obj) {
  console.log(true);   //=> true -> new Boolean(false) is an object & converts to true
} else {
  console.log(false);
}

BUT

object-to-string & object-to-number conversions

are more complicated



objects

inherit two different methods

that perform these conversions


toString()

returns a string representation of the object


valueOf()

converts an object to a primitive value

that represents the object

toString() method

by default does not return a very interesting value
var obj = {
  title: 'JavaScript - The Basics'
};

obj.toString();   //=> "[object Object]"

other classes define more specific versions of this method

[1, 2, 3, 4].toString();       //=> "1,2,3,4"

var fn = function (param) { 
  return param; 
};
fn.toString();                 //=> "function (param) { return param; }"

var time = new Date(); 
time.toString();          //=> "Tue Aug 12 2014 21:07:31 GMT+0300 (GTB Daylight Time)"

valueOf() method


a less well-defined conversion function

because objects are compound values
cannot really be represented by a single primitive value
by default the valueOf() method simply returns the object itself

var obj = {
  title: 'JavaScript - The Basics'
};

obj.valueOf();            //=> Object {title: "JavaScript - The Basics"}
[1, 2, 3, 4].valueOf();   //=> [1, 2, 3, 4]


Date class defines a specific valueOf() method
(new Date()).valueOf();   //=> 1407867809210 -> milliseconds since January 1, 1970

Conversions & equality


because JavaScript can convert values flexibly
its == equality operator is also flexible with its notion of equality
all of the following comparisons are true

null == undefined   //=> true
"0"  == 0           //=> true -> string becomes a number (0 == 0)
 0   == false       //=> true -> boolean becomes a number (0 == 0)
"0"  == false       //=> true -> both 0 & false become numbers (0 == 0)

BUT

undefined == false  //=> false -> == operator never attempts to
                    //            convert its operands to booleans    

converting of one value to another
does not imply equality of those values

Explicit conversions


although many type conversions are performed automatically
sometimes explicit conversions are needed

the simplest way to do it is by invoking the functions
Number() / String() / Boolean() and Object()
without the new operator

Number("1");   // => 1
String(true);  // => "true"
Boolean({});   // => true
Object(1);     // => Number {} -> new Number(1)
Object();      // => Object {} -> an empty object

some operators perform implicit type conversions

&

are sometimes used for this purposes

1 + ""    //=> "1"   -> + converts the second operator to string if one operator is a string
+"1"      //=> 1     -> unary + operator converts its operand to number
!!""      //=> false -> unary ! operator converts its operand to a boolean and negates it

JavaScript 


has specialized functions
which provide more precise control over
number-to-string and string-to-number conversions

toString() 

defined by the Number class
converts a number to a string
accepts optional argument as radix for the conversion

var n = 15;

n.toString(2);    //=> "1111"
n.toString(8);    //=> "17"
n.toString(16);   //=> "f"


toFixed()

converts a number to a string
with a specified number of digits after the decimal point

var n = 12345.6789;

n.toFixed(0);    //=> "12345"
n.toFixed(2);    //=> "12345.68"
n.toFixed(7);    //=> "12345.6789000" 

toExponential()

converts a number to a string using exponential notation
with one digit before the 
decimal point & a specified number of digits
after the decimal point

var n = 12345.6789;

n.toExponential(0);   //=> "1e+4"
n.toExponential(2);   //=> "1.23e+4"
n.toExponential(7);   //=> "1.2345679e+4"


toPrecision()

converts a number to a string
with the number of significant digits you specify

var n = 12345.6789;

n.toPrecision(1);     //=> "1e+4"
n.toPrecision(7);     //=> "12345.68"
n.toPrecision(21);    //=> "12345.6789000000007945"

parseFloat()

parses integers and floating-point numbers

 parseFloat("1px");    //=> 1
 parseFloat(".1");     //=> 0.1
 parseFloat("$1.0");   //=> NaN

parseInt()

parses only integers
if string begins with "0x" / "0X" interprets number as hexadecimal 

parseInt("1px");   // => 1
parseInt("1.0");   // => 1
parseInt("0.1");   // => 0
parseInt(".1");    // => NaN -> integers can't start with "."
parseInt("0xf");   // => 15
parseInt("0XF");   // => 15
parseInt() accepts optional second argument as radix

parseInt("1111", 2);  // => 15
parseInt("f", 16);    // => 15
parseInt("017", 8);   // => 15

both parseInt() & parseFloat() functions 

skip leading whitespace 

&
 parse as many numeric characters as they can
ignoring anything else that follows 


if the first non-space character 
is not part of a valid numeric literal
the returned value is 
NaN
Made with Slides.com