JAVASCRIPT

THE BASICS


Types

Values

Variables


I

Types


Numbers

Strings

Booleans

null & undefined

Objects

Types


are

kinds of values

that can be

represented manipulated

in a programming language



JavaScript types 

can be categorized as follows


primitives / objects

&

mutable immutable

primitives / objects


primitives

numberstringbooleannullundefined


objects

any value that does not belong to the primitive type

NumberS

JavaScript has a single number type


there is no distinction between integer values and floating-point values

  all numbers are represented in 64-bit floating-point format

  the largest and smallest numbers that can be represented are
1.7976931348623157e+308
&
5e-324

when a number appears directly in a JavaScript program

it is called a numeric literal

Number literals






Integer literals


base 10

a sequence of digits

base 16

(hexadecimal)
0X or 0x followed by hexadecimal digits 0-9 A-F
base 8
(octal)
0 followed by digits 0-7

15                 //=> 15 in base 10
0xF                //=> 15 in base 16
017                //=> 15 in base 8

Floating-point literals


use traditional syntax for real numbers

or

the exponential notation which

represents the real number multiplied by 10 

to the power of the exponent


0.15    //=> 0.15
.15     //=> 0.15
0.15e+2 //=> 15 (0.15 * (10 * 10))
0.15e-2 //=> 0.0015 (0.15 / (10 * 10))

Arithmetic operations


work with numbers is done using basic arithmetic operators

+ addition

- subtraction

* multiplication

/ division

% modulo (remainder)

&
a set of functions and constants
 for more complex operations

Math.pow(2, 53)          Math.round(.6)           Math.ceil(.6)          Math.floor(.6)
Math.abs(-5) Math.max(x,y,z) Math.min(x,y,z) Math.random()
Math.PI Math.E Math.sqrt(3) Math.pow(3, 1/3)
Math.sin(0) Math.log(10) Math.exp(3) Math.log(100)/Math.LN10 Math.log(512)/Math.LN2

in JavaScript there are no errors

in cases of 


overflow

underflow

or

division by zero

overflow


when the result of a numeric operation is larger

than the largest representable number the result is

Infinity


when a negative value becomes larger than the largest
representable negative number the result is
-Infinity


adding / subtracting / multiplying / dividing

infinite values

by anything else

results in an infinite value

underflow


when the result of a numeric operation is closer to zero 

than the smallest representable number 

thresult is 0


if it occurs from a negative number 

negative zero is returned

15 / 1.8e+308    //=> 0
-15 / 1.8e+308   //=> -0

negative zero value (-0)  

is almost indistinguishable to  positive zero
except when used as a divisor

15/-0 === 15/0   //=> false

division by zero


is not an error

it simply returns Infinity or -Infinity


BUT

there is one exception

zero divided by zero evaluates to NaN

Predefined global variables


Infinity
holds the positive infinity
anything larger than the largest representable number

isFinite()
returns true if its argument is a number other than
NaNInfinity-Infinity

isFinite(10);       //=> true
isFinite(0.1);      //=> true
isFinite(10.1e+7);  //=> true
isFinite(Infinity); //=> false
isFinite(10/0);     //=> false
isFinite(NaN);      //=> false

NaN

holds the not-a-number value


isNaN()
returns true if its argument is NaN 
or a non-numeric value such as a string or an object


isNaN(NaN);   //=> true
isNaN('ten'); //=> true
isNaN({});    //=> true
isNaN(10);    //=> false
isNaN('10');  //=> false
isNaN(0xF);   //=> false

rounding errors


only a

finite number of real numbers can be represented

with the binary floating point format

which means that when working with them this will often be only

an approximation


the values often are very close to the correct value

adequate for almost any purpose


0.2 + 0.1                           //=> 0.30000000000000004
((0.2 * 100) + (0.1 * 100)) / 100   //=> 0.3




Strings

Strings


are JavaScript’s type for representing text


a string is an immutable ordered sequence of 16-bit values

which typically represents a Unicode character


  the length of a string is the number of 16-bit values it contains

  

empty string

is the string with the 

length equal to 0


  there is no special type that represents a single element of a string

String Literals


  to represent a string literally simply enclose the characters of the string

within a matched pair of single or double quotes (' or ")



Escape sequences


the backslash character (\) combined with the character that follows

represents a character that is otherwise not represented in the string


\0  — the NUL character (\u0000)    \b  — backspace (\u0008)
\t — horizontal tab (\u0009)    \n — newline (\u000A)
\v — vertical tab (\u000B)    \f  — form feed (\u000C)
\r — carriage return (\u000D)    \"  — double quote (\u0022)
\' — apostrophe or single quote (\u0027)    \\  — backslash (\u005C)
\xXX — character code specified by two hexadecimal digits XX
\uXXXX  — character code specified by four hexadecimal digits XXXX

if  the \ character precedes any character
other than the ones mentioned above
the backslash is simply ignored

Working with strings


concatenation

using the + operator

joins two strings

appending the second to the first


length property

used to determine the length of a string

var str = 'JavaScript';
str.length //=> 10

invoking methods methods on strings

var str = 'JavaScript';
str.charAt(0);          //=> "J"
str.substring(5,10);    //=> "cript"
str.split('');          //=> ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"]
str.toLowerCase();      //=> "javascript"
str.replace('J', 'j');  //=> "javaScript"

strings


are immutable


always remember that 

some methods will return a new string

and they do not modify the string on which they are invoked


var str = 'JavaScript';
var newStr = str.toUpperCase();

console.log(str);    //=> "JavaScript"
console.log(newStr); //=> "JAVASCRIPT"

Booleans

Booleans


  there are only two values possible for this type

true / false



they are usually the result of comparisons

'JavaScript' === 15 //=> false
15 === 15           //=> true
'15' != 15          //=> false

any value can be converted to a boolean value

undefined / null / 0 / -0 / NaN / "" (empty string)

convert to false & are called

falsy values


all other values convert to true & are called

truthy values


toString() method
can be invoked on booleans to convert them

to "true" or "false" strings

Boolean operators


&& (AND)

evaluates to a truthy value if and only if both of its operands are truthy

otherwise it evaluates to a falsy value

10 < 15 && 15 > 10 //=> true

| | (OR)

evaluates to a truthy value if either one (or both) of its operands is truthy

and evaluates to a falsy value if both operands are falsy

15 < 10 || 15 > 10 //=> true 

! (NOT)

evaluates to true if its operand is falsy and evaluates to false if its operand is truthy

15 < 10 === !true //=> true

Null

&

undefined

Null


is a keyword that evaluates to a special value

used to indicate the absence of a value



it is typically regarded as the 

sole member of its own type

&

  it can be used to indicate no value for

numbers, strings or objects

UNDEFINED

  is a predefined global variable

which also indicates the absence of value


BUT

a deeper kind of absence



it is the value

of variable that have not been initialized

of object property or array element that does not exist

returned by functions that have no return value

of function parameters for which no argument is supplied

undefined is system-level unexpected 

error-like absence of value


null is program-level expected

normal absence of value

despite the differences null & undefined both

indicate the absence of value

can be used interchangeably

are falsy values

behave like false when a boolean value is required



none of them have got any properties or methods

using . or [] notation

to access a property or method

of these values causes a TypeError

var person = { 
  name: 'John Doe',
  children: null
};

person.children.length;  //=> TypeError: Cannot read property 'length' of null
obj.children[0]          //=> TypeError: Cannot read property '0' of null

Objects

Object types


are

any values that does not belong to the primitive types


an ordinary object

is a collection of properties

where each property has a name or key 

&

a value


var obj = {
  keyOne: 'valueOne',
  keyTwo: 'valuerTwo',
  keyN: 'valueN'
};

Object Literals



objects are useful for collecting & organizing data


the most common things to do with objects are

create 

&

 set / query / delete / test / enumerate
their properties

special kind of objects



arrays

functions

global object

wrapper objects 

ARRAYS


are
ordered collection of numbered values

JavaScript includes a special syntax for working with arrays
 and arrays have some special behavior that distinguishes them from ordinary objects
 

 


var arr = [1000, 'string', function () {}, { name: 'JavaScript'}, [1, 2]];

FUNCTIONs


a function is

an object that has executable code associated with it



 

  

it may be invoked to run that executable code and return a computed value

JavaScript defines a special language syntax for working with them

The Global Object


is a regular object that serves a very important purpose

its properties are the globally defined symbols 

that are available to a JavaScript program


when the JavaScript interpreter starts it creates a new 

global object and gives it an initial set of properties that define

global properties like undefined, Infinity, NaN

global functions like isNaN(), parseInt(), eval()

constructor functions like Date(), RegExp(), String(), Object(),  Array()

global objects like Math and JSON


besides all predefined global values

global object also holds program-defined globals

WRAPPER objects


strings / numbers / booleans

are not objects

so why do they have properties?

because whenever you try to refer to a property

JavaScript

converts the string value to an object 

as if by calling 

new String() / new Number() / new Boolean()


this object inherits all methods available on

strings, numbers or booleans

and is used to resolve the property reference


once the property has been resolved

the newly created object is discarded

in conclusion


wrapper objects

are

temporary objects 

created when you access 

a property of a 

string / number / boolean


it is possible to explicitly create wrapper objects

by invoking the String(), Number(), or Boolean() constructors

new String('JavaScript');       //=> String {0: "J", 1: "a", 2: "v", 3: "a", 4: "S", 5: "c", 6: "r", 
     //           7: "i", 8: "p", 9: "t", length: 10}

JavaScript converts wrapper objects into the wrapped

primitive value as necessary

var s = "test", n = 1, b = true; //=> a string, number, and boolean value
var S = new String(s);           //=> a string object
var N = new Number(n);           //=> a number object
var B = new Boolean(b);          //=> a boolean object 

the objects usually

but not always, behave just like the values


== equality operator treats a value and its wrapper object as equal

=== strict equality operator distinguishes them


the typeof operator will also show the difference

between a primitive value and its wrapper objects

Made with Slides.com