Saturday, October 22, 2016

SharePoint Prod Issue Trouble shooting steps By MS By diff Engineers

Rough Steps are drafted here.
Hope i will get some time to fair it


Merge-SPLogFile -Path "C:\FarmMergedLog.log" -Overwrite -StartTime $start - EndTime $end

Merge-SPLogFile -Path "D:\FarmMergedLog1435.log" -Overwrite -StartTime "10/19/2016 14:35:00" - EndTime "10/19/2016 14:40:00"
$start=get-date
Browse the page , produce the error
$end=get-date
Merge-SPLogFile -Path "C:\FarmMergedLog.log" -Overwrite -StartTime $start - EndTime $end



Set-SPLogLevel -TraceSeverity VerboseEx
Clear-SPLogLevel



---
1. Inetmgr, go to the w3wp3.exe , generate memory dumps for by selecting the process.
it will generate memory dumps in c:\users\userid\app\temp\                                                                                       
Install debug diag tool and analyze the memory dumps
SQL Server:

frequen of reindexing and update statistics
blocking
long running queries
deadlocks
CPU
Memory


custom error s need to turn off
httperrors turned off

--
fiddler trace
Net Mon ( Network Monitor)
ipconfig /flushdns

----
load balancer traffic

----
ULS logs
----

http probe check turned on

Steps to collect netsh trace from both endpoints in the test.
1. Open command prompt as administrator on both endpoints in the test
2. Issue the following command to start the network trace on the client machine and server
a. netsh trace start scenario=netconnection fileMode=circular maxsize=2048 tracefile=c:\%computername%.etl capture=yes
3. recreate the issue (open the connection to the server)
4. Once the error occurs issue the following command to stop the network trace endpoints in the test
a. netsh trace stop
5. After the files get created please rename the .cab and .etl files to reflect the machine name where file was collected.
6. Then upload those files to the workspace created for this issue.(please let me know if you need that login information again)


https://support.microsoft.com/en-us/kb/977453

netsh int tcp set global chimney=disabled
netsh int tcp set global rss=disabled
netsh int ip set global taskoffload=disabled
netsh int tcp set global autotuninglevel=disabled

from Raghavendran to Everyone:
netsh int tcp set global congestionprovider=none

 remote visual debugger to debug from the stage / prod machine, if you have the approvals

process monitor, to monitor the changes of Registry values
weblog expert to analyze the sharepoint IIS logs

Tuesday, September 6, 2016

jQuery Key notes

Chapter : JQuery Intro:

What is jQuery?
jQuery is a lightweight, "write less, do more", JavaScript library.

The purpose of jQuery is to make it much easier to use JavaScript on your website.

jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.

jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.

The jQuery library contains the following features:

HTML/DOM manipulation
CSS manipulation
HTML event methods
Effects and animations
AJAX
Utilities
Tip: In addition, jQuery has plugins for almost any task out there.

Chapter : JQuery Get Started

Adding jQuery to Your Web Pages
There are several ways to start using jQuery on your web site. You can:

Download the jQuery library from jQuery.com
Include jQuery from a CDN, like Google
Downloading jQuery
There are two versions of jQuery available for downloading:

Production version - this is for your live website because it has been minified and compressed
Development version - this is for testing and development (uncompressed and readable code)
Both versions can be downloaded from jQuery.com.

The jQuery library is a single JavaScript file, and you reference it with the HTML <script> tag (notice that the <script> tag should be inside the <head> section):

<head>
<script src="jquery-1.12.4.min.js"></script>
</head>
Tip: Place the downloaded file in the same directory as the pages where you wish to use it.
Do you wonder why we do not have type="text/javascript" inside the <script> tag?

This is not required in HTML5. JavaScript is the default scripting language in HTML5 and in all modern browsers!

jQuery CDN
If you don't want to download and host jQuery yourself, you can include it from a CDN (Content Delivery Network).

Both Google and Microsoft host jQuery.

To use jQuery from Google or Microsoft, use one of the following:

Google CDN:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
Try it Yourself »
Microsoft CDN:
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"></script>
</head>
Try it Yourself »
One big advantage of using the hosted jQuery from Google or Microsoft:

Many users already have downloaded jQuery from Google or Microsoft when visiting another site. As a result, it will be loaded from cache when they visit your site, which leads to faster loading time. Also, most CDN's will make sure that once a user requests a file from it, it will be served from the server closest to them, which also leads to faster loading time.

Chapter : JQuery Syntax

With jQuery you select (query) HTML elements and perform "actions" on them.

jQuery Syntax
The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s).

Basic syntax is: $(selector).action()

A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)
Examples:

$(this).hide() - hides the current element.

$("p").hide() - hides all <p> elements.

$(".test").hide() - hides all elements with class="test".

$("#test").hide() - hides the element with id="test".

Are you familiar with CSS selectors?

jQuery uses CSS syntax to select elements. You will learn more about the selector syntax in the next chapter of this tutorial.

The Document Ready Event
You might have noticed that all jQuery methods in our examples, are inside a document ready event:

$(document).ready(function(){

   // jQuery methods go here...

});
This is to prevent any jQuery code from running before the document is finished loading (is ready).

It is good practice to wait for the document to be fully loaded and ready before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section.

Here are some examples of actions that can fail if methods are run before the document is fully loaded:

Trying to hide an element that is not created yet
Trying to get the size of an image that is not loaded yet
Tip: The jQuery team has also created an even shorter method for the document ready event:

$(function(){

   // jQuery methods go here...

});

Chapter: jQuery Selectors
jQuery Selectors
jQuery selectors allow you to select and manipulate HTML element(s).

jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.

All selectors in jQuery start with the dollar sign and parentheses: $().

The element Selector
The jQuery element selector selects elements based on the element name.

You can select all <p> elements on a page like this:

$("p")

The #id Selector
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.

An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

To find an element with a specific id, write a hash character, followed by the id of the HTML element:

$("#test")

The .class Selector
The jQuery class selector finds elements with a specific class.

To find elements with a specific class, write a period character, followed by the name of the class:

$(".test")


More Examples of jQuery Selectors
Syntax            Description    Example
$("*")            Selects all elements    Try it
$(this)            Selects the current HTML element    Try it
$("p.intro")        Selects all <p> elements with class="intro"    Try it
$("p:first")        Selects the first <p> element    Try it
$("ul li:first")    Selects the first <li> element of the first <ul>    Try it
$("ul li:first-child")    Selects the first <li> element of every <ul>    Try it
$("[href]")        Selects all elements with an href attribute    Try it
$("a[target='_blank']")    Selects all <a> elements with a target attribute value equal to "_blank"    Try it
$("a[target!='_blank']")    Selects all <a> elements with a target attribute value NOT equal to "_blank"    Try it
$(":button")        Selects all <button> elements and <input> elements of type="button"    Try it
$("tr:even")        Selects all even <tr> elements    Try it
$("tr:odd")        Selects all odd <tr> elements

jQuery Event Methods

jQuery is tailor-made to respond to events in an HTML page.

What are Events?
All the different visitor's actions that a web page can respond to are called events.

An event represents the precise moment when something happens.

Examples:

moving a mouse over an element
selecting a radio button
clicking on an element
The term "fires/fired" is often used with events. Example: "The keypress event is fired, the moment you press a key".

Here are some common DOM events:

Mouse Events    Keyboard Events    Form Events    Document/Window Events
click        keypress    submit        load
dblclick    keydown        change        resize
mouseenter    keyup        focus        scroll
mouseleave             blur        unload

jQuery Syntax For Event Methods
In jQuery, most DOM events have an equivalent jQuery method.

To assign a click event to all paragraphs on a page, you can do this:

$("p").click();
The next step is to define what should happen when the event fires. You must pass a function to the event:

$("p").click(function(){
  // action goes here!!
});
Commonly Used jQuery Event Methods
$(document).ready()

The $(document).ready() method allows us to execute a function when the document is fully loaded. This event is already explained in the jQuery Syntax chapter.

click()

The click() method attaches an event handler function to an HTML element.

The function is executed when the user clicks on the HTML element.

The following example says: When a click event fires on a <p> element; hide the current <p> element:

dblclick()

The dblclick() method attaches an event handler function to an HTML element.

The function is executed when the user double-clicks on the HTML element:

Example
$("p").dblclick(function(){
    $(this).hide();
})


mouseenter()

The mouseenter() method attaches an event handler function to an HTML element.

The function is executed when the mouse pointer enters the HTML element:

Example
$("#p1").mouseenter(function(){
    alert("You entered p1!");
});

mouseleave()

The mouseleave() method attaches an event handler function to an HTML element.

The function is executed when the mouse pointer leaves the HTML element:

mousedown()

The mousedown() method attaches an event handler function to an HTML element.

The function is executed, when the left, middle or right mouse button is pressed down, while the mouse is over the HTML element:

mouseup()

The mouseup() method attaches an event handler function to an HTML element.

The function is executed, when the left, middle or right mouse button is released, while the mouse is over the HTML element:

hover()

The hover() method takes two functions and is a combination of the mouseenter() and mouseleave() methods.

The first function is executed when the mouse enters the HTML element, and the second function is executed when the mouse leaves the HTML element:

focus()

The focus() method attaches an event handler function to an HTML form field.

The function is executed when the form field gets focus:

blur()

The blur() method attaches an event handler function to an HTML form field.

The function is executed when the form field loses focus:

The on() Method
The on() method attaches one or more event handlers for the selected elements.

Attach a click event to a <p> element:

Chapter: jQuery Hide/Show
jQuery Effects - Hide and Show

Hide, Show, Toggle, Slide, Fade, and Animate. WOW!


Examples
jQuery hide()
Demonstrates a simple jQuery hide() method.

jQuery hide()
Another hide() demonstration. How to hide parts of text.


Syntax:

$(selector).hide(speed,callback);

$(selector).show(speed,callback);
The optional speed parameter specifies the speed of the hiding/showing, and can take the following values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the hide() or show() method completes (you will learn more about callback functions in a later chapter).

The following example demonstrates the speed parameter with hide():

Example
$("button").click(function(){
    $("p").hide(1000);
});


jQuery toggle()
With jQuery, you can toggle between the hide() and show() methods with the toggle() method.

Shown elements are hidden and hidden elements are shown:

Example
$("button").click(function(){
    $("p").toggle();
});

Syntax:

$(selector).toggle(speed,callback);
The optional speed parameter can take the following values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after toggle() completes.

Chapter: jQuery Fade
jQuery Effects - Fading

With jQuery you can fade elements in and out of visibility.

Examples
jQuery fadeIn()
Demonstrates the jQuery fadeIn() method.

jQuery fadeOut()
Demonstrates the jQuery fadeOut() method.

jQuery fadeToggle()
Demonstrates the jQuery fadeToggle() method.

jQuery fadeTo()
Demonstrates the jQuery fadeTo() method

jQuery Fading Methods
With jQuery you can fade an element in and out of visibility.

jQuery has the following fade methods:

fadeIn()
fadeOut()
fadeToggle()
fadeTo()
jQuery fadeIn() Method
The jQuery fadeIn() method is used to fade in a hidden element.

Syntax:

$(selector).fadeIn(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the fading completes.

The following example demonstrates the fadeIn() method with different parameters:

Example
$("button").click(function(){
    $("#div1").fadeIn();
    $("#div2").fadeIn("slow");
    $("#div3").fadeIn(3000);
});

jQuery fadeOut() Method
The jQuery fadeOut() method is used to fade out a visible element.

Syntax:

$(selector).fadeOut(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the fading completes.

The following example demonstrates the fadeOut() method with different parameters:

Example
$("button").click(function(){
    $("#div1").fadeOut();
    $("#div2").fadeOut("slow");
    $("#div3").fadeOut(3000);
});
Try it Yourself »


jQuery fadeToggle() Method
The jQuery fadeToggle() method toggles between the fadeIn() and fadeOut() methods.

If the elements are faded out, fadeToggle() will fade them in.

If the elements are faded in, fadeToggle() will fade them out.

Syntax:

$(selector).fadeToggle(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the fading completes.

The following example demonstrates the fadeToggle() method with different parameters:

jQuery fadeTo() Method
The jQuery fadeTo() method allows fading to a given opacity (value between 0 and 1).

Syntax:

$(selector).fadeTo(speed,opacity,callback);
The required speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.

The required opacity parameter in the fadeTo() method specifies fading to a given opacity (value between 0 and 1).

The optional callback parameter is a function to be executed after the function completes.

The following example demonstrates the fadeTo() method with different parameters:
Chapter: jQuery Slide
jQuery Effects - Sliding

The jQuery slide methods slide elements up and down.


Examples
jQuery slideDown()
Demonstrates the jQuery slideDown() method.

jQuery slideUp()
Demonstrates the jQuery slideUp() method.

jQuery slideToggle()
Demonstrates the jQuery SlideToggle() method.
jQuery Sliding Methods
With jQuery you can create a sliding effect on elements.

jQuery has the following slide methods:

slideDown()
slideUp()
slideToggle()
jQuery slideDown() Method
The jQuery slideDown() method is used to slide down an element.

Syntax:

$(selector).slideDown(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the sliding completes.

jQuery slideUp() Method
The jQuery slideUp() method is used to slide up an element.

Syntax:

$(selector).slideUp(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the sliding completes.

jQuery slideToggle() Method
The jQuery slideToggle() method toggles between the slideDown() and slideUp() methods.

If the elements have been slid down, slideToggle() will slide them up.

If the elements have been slid up, slideToggle() will slide them down.

$(selector).slideToggle(speed,callback);
The optional speed parameter can take the following values: "slow", "fast", milliseconds.

The optional callback parameter is a function to be executed after the sliding completes.

The following example demonstrates the slideToggle() method:

Chapter: jQuery Animate
jQuery Effects - Animation

The jQuery animate() method lets you create custom animations.

jQuery Animations - The animate() Method
The jQuery animate() method is used to create custom animations.

Syntax:

$(selector).animate({params},speed,callback);
The required params parameter defines the CSS properties to be animated.

The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the animation completes.

The following example demonstrates a simple use of the animate() method; it moves a <div> element to the right, until it has reached a left property of 250px:

jQuery animate() - Manipulate Multiple Properties
Notice that multiple properties can be animated at the same time:
Is it possible to manipulate ALL CSS properties with the animate() method?

Yes, almost! However, there is one important thing to remember: all property names must be camel-cased when used with the animate() method: You will need to write paddingLeft instead of padding-left, marginRight instead of margin-right, and so on.

Also, color animation is not included in the core jQuery library.
If you want to animate color, you need to download the Color Animations plugin from jQuery.com.

jQuery animate() - Using Relative Values
It is also possible to define relative values (the value is then relative to the element's current value). This is done by putting += or -= in front of the value:

Example
$("button").click(function(){
    $("div").animate({
        left: '250px',
        height: '+=150px',
        width: '+=150px'
    });
});

jQuery animate() - Using Pre-defined Values
You can even specify a property's animation value as "show", "hide", or "toggle":

Example
$("button").click(function(){
    $("div").animate({
        height: 'toggle'
    });
});

jQuery animate() - Uses Queue Functionality
By default, jQuery comes with queue functionality for animations.

This means that if you write multiple animate() calls after each other, jQuery creates an "internal" queue with these method calls. Then it runs the animate calls ONE by ONE.

So, if you want to perform different animations after each other, we take advantage of the queue functionality:

Example 1
$("button").click(function(){
    var div = $("div");
    div.animate({height: '300px', opacity: '0.4'}, "slow");
    div.animate({width: '300px', opacity: '0.8'}, "slow");
    div.animate({height: '100px', opacity: '0.4'}, "slow");
    div.animate({width: '100px', opacity: '0.8'}, "slow");
});

Chapter: Stop Animations

The jQuery stop() method is used to stop animations or effects before it is finished.

Examples
jQuery stop() sliding
Demonstrates the jQuery stop() method.

jQuery stop() animation (with parameters)
Demonstrates the jQuery stop() method.

jQuery stop() Method
The jQuery stop() method is used to stop an animation or effect before it is finished.

The stop() method works for all jQuery effect functions, including sliding, fading and custom animations.

Syntax:

$(selector).stop(stopAll,goToEnd);
The optional stopAll parameter specifies whether also the animation queue should be cleared or not. Default is false, which means that only the active animation will be stopped, allowing any queued animations to be performed afterwards.

The optional goToEnd parameter specifies whether or not to complete the current animation immediately. Default is false.

So, by default, the stop() method kills the current animation being performed on the selected element.

The following example demonstrates the stop() method, with no parameters:

Example
$("#stop").click(function(){
    $("#panel").stop();
});

Chapter: jQuery Callback
jQuery Callback Functions

jQuery Callback Functions
JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors.

To prevent this, you can create a callback function.

A callback function is executed after the current effect is finished.

Typical syntax: $(selector).hide(speed,callback);

Examples

The example below has a callback parameter that is a function that will be executed after the hide effect is completed:

Example with Callback
$("button").click(function(){
    $("p").hide("slow", function(){
        alert("The paragraph is now hidden");
    });
});

The example below has no callback parameter, and the alert box will be displayed before the hide effect is completed:

Example without Callback
$("button").click(function(){
    $("p").hide(1000);
    alert("The paragraph is now hidden");
});

Chapter: jQuery Chaining
With jQuery, you can chain together actions/methods.

Chaining allows us to run multiple jQuery methods (on the same element) within a single statement.

jQuery Method Chaining
Until now we have been writing jQuery statements one at a time (one after the other).

However, there is a technique called chaining, that allows us to run multiple jQuery commands, one after the other, on the same element(s).

Tip: This way, browsers do not have to find the same element(s) more than once.

To chain an action, you simply append the action to the previous action.

The following example chains together the css(), slideUp(), and slideDown() methods. The "p1" element first changes to red, then it slides up, and then it slides down:

Example
$("#p1").css("color", "red").slideUp(2000).slideDown(2000);

We could also have added more method calls if needed.

Tip: When chaining, the line of code could become quite long. However, jQuery is not very strict on the syntax; you can format it like you want, including line breaks and indentations.

This also works just fine:

Saturday, September 3, 2016

JavaScript Key Notes


A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).

Function Invocation

The code inside the function will execute when "something" invokes (calls) the function:
  • When an event occurs (when a user clicks a button)
  • When it is invoked (called) from JavaScript code
  • Automatically (self invoked)

Function Return

When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":

The () Operator Invokes the Function

Using the example above, toCelsius refers to the function object, and toCelsius() refers to the function result.

Functions Used as Variable Values

Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations.

Real Life Objects, Properties, and Methods

In real life, a car is an object.
A car has properties like weight and color, and methods like start and stop:

Properties
car.name = Fiat
car.model = 500
car.weight = 850kg
car.color = white

Methods()
====
car.start()
car.drive()
car.brake() 
car.stop()

All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different times.

JavaScript Objects

You have already learned that JavaScript variables are containers for data values.
This code assigns a simple value (Fiat) to a variable named car:

Object Properties

The name:values pairs (in JavaScript objects) are called properties.
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Object Methods

Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.

Accessing Object Properties

objectName.propertyName  or objectName["propertyName"]

Accessing Object Methods

objectName.methodName()

A method is actually a function definition stored as a property value.

Do Not Declare Strings, Numbers, and Booleans as Objects!

When a JavaScript variable is declared with the keyword "new", the variable is created as an object:

var x = new String();        // Declares x as a String object
var y = new Number();        // Declares y as a Number object
var z = new Boolean();       // Declares z as a Boolean object  

Avoid String, Number, and Boolean objects. They complicate your code and slow down execution speed


JavaScript Scope

Scope is the set of variables you have access to.

JavaScript Scope
In JavaScript, objects and functions are also variables.

In JavaScript, scope is the set of variables, objects, and functions you have access to.

JavaScript has function scope: The scope changes inside functions.

Local JavaScript Variables
Variables declared within a JavaScript function, become LOCAL to the function.


Local variables have local scope: They can only be accessed within the function.

Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.

Local variables are created when a function starts, and deleted when the function is completed.

Global JavaScript Variables
A variable declared outside a function, becomes GLOBAL.


A global variable has global scope: All scripts and functions on a web page can access it.


The Lifetime of JavaScript Variables

The lifetime of a JavaScript variable starts when it is declared.
Local variables are deleted when the function is completed.
Global variables are deleted when you close the page.

Function Arguments
Function arguments (parameters) work as local variables inside functions.



JavaScript Events


HTML events are "things" that happen to HTML elements.



When JavaScript is used in HTML pages, JavaScript can "react" on these events.



HTML Events

An HTML event can be something the browser does, or something a user does.



Here are some examples of HTML events:


An HTML web page has finished loading
An HTML input field was changed
An HTML button was clicked
Often, when events happen, you may want to do something.

JavaScript lets you execute code when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

With single quotes:

<some-HTML-element some-event='some JavaScript'>
With double quotes:

<some-HTML-element some-event="some JavaScript">


Common HTML Events
Here is a list of some common HTML events:

Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page

What can JavaScript Do?
Event handlers can be used to handle, and verify, user input, user actions, and browser actions:

Things that should be done every time a page loads
Things that should be done when the page is closed
Action that should be performed when a user clicks a button
Content that should be verified when a user inputs data
And more ...
Many different methods can be used to let JavaScript work with events:

HTML event attributes can execute JavaScript code directly
HTML event attributes can call JavaScript functions
You can assign your own event handler functions to HTML elements
You can prevent events from being sent or being handled



JavaScript Strings


JavaScript strings are used for storing and manipulating text.



JavaScript Strings

A JavaScript string simply stores a series of characters like "John Doe".



A string can be any text inside quotes. You can use single or double quotes:



The escape character (\) can also be used to insert other special characters in a string.

This is the list of special characters that can be added to a text string with the backslash sign:
Code Outputs
\' single quote
\" double quote
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed
Breaking Long Code Lines
For best readability, programmers often like to avoid code lines longer than 80 characters.

If a JavaScript statement does not fit on one line, the best place to break it is after an operator:

The \ method is not a ECMAScript (JavaScript) standard.
Some browsers do not allow spaces behind the \ character.

The safest (but a little slower) way to break a long string is to use string addition:

Strings Can be Objects
Normally, JavaScript strings are primitive values, created from literals: var firstName = "John"

But strings can also be defined as objects with the keyword new: var firstName = new String("John")

Don't create strings as objects. It slows down execution speed.
The new keyword complicates the code. This can produce some unexpected results:

When using the == equality operator, equal strings look equal:

When using the === equality operator, equal strings are not equal, because the === operator expects equality in both type and value.

JavaScript String Methods

String Methods and Properties
Primitive values, like "John Doe", cannot have properties or methods (because they are not objects).

But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.

Finding a String in a String
The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string:

The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:

Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found.

JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third ...

Both methods accept a second parameter as the starting position for the search.

Searching for a String in a String
The search() method searches a string for a specified value and returns the position of the match:

Did You Notice?
The two methods, indexOf() and search(), are equal.

They accept the same arguments (parameters), and they return the same value.

The two methods are equal, but the search() method can take much more powerful search values.

You will learn more about powerful search values in the chapter about regular expressions.

Extracting String Parts
There are 3 methods for extracting a part of a string:

slice(start, end)
substring(start, end)
substr(start, length)

The slice() Method
slice() extracts a part of a string and returns the extracted part in a new string.

The method takes 2 parameters: the starting index (position), and the ending index (position).

This example slices out a portion of a string from position 7 to position 13:

If a parameter is negative, the position is counted from the end of the string.

This example slices out a portion of a string from position -12 to position -6:

If you omit the second parameter, the method will slice out the rest of the string:

The substring() Method
substring() is similar to slice().

The difference is that substring() cannot accept negative indexes

The substr() Method
substr() is similar to slice().

The difference is that the second parameter specifies the length of the extracted part.

If the first parameter is negative, the position counts from the end of the string.

The second parameter can not be negative, because it defines the length.

If you omit the second parameter, substr() will slice out the rest of the string.

Replacing String Content
The replace() method replaces a specified value with another value in a string:

The replace() method can also take a regular expression as the search value.

By default, the replace() function replaces only the first match. To replace all matches, use a regular expression with a g flag (for global match):

The replace() method does not change the string it is called on. It returns a new string.

Converting to Upper and Lower Case
A string is converted to upper case with toUpperCase():

The concat() Method
concat() joins two or more strings:

All string methods return a new string. They don't modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only replaced.

Extracting String Characters
There are 2 safe methods for extracting string characters:

charAt(position)
charCodeAt(position)
The charAt() Method
The charAt() method returns the character at a specified index (position) in a string:

The charCodeAt() Method
The charCodeAt() method returns the unicode of the character at a specified index in a string:

Accessing a String as an Array is Unsafe
You might have seen code like this, accessing a string as an array:

This is unsafe and unpredictable:

It does not work in all browsers (not in IE5, IE6, IE7)
It makes strings look like arrays (but they are not)
str[0] = "H" does not give an error (but does not work)
If you want to read a string as an array, convert it to an array first.

Converting a String to an Array
A string can be converted to an array with the split() method:

If the separator is omitted, the returned array will contain the whole string in index [0].

If the separator is "", the returned array will be an array of single characters:




JavaScript Numbers


JavaScript Numbers

JavaScript numbers can be written with, or without decimals:



Extra large or extra small numbers can be written with scientific (exponent) notation:



JavaScript Numbers are Always 64-bit Floating Point

Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc.

JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard. 

This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63:

Value (aka Fraction/Mantissa) Exponent Sign
52 bits (0 - 51) 11 bits (52 - 62) 1 bit (63)

Precision
Integers (numbers without a period or exponent notation) are considered accurate up to 15 digits.
The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate:
To solve the problem above, it helps to multiply and divide:

Hexadecimal
JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x.
Never write a number with a leading zero (like 07).
Some JavaScript versions interpret numbers as octal if they are written with a leading zero.

By default, Javascript displays numbers as base 10 decimals.

But you can use the toString() method to output numbers as base 16 (hex), base 8 (octal), or base 2 (binary).

Infinity
Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number.

Division by 0 (zero) also generates Infinity:
Infinity is a number: typeOf Infinity returns number.

NaN - Not a Number
NaN is a JavaScript reserved word indicating that a number is not a legal number.

Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number):

NaN - Not a Number
NaN is a JavaScript reserved word indicating that a number is not a legal number.

However, if the string contains a numeric value , the result will be a number:

You can use the global JavaScript function isNaN() to find out if a value is a number.

Watch out for NaN. If you use NaN in a mathematical operation, the result will also be NaN:

NaN is a number, and typeof NaN returns number:

Numbers Can be Objects
Normally JavaScript numbers are primitive values created from literals: var x = 123

But numbers can also be defined as objects with the keyword new: var y = new Number(123)

Do not create Number objects. It slows down execution speed.
The new keyword complicates the code. This can produce some unexpected results:

When using the == equality operator, equal numbers looks equal:

When using the === equality operator, equal numbers are not equal, because the === operator expects equality in both type and value.

Or even worse. Objects cannot be compared:

JavaScript objects cannot be compared.



JavaScript Math Object


JavaScript Math Object



The Math object allows you to perform mathematical tasks on numbers.



The Math Object

The Math object allows you to perform mathematical tasks.

The Math object includes several mathematical methods.

One common use of the Math object is to create a random number:

Math has no constructor. No methods have to create a Math object first.

Math.min() and Math.max()
Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments:

Math.round()
Math.round() rounds a number to the nearest integer:

Math.ceil()
Math.ceil() rounds a number up to the nearest integer:

Math.floor()
Math.floor() rounds a number down to the nearest integer:

Math Constants
JavaScript provides 8 mathematical constants that can be accessed with the Math object:

Example
Math.E          // returns Euler's number
Math.PI         // returns PI
Math.SQRT2      // returns the square root of 2
Math.SQRT1_2    // returns the square root of 1/2
Math.LN2        // returns the natural logarithm of 2
Math.LN10       // returns the natural logarithm of 10
Math.LOG2E      // returns base 2 logarithm of E
Math.LOG10E     // returns base 10 logarithm of E

Math Object Methods
Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
atan2(y,x) Returns the arctangent of the quotient of its arguments
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
exp(x) Returns the value of Ex
floor(x) Returns x, rounded downwards to the nearest integer
log(x) Returns the natural logarithm (base E) of x
max(x,y,z,...,n) Returns the number with the highest value
min(x,y,z,...,n) Returns the number with the lowest value
pow(x,y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Rounds x to the nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle


JavaScript Dates


The Date object lets you work with dates (years, months, days, hours, minutes, seconds, and milliseconds)



JavaScript Date Formats

A JavaScript date can be written as a string:


Mon Sep 05 2016 03:38:46 GMT-0400 (Eastern Daylight Time)

or as a number:

1473061126870

Dates written as numbers, specifies the number of milliseconds since January 1, 1970, 00:00:00.

Displaying Dates
In this tutorial we use a script to display dates inside a <p> element with id="demo":

The script above says: assign the value of Date() to the content (innerHTML) of the element with id="demo". 

You will learn how to display a date, in a more readable format, at the bottom of this page.

Creating Date Objects
The Date object lets us work with dates.

A date consists of a year, a month, a day, an hour, a minute, a second, and milliseconds.

Date objects are created with the new Date() constructor.

There are 4 ways of initiating a date:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Using new Date(), creates a new date object with the current date and time:

Valid date strings (date formats) are described in the next chapter.

Using new Date(number), creates a new date object as zero time plus the number.

Zero time is 01 January 1970 00:00:00 UTC. The number is specified in milliseconds:

JavaScript dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC). One day contains 86,400,000 millisecond.

Using new Date(7 numbers), creates a new date object with the specified date and time:

The 7 numbers specify the year, month, day, hour, minute, second, and millisecond, in that order:

JavaScript counts months from 0 to 11. January is 0. December is 11.

Date Methods
When a Date object is created, a number of methods allow you to operate on it.

Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of objects, using either local time or UTC (universal, or GMT) time.

Date methods are covered in a later chapter.

Displaying Dates
When you display a date object in HTML, it is automatically converted to a string, with the toString() method.

The toUTCString() method converts a date to a UTC string (a date display standard).

The toDateString() method converts a date to a more readable format:

Date objects are static. The computer time is ticking, but date objects, once created, are not.

Time Zones
When setting a date, without specifying the time zone, JavaScript will use the browser's time zone.

When getting a date, without specifying the time zone, the result is converted to the browser's time zone.

In other words: If a date/time is created in GMT (Greenwich Mean Time), the date/time will be converted to CDT (Central US Daylight Time) if a user browses from central US.

JavaScript Date Formats


JavaScript Date Input

There are generally 4 types of JavaScript date input formats:



Type Example

ISO Date "2015-03-25" (The International Standard)
Short Date "03/25/2015" or "2015/03/25"
Long Date "Mar 25 2015" or "25 Mar 2015"
Full Date "Wednesday March 25 2015"
JavaScript Date Output
Independent of input format, JavaScript will (by default) output dates in full text string format:

JavaScript ISO Dates
ISO 8601 is the international standard for the representation of dates and times.

The ISO 8601 syntax (YYYY-MM-DD) is also the preferred JavaScript date format:
The computed date will be relative to your time zone.
Depending on your time zone, the result above will vary between March 24 and March 25.

It can be written without specifying the day (YYYY-MM):
The T in the date string, between the date and time, indicates UTC time.

JavaScript Long Dates.
Long dates are most often written with a "MMM DD YYYY" syntax like this:
Month and day can be in any order:

And, month can be written in full (January), or abbreviated (Jan):


JavaScript Date Methods

Date methods let you get and set date values (years, months, days, hours, minutes, seconds, milliseconds)

Date Get Methods
Get methods are used for getting a part of a date. Here are the most common (alphabetically):

Method Description
getDate() Get the day as a number (1-31)
getDay() Get the weekday as a number (0-6)
getFullYear() Get the four digit year (yyyy)
getHours() Get the hour (0-23)
getMilliseconds() Get the milliseconds (0-999)
getMinutes() Get the minutes (0-59)
getMonth() Get the month (0-11)
getSeconds() Get the seconds (0-59)
getTime() Get the time (milliseconds since January 1, 1970)
The getTime() Method
getTime() returns the number of milliseconds since January 1, 1970:

In JavaScript, the first day of the week (0) means "Sunday", even if some countries in the world consider the first day of the week to be "Monday"

You can use an array of names, and getDay() to return the weekday as a name:

Date Set Methods
Set methods are used for setting a part of a date. Here are the most common (alphabetically):

Method Description
setDate() Set the day as a number (1-31)
setFullYear() Set the year (optionally month and day)
setHours() Set the hour (0-23)
setMilliseconds() Set the milliseconds (0-999)
setMinutes() Set the minutes (0-59)
setMonth() Set the month (0-11)
setSeconds() Set the seconds (0-59)
setTime() Set the time (milliseconds since January 1, 1970)
The setFullYear() Method
setFullYear() sets a date object to a specific date. In this example, to January 14, 2020:

Date Input - Parsing Dates
If you have a valid date string, you can use the Date.parse() method to convert it to milliseconds.

Date.parse() returns the number of milliseconds between the date and January 1, 1970:

You can then use the number of milliseconds to convert it to a date object:

Compare Dates
Dates can easily be compared.

The following example compares today's date with January 14, 2100:

UTC Date Methods
UTC date methods are used for working UTC dates (Univeral Time Zone dates):

Method Description
getUTCDate() Same as getDate(), but returns the UTC date
getUTCDay() Same as getDay(), but returns the UTC day
getUTCFullYear() Same as getFullYear(), but returns the UTC year
getUTCHours() Same as getHours(), but returns the UTC hour
getUTCMilliseconds() Same as getMilliseconds(), but returns the UTC milliseconds
getUTCMinutes() Same as getMinutes(), but returns the UTC minutes
getUTCMonth() Same as getMonth(), but returns the UTC month
getUTCSeconds() Same as getSeconds(), but returns the UTC seconds


JavaScript Arrays

JavaScript arrays are used to store multiple values in a single variable.

What is an Array?
An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

var car1 = "Saab";
var car2 = "Volvo";
var car3 = "BMW";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the values by referring to an index number.

Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.

Syntax:

var array-name = [item1, item2, ...];      
Never put a comma after the last element (like "BMW",).
The effect is inconsistent across browsers.

Using the JavaScript Keyword new
The following example also creates an Array, and assigns values to it:

Example
var cars = new Array("Saab", "Volvo", "BMW");
The two examples above do exactly the same. There is no need to use new Array().
For simplicity, readability and execution speed, use the first one (the array literal method).

Access the Elements of an Array
You refer to an array element by referring to the index number.

This statement accesses the value of the first element in cars:

var name = cars[0];
This statement modifies the first element in cars:

cars[0] = "Opel";

[0] is the first element in an array. [1] is the second. Array indexes start with 0.

Access the Full Array
With JavaScript, the full array can be accessed by referring to the array name:

Arrays are Objects
Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.

But, JavaScript arrays are best described as arrays.

Arrays use numbers to access its "elements". In this example, person[0] returns John:

Objects use names to access its "members". In this example, person.firstName returns John:

Object:
var person = {firstName:"John", lastName:"Doe", age:46};

Array Elements Can Be Objects
JavaScript variables can be objects. Arrays are special kinds of objects.

Because of this, you can have variables of different types in the same Array.

You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:

myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
Array Properties and Methods
The real strength of JavaScript arrays are the built-in array properties and methods:

Examples
var x = cars.length;   // The length property returns the number of elements
var y = cars.sort();   // The sort() method sorts arrays
Array methods are covered in the next chapters.

The length Property
The length property of an array returns the length of an array (the number of array elements).

Adding Array Elements
The easiest way to add a new element to an array is using the push method:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon");                // adds a new element (Lemon) to fruits

New element can also be added to an array using the length property:

Adding elements with high indexes can create undefined "holes" in an array:

Looping Array Elements
The best way to loop through an array, is using a "for" loop:

Associative Arrays
Many programming languages support arrays with named indexes.

Arrays with named indexes are called associative arrays (or hashes).

JavaScript does not support arrays with named indexes.

In JavaScript, arrays always use numbered indexes.

WARNING !!
If you use a named index, JavaScript will redefine the array to a standard object.
After that, all array methods and properties will produce incorrect results.
When to Use Arrays. When to use Objects.
JavaScript does not support associative arrays.
You should use objects when you want the element names to be strings (text).
You should use arrays when you want the element names to be numbers.
Avoid new Array()
There is no need to use the JavaScript's built-in array constructor new Array().

Use [] instead.

These two different statements both create a new empty array named points:

var points = new Array();         // Bad
var points = [];                  // Good
These two different statements both create a new array containing 6 numbers:

var points = new Array(40, 100, 1, 5, 25, 10); // Bad
var points = [40, 100, 1, 5, 25, 10];          // Good

The new keyword only complicates the code. It can also produce some unexpected results:

How to Recognize an Array
A common question is: How do I know if a variable is an array?

The problem is that the JavaScript operator typeof returns "object":

The typeof operator returns object because a JavaScript array is an object.

Solution 1:
To solve this problem ECMAScript 5 defines a new method Array.isArray():
The problem with this solution is that ECMAScript 5 is not supported in older browsers.

Solution 2:
To solve this problem you can create your own isArray() function:

The function above always returns true if the argument is an array.

Or more precisely: it returns true if the object prototype contains the word "Array".

Solution 3:
The instanceof operator returns true if an object is created by a given constructor:
var fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits instanceof Array     // returns true