JavaScript notes
JavaScript Declarations are Hoisted
Functions declarations are also hoisted
JavaScript Initializations are Not Hoisted
typeof undefined // undefined
typeof null // object
null === undefined // false
null == undefined // true
var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
cars.length // gives size
cars.sort(); // only sorts alphabets not number array
cars.reverse();
// to sort number array
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
Array.isArray(cars); // returns true
var temp = "";
Array.isArray(temp); // returns false
// other method to check the type is using
// 'constructor' property
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = isArray(fruits);
function isArray(myArray) {
return myArray.constructor === Array; // this will return true
}
</script>
// similarly
<script>
var myDate = new Date();
document.getElementById("demo").innerHTML = isDate(myDate);
function isDate(myDate) {
return myDate.constructor === Date; // this will return true
}
</script>
// reason
new Date().constructor // this returns --- function Date() { [native code] }
// converts anything to string
String(x)
x.toString()
// converts string to number
Number("3.14") // returns 3.14
Number(" ") // returns 0
Number("") // returns 0
Number("99 88") // returns NaN
Number(false) // returns 0
Number(true) // returns 1
5 + null // returns 5 because null is converted to 0
"5" + null // returns "5null" because null is converted to "null"
"5" + 2 // returns 52 because 2 is converted to "2"
"5" - 2 // returns 3 because "5" is converted to 5
"5" * "2" // returns 10 because "5" and "2" are converted to 5 and 2
Boolean("0"); // retunrs true ******
Boolean(0); // retunrs false ******
// function - written inside the object
<script>
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
// constructor
<script>
function person(firstName,lastName,age,eyeColor) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.eyeColor = eyeColor;
this.changeName = function (name) {
this.lastName = name;
}
}
var myMother = new person("Sally","Rally",48,"green");
myMother.changeName("Doe");
document.getElementById("demo").innerHTML =
"My mother's last name is " + myMother.lastName;
</script>
// javascript prototype is a constructor only
// valid
<script>
var x = function (a, b) {return a * b};
document.getElementById("demo").innerHTML = x(4, 3);
</script>
// valid
// Function constructor
<script>
var myFunction = new Function("a", "b", "return a * b");
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>