Window Popup
alert("Hello! I am an alert box!")
Get Element By ID
document.getElementById('demo')// demo is the id of element
// Assign some value
document.getElementById('demo').innerHTML = Date();
document.getElementById('demo1').innerHTML = 'Magic'
// Change Font Size
document.getElementById('demo2').style.fontSize='35px'
Stop execution of debugging at certain point
debugger;
Hide
document.getElementById('demo1').style.display = 'none'
Display
document.getElementById('demo1').style.display = 'block'
Write in various form
document.write("This is document.write");
document.write("<br>");
document.write(10 * 5);
window.alert("This is window.alert");
console.log("this message is coming from console.log");
Function
//Accessing a function without () will return the function definition instead of the function result:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius;
Calling function
<input type="button" value="button1" onClick="myFunction()"/>
var text = "The temperature is " + toCelsius(77) + " Celsius";
Object
var car = {type:"Fiat", model:"500", color:"white"};
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
//The name:values pairs in JavaScript objects are called properties:
Accessing Object Properties
objectName.propertyName
//or
objectName["propertyName"]
Variable Declaration
// Simple string
var car = "Fiat"
The this Keyword
In a function definition, this refers to the "owner" of the function.
In other words, this.firstName means the firstName property of this object.
fullName : function() {
return this.firstName + " " + this.lastName;
}
<button onclick="this.innerHTML = Date()">The time is?</button>
//A method is a function stored as a property.
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
String Operations
Length
txt.length;
Escape character
The backslash (\) escape character turns special characters into string characters
var x = "We are the so-called \"Vikings\" from the north.";
More
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Horizontal Tabulator
\v Vertical Tabulator
Break Line string
var txt = "Hello \
Dolly!";
var txt = "Hello " +
"Dolly!";
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.
String Index
str.indexOf("locate");
str.lastIndexOf("locate");
Both indexOf(), and lastIndexOf() return -1 if the text is not found.
Both methods accept a second parameter as the starting position for the search:
str.indexOf("locate", 15);
String Search
The search() method searches a string for a specified value and returns the position of the match:
str.search("locate");
The search() method cannot take a second start position argument.
The indexOf() method cannot take powerful search values (regular expressions).
String other operations
slice(start, end)
substring(start, end)
substr(start, length)
substring() is similar to slice().
The difference is that substring() cannot accept negative indexes.
<script>
var str = "Apple, Banana, Kiwi";
var res = str.slice(-12)
document.getElementById("demo").innerHTML = res;
</script>
output:
Banana, Kiwi
<script>
var str = "Apple, Banana, Kiwi";
var res = str.slice(7);
document.getElementById("demo").innerHTML = res;
</script>
output:
Banana, Kiwi
var x = 100 / "Apple";
isNaN(x);
Output:
true
-----
String Equal
When using the == operator, equal strings are equal:
When using the === operator, equal strings are not equal, because the === operator expects equality in both type and value.
var x = 500;
var y = new Number(500);
// (x == y) is true because x and y have equal values
// (x === y) is false because x and y have different types
toFixed()
returns a string, with the number written with a specified number of decimals:
var x = 9.656;
x.toFixed(0); // returns 10
x.toFixed(2); // returns 9.66
x.toFixed(4); // returns 9.6560
x.toFixed(6); // returns 9.656000
toPrecision()
returns a string, with a number written with a specified length:
var x = 9.656;
x.toPrecision(); // returns 9.656
x.toPrecision(2); // returns 9.7
x.toPrecision(4); // returns 9.656
x.toPrecision(6); // returns 9.65600
valueOf()
returns a number as a number.
var x = 123;
x.valueOf(); // returns 123 from variable x
(123).valueOf(); // returns 123 from literal 123
(100 + 23).valueOf(); // returns 123 from expression 100 + 23
Array
var cars = ["Saab", "Volvo", "BMW"];
var cars = [
"Saab",
"Volvo",
"BMW"
];
var cars = new Array("Saab", "Volvo", "BMW");
Array Vs Object
Arrays use numbers to access its "elements". In this example, person[0] returns John
var person = ["John", "Doe", 46];
Objects use names to access its "members". In this example, person.firstName returns John
var person = {firstName:"John", lastName:"Doe", age:46};
In JavaScript, arrays use numbered indexes.
In JavaScript, objects use named indexes.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length of fruits is 4
fruits = ["Banana", "Orange", "Apple", "Mango"];
var first = fruits[0];//Accessing the First Array Element
var last = fruits[fruits.length - 1];//Accessing the Last Array Element
Looping Array Elements
var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
var fruits, text;
fruits = ["Banana", "Orange", "Apple", "Mango"];
text = "<ul>";
fruits.forEach(myFunction);
text += "</ul>";
function myFunction(value) {
text += "<li>" + value + "</li>";
}
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // adds a new element (Lemon) to fruits
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.
----
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
document.getElementById("demo1").innerHTML = fruits.join(" * ");
output:
Banana,Orange,Apple,Mango
Banana * Orange * Apple * Mango
The pop, push, shift, unshift
method removes the last element from an array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop(); // Removes the last element ("Mango") from fruits
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.pop(); // the value of x is "Mango"
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.push("Kiwi"); // the value of x is 5
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
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.shift(); // the value of x is "Banana"
The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Adds a new element "Lemon" to fruits
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Returns 5
----
The length property provides an easy way to append a new element to an array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Kiwi"; // Appends "Kiwi" to fruits
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
Using delete may leave undefined holes in the array. Use pop() or shift() instead.
The splice()
method can be used to add new items to an array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
The first parameter (2) defines the position where new elements should be added (spliced in).
The second parameter (0) defines how many elements should be removed.
The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.
The splice() method returns an array with the deleted items:
String concat
var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias", "Linus"];
var myChildren = myGirls.concat(myBoys); // Concatenates (joins) myGirls and myBoys
var arr1 = ["Cecilie", "Lone"];
var arr2 = ["Emil", "Tobias", "Linus"];
var arr3 = ["Robin", "Morgan"];
var myChildren = arr1.concat(arr2, arr3); // Concatenates arr1 with arr2 and arr3
var arr1 = ["Cecilie", "Lone"];
var myChildren = arr1.concat(["Emil", "Tobias", "Linus"]);
The slice, sort, referese()
method slices out a piece of an array into a new array.
This example slices out a part of an array starting from array element 1 ("Orange"):
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1);
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // First sort the elements of fruits
fruits.reverse(); // Then reverse the order of the elements
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b}); //Ascending
points.sort(function(a, b){return a - b}); //Descending