- JavaScript Where to
JavaScript can be placed in the <body> and the <head> sections of an HTML page.
- importing external js
<script src="myScript.js"></script>
- JavaScript Display Possibilities
JavaScript can "display" data in different ways:
- Writing into an alert box, using window.alert().
- Writing into the HTML output using document.write().Using document.write() after an HTML document is fully loaded, will delete all existing HTML:
- Writing into an HTML element, using innerHTML.
- Writing into the browser console, using console.log().In your browser, you can use the console.log() method to display data.
- JavaScript Comments
Not all JavaScript statements are "executed".
Code after double slashes // or between /* and */ is treated as a comment.
Comments are ignored, and will not be executed:
- Re-Declaring JavaScript Variables
If you re-declare a JavaScript variable, it will not lose its value.
The variable carName will still have the value "Volvo" after the execution of these statements:
Example
var carName = "Volvo";
var carName;
- JavaScript Type Operators
| Operator | Description |
|---|---|
| typeof | Returns the type of a variable |
| instanceof | Returns true if an object is an instance of an object type |
- When adding a number and a string, JavaScript will treat the number as a string.
var x = 16 + "Volvo";= 16volvo
var x = 16 + 4 + "Volvo";= 20volvo
var x = "Volvo" + 16 + 4;=volvo164
- JavaScript Has Dynamic Types
JavaScript has dynamic types. This means that the same variable can be used as different type
var x; // Now x is undefinedvar x = 5; // Now x is a Numbervar x = "John"; // Now x is a String// replace previous value
- Null
In JavaScript null is "nothing". It is supposed to be something that doesn't exist.
Unfortunately, in JavaScript, the data type of null is an object.
- You can consider it a bug in JavaScript that typeof null is an object. It should be null.
You can empty an object by setting it to null:
- You can consider it a bug in JavaScript that typeof null is an object. It should be null.
Example
var person = null;
var person = null;
- Difference Between Undefined and Null
typeof undefined // undefinedtypeof null // objectnull === undefined // falsenull == undefined // true
- triple = vs double =
The == operator will compare for equality after doing any necessary type conversions. The ===operator will not do the conversion, so if two values are not the same type === will simply return false
example
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
' \t\r\n ' == 0 // true
- triple = vs double =
The
== operator will compare for equality after doing any necessary type conversions. The ===operator will not do the conversion, so if two values are not the same type === will simply return falseexample '' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
' \t\r\n ' == 0 // true
- JavaScript Objects
Objects are variables too. But objects can contain many values.
var car = {type:"Fiat", model:"500", color:"white"};
- Accessing Object Properties
objectName.propertyName
- creating and Accessing Object functions
<script>
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
accsessing ->document.getElementById("demo").innerHTML = person.fullName();
- note ->If you access the fullName method, without (), it will return the function definition
name = person.fullName; ie name=function () { return this.firstName + " " + this.lastName; }
- Automatically Global
If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable. like initialize a variable in a function without declaring it
ex--
This code example will declare a global variable carName, even if the value is assigned inside a function.
document.getElementById("demo").innerHTML = "I can display " + carName;
function myFunction() {
carName = "Volvo";
}
- creating and Accessing Object functions
<script>
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
accsessing ->document.getElementById("demo").innerHTML = person.fullName();
- note ->If you access the fullName method, without (), it will return the function definition
name = person.fullName; ie name=function () { return this.firstName + " " + this.lastName; }
- Automatically Global
If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable. like initialize a variable in a function without declaring it
ex--
This code example will declare a global variable carName, even if the value is assigned inside a function.
document.getElementById("demo").innerHTML = "I can display " + carName;
function myFunction() {
carName = "Volvo";
}
- 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")
var x = "John";
var y = new String("John");
// typeof x will return string// typeof y will return object
Don't create strings as objects. It slows down execution speed.
The new keyword complicates the code. This can produce some unexpected results:
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")
var x = "John";
var y = new String("John");
// typeof x will return string// typeof y will return object
var y = new String("John");
// typeof x will return string// typeof y will return object
Don't create strings as objects. It slows down execution speed.
The new keyword complicates the code. This can produce some unexpected results:
The new keyword complicates the code. This can produce some unexpected results:
- Extracting String Parts
- slice(start, end)
- substring(start, end)
- substr(start, length)
- 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:
var str = "Apple, Banana, Kiwi";
var res = str.slice(7,13);
The result of res will be:
Banana
- slice(start, end)
- substring(start, end)
- substr(start, length)
- 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:
var str = "Apple, Banana, Kiwi";
var res = str.slice(7,13);
var res = str.slice(7,13);
The result of res will be:
Banana
var str = "Apple, Banana, Kiwi";
var res = str.slice(-12,-6);(count from left side)
var res = str.slice(-12,-6);(count from left side)
again result will be "Banana"
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.
- other methods
- toUpperCase():
- toLowerCase():
- concat()
- charAt(position)
- charCodeAt() method returns the unicode of the character at a specified index in a string:
- toString() returns a number as a string.
- toExponential() returns a string, with a number rounded and written using exponential notation.
- Converting a String to an Array
A string can be converted to an array with the split() method:
var txt = "a,b,c,d,e"; // Stringtxt.split(","); // Split on commastxt.split(" "); // Split on spacestxt.split("|");
- JavaScript Math Object
Math.random() return a number <1
Math.PI;
Math.round()
a proper random function
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
return Math.floor(Math.random() * (max - min) ) + min;
}
math.min(), math.max(), math.cos()..........
- Date Get Methods
| 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) |
- Converting Arrays to Strings
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
note -> pop() and push() can be used for inserting and removing from a array in js .
document.getElementById("demo").innerHTML = fruits.toString();
- Shifting Elements
Shifting is equivalent to popping, working on the first element instead of the last.
The shift() method removes the first array element and "shifts" all other elements to a lower index.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift(); // Removes the first element "Banana" from fruits
fruits.shift(); // Removes the first element "Banana" from fruits
- Deleting Elements
Since JavaScript arrays are objects, elements can be deleted by using the JavaScript operator delete:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0]; // Changes the first element in fruits to undefined
- SORT AND REVERSE
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // Sorts the elements of fruits fruits.reverse(); // Reverses the order of the elements
delete fruits[0]; // Changes the first element in fruits to undefined
- SORT AND REVERSE
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // Sorts the elements of fruits fruits.reverse(); // Reverses the order of the elements
fruits.sort(); // Sorts the elements of fruits fruits.reverse(); // Reverses the order of the elements
- The Compare Function
The purpose of the compare function is to define an alternative sort order.
The compare function should return a negative, zero, or positive value, depending on the arguments:
function(a, b){return a-b}
ints.sort(function(a, b){return a - b});// SORTING WITH COMPARATOR ...
- Sorting Object Arrays
var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}];
cars.sort(function(a, b){return a.year - b.year});
BIT WISE OPERATOR
| << | Zero fill left shift | 5 << 1 | 0101 << 1 | 10 | 1010 |
| >> | Signed right shift | 5 >> 1 | 0101 >> 1 | 2 | 0010 |
| >>> | Zero fill right shift | 5 >>> 1 | 0101 >>> 1 | 2 | 0010 |
- Using String search() With aRegularExpression
var str = "Visit W3Schools";
var n = str.search(/w3schools/i); n=6,
Regular expression arguments (instead of string arguments) can be used in the methods above.
var str = "Visit W3Schools!";
var n = str.search("W3Schools");
but if we are doing with string than there are some limitations
Regular expressions can make your search much more powerful (case insensitive for example).
- Regular Expression Modifiers
Modifier Description
i Perform case-insensitive matching
g Perform a global match (find all matches rather than stopping after the first match)
m Perform multiline matching
| Modifier | Description |
|---|---|
| i | Perform case-insensitive matching |
| g | Perform a global match (find all matches rather than stopping after the first match) |
| m | Perform multiline matching |
- Regular Expression Patterns
Brackets are used to find a range of characters:
| Expression | Description |
|---|---|
| [abc] | Find any of the characters between the brackets |
| [0-9] | Find any of the digits between the brackets |
| (x|y) | Find any of the alternatives separated with | |
- JavaScript Declarations are Hoisted
In JavaScript, a variable can be declared after it has been used.
In other words; a variable can be used before it has been declared.
x = 5; // Assign 5 to x
elem = document.getElementById("demo"); // Find an element elem.innerHTML = x; // Display x in the element
var x; // Declare x
elem = document.getElementById("demo"); // Find an element elem.innerHTML = x; // Display x in the element
var x; // Declare x
- JavaScript Use Strict
"use strict"; Defines that JavaScript code should be executed in "strict mode".
strict will restrict a variable to be used before declaration..
- Why Strict Mode?
Strict mode makes it easier to write "secure" JavaScript.
Strict mode changes previously accepted "bad syntax" into real errors.
As an example, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.
In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties.
In strict mode, any assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object, will throw an error.
- Deleting a variable (or object) is not allowed in strict mode
"use strict";
var x = 3.14;
delete x; // This will cause an error
- Deleting a function is not allowed in a strict mode .
"use strict";
function x(p1, p2) {};
delete x;
- Duplicating a parameter name is not allowed:
"use strict";
function x(p1, p1) {}; // This will cause an error
- Escape characters are not allowed:
"use strict";
var x = \010; // This will cause an error
Strict mode makes it easier to write "secure" JavaScript.
Strict mode changes previously accepted "bad syntax" into real errors.
As an example, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.
In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties.
In strict mode, any assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object, will throw an error.
- Deleting a variable (or object) is not allowed in strict mode
"use strict";
var x = 3.14;delete x; // This will cause an error
- Deleting a function is not allowed in a strict mode .
"use strict";
function x(p1, p2) {}; delete x;
- Duplicating a parameter name is not allowed:
"use strict";
function x(p1, p1) {}; // This will cause an error- Escape characters are not allowed:
"use strict";
var x = \010; // This will cause an error
- JavaScript Performance
- Reduce Activity in Loops
- Reduce DOM Access
- Reduce DOM Size
- Avoid Unnecessary Variables
- Delay JavaScript Loading
-
Putting your scripts at the bottom of the page body, lets the browser load the page first.
While a script is downloading, the browser will not start any other downloads. In addition all parsing and rendering activity might be blocked.
The HTTP specification defines that browsers should not download more than two components in parallel.
An alternative is to use defer="true" in the script tag. The defer attribute specifies that the script should be executed after the page has finished parsing, but it only works for external scripts.
If possible, you can add your script to the page by code, after the page has loaded:
Putting your scripts at the bottom of the page body, lets the browser load the page first.
While a script is downloading, the browser will not start any other downloads. In addition all parsing and rendering activity might be blocked.
The HTTP specification defines that browsers should not download more than two components in parallel.
An alternative is to use defer="true" in the script tag. The defer attribute specifies that the script should be executed after the page has finished parsing, but it only works for external scripts.
If possible, you can add your script to the page by code, after the page has loaded:
- HTTP and HTTPS: What do they do, and how are they different?
You click to check out at an online merchant. Suddenly your browser address bar says HTTPS instead of HTTP. What's going on? Is your credit card information safe?
Good news. Your information is safe. The website you are working with has made sure that no one can steal your information.
Instead of HyperText Transfer Protocol (HTTP), this website uses HyperText Transfer Protocol Secure (HTTPS).
Using HTTPS, the computers agree on a "code" between them, and then they scramble the messages using that "code" so that no one in between can read them. This keeps your information safe from hackers.
They use the "code" on a Secure Sockets Layer (SSL), sometimes called Transport Layer Security (TLS) to send the information back and forth.
How does HTTP work? How is HTTPS different from HTTP? This tutorial will teach you about SSL, HTTP and HTTPS.
You click to check out at an online merchant. Suddenly your browser address bar says HTTPS instead of HTTP. What's going on? Is your credit card information safe?
Good news. Your information is safe. The website you are working with has made sure that no one can steal your information.
Instead of HyperText Transfer Protocol (HTTP), this website uses HyperText Transfer Protocol Secure (HTTPS).
Using HTTPS, the computers agree on a "code" between them, and then they scramble the messages using that "code" so that no one in between can read them. This keeps your information safe from hackers.
They use the "code" on a Secure Sockets Layer (SSL), sometimes called Transport Layer Security (TLS) to send the information back and forth.
How does HTTP work? How is HTTPS different from HTTP? This tutorial will teach you about SSL, HTTP and HTTPS.
- How Does HTTP Work?
In the beginning, network administrators had to figure out how to share the information they put out on the Internet.
They agreed on a procedure for exchanging information and called it HyperText Transfer Protocol (HTTP).
Once everyone knew how to exchange information, intercepting on the Internet was not difficult. So knowledgeable administrators agreed upon a procedure to protect the information they exchanged. The protection relies on SSL Certificate to encrypt the online data. Encryption means that the sender and recipient agree upon a "code" and translate their documents into random-looking character strings.
The procedure for encrypting information and then exchanging it is called HyperText Transfer Protocol Secure (HTTPS).
With HTTPS if anyone in between the sender and the recipient could open the message, they still could not understand it. Only the sender and the recipient, who know the "code," can decipher the message.
Humans could encode their own documents, but computers do it faster and more efficiently. To do this, the computer at each end uses a document called an "SSL Certificate" containing character strings that are the keys to their secret "codes."
SSL certificates contain the computer owner's "public key."
The owner shares the public key with anyone who needs it. Other users need the public key to encrypt messages to the owner. The owner sends those users the SSL certificate, which contains the public key. The owner does not share the private key with anyone.
The security during the transfer is called the Secure Sockets Layer (SSL) and Transport Layer Security (TLS).
The procedure for exchanging public keys using SSL Certificate to enable HTTPS, SSL and TLS is called Public Key Infrastructure (PKI).
In the beginning, network administrators had to figure out how to share the information they put out on the Internet.
They agreed on a procedure for exchanging information and called it HyperText Transfer Protocol (HTTP).
Once everyone knew how to exchange information, intercepting on the Internet was not difficult. So knowledgeable administrators agreed upon a procedure to protect the information they exchanged. The protection relies on SSL Certificate to encrypt the online data. Encryption means that the sender and recipient agree upon a "code" and translate their documents into random-looking character strings.
The procedure for encrypting information and then exchanging it is called HyperText Transfer Protocol Secure (HTTPS).
With HTTPS if anyone in between the sender and the recipient could open the message, they still could not understand it. Only the sender and the recipient, who know the "code," can decipher the message.
Humans could encode their own documents, but computers do it faster and more efficiently. To do this, the computer at each end uses a document called an "SSL Certificate" containing character strings that are the keys to their secret "codes."
SSL certificates contain the computer owner's "public key."
The owner shares the public key with anyone who needs it. Other users need the public key to encrypt messages to the owner. The owner sends those users the SSL certificate, which contains the public key. The owner does not share the private key with anyone.
The security during the transfer is called the Secure Sockets Layer (SSL) and Transport Layer Security (TLS).
The procedure for exchanging public keys using SSL Certificate to enable HTTPS, SSL and TLS is called Public Key Infrastructure (PKI).
No comments:
Post a Comment