-
A programming language that is used to make web pages interactive.
-
Interpreted language.
-
Runs on the client's computer/browser.
-
Game Development.
-
Server Application.
-
Web Application.
-
Native Mobile Application.
-
Desktop Application.
-
Typescript.
-
Frameworks before core javascript???
-
Dynamically Typed Language.
-
Case sensitive.
-
Whitespace are ignored.
-
Variables much not be a keyword.
-
Syntax parser
Your code => Compiler => Run at your computer
-
Reads each characters one by one.
-
Js object are name value paired.
-
Execution context
-
Creation phase
-
Execution code
-
Single Threaded
-
Synchronous.
-
Invocation
- Declarations
-var
-let
-const
- Declaring variables.
var firstName = 'JS';
-
Variable Hoisting.
-
Function Hoisting.
-
Declaring const.
const PIE = 3.14;
- Boolean.
var isReadable = true;
- null
var fruits = null;
- undefined
var firstName;
Never initialize you variable to undefined use null instead.
- Number
var firstIndex = 0;
- String
var firstName = 'I love JS';
- Object
var myCar = {};
- How to know data types ??
typeof myCar;
-
parseInt()
-
parseFloat()
-
+"1"
// Example:
let myNumber = '30.22';
parseInt(myNumber);
parseFloat(myNumber);
+myNumber;
if(condition) {
// do something
} else if(second condition) {
// do something else
} else {
// if none condition match, do this
}
var dollarPrice = 100;
if (dollarPrice <== 90) {
alert('Currently dollar price is low');
} else (dollarPrice > 90 || dollarPrice <== 140) {
alert('Current price of dollar is average')
} else {
alert('Current price of dollar is high')
}
switch (condition) {
case label:
// do something
break;
case label_2:
// do something else
break;
default:
// do if other doesnt do
break;
}
1. fasle
2. undefined
3. null
4. ''
5. 0
6. NaN
for(statement1, statement2, statement3) { // code to be executed }
for (let i = 0; i < 10; i++) {
console.log('index', i);
}
while (condition) {
// code to be executed
}
while (i < 10) {
console.log('index', i);
i++;
}
do {
// code to be executed
} while (condition);
do {
console.log('index', i);
i++;
} while (i < 10);
for item in collection {
// code to be executed
}
let fruits = ['apple', 'banana', 'cherry'];
for (fruit in fruits) {
console.log(fruits[fruit]);
// code to be executed
}
function functionName(parameter1, parameter2) {
// code to be executed
return value;
}
var result = getFirstName('Hari prasad');
function getFirstName(firstName) {
return 'Mr.' + firstName;
}
OR
const getFirstName = function(firstName) {
return 'Mr.' + firstName;
};
Collection of same data type.
Joins two array.
var result = Array.concat(value1[, value2[, ...[, valueN]]])
let fruits = ['apple'];
let additionalFruits = ['banana', 'cherry'];
let myFruits = fruits.concat(additionalFruits);
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
Array.map(function(item, index) {
return item;
});
// Multiple each number in array by 5.
var myNumbers = [1, 2, 3, 4];
var result = myNumbers.map(function(item, index) {
return item * 5;
});
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Array.filter(function(item, index) {
return condition;
});
// Multiple each number in array by 5.
var myNumbers = [1, 2, 3, 4];
var result = myNumbers.filter(function(item, index) {
return item % 2 === 0;
});
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
Array.map(function(item, index) {
return item;
});
// Multiple each number in array by 5.
var myNumbers = [1, 2, 3, 4];
var result = myNumbers.map(function(item, index) {
return item * 5;
});
The reduce() method executes a provided function for each value of the array (from left-to-right).
Array.reduce(function(total, currentValue, currentIndex), initialValue) {
return item;
});
var myNumbers = [1, 2, 3, 4];
var result = myNumbers.reduce(function(total, item) {
return total + item;
});
The includes() method determines whether an array contains a specified element
Array.includes(value);
var myNumbers = [1, 2, 3, 4];
var result = myNumbers.includes(5);
The push() method adds new elements to the end of an array, and returns the new length
Array.push(value);
var myNumbers = [1, 2, 3, 4];
myNumbers.push(5)
The pop() method removes the last element of an array, and returns that element
Array.pop();
var myNumbers = [1, 2, 3, 4];
myNumbers.pop()
The sort() method sorts the elements of an array
Array.sort();
// Multiple each number in array by 5.
var myNumbers = [5, 1, 2, 3, 4];
var result = myNumbers.sort();
var result = myNumbers.reverse();
A JavaScript object is a collection of named values. Object can have properties and methods.
var phone = {
modelNo: '1600',
brand: 'Nokai',
color: 'white',
getInfo: function() {
return 'Your mobile is' + this.brand + 'of' + this.modelNo;
}
};
Here, modelNo, brand and color are properties of phone.
getInfo is a method.
this refers to the owner of the funtion. Here this is a phone object that owns getInfo function.
var myObject = {};
var myObject = new Object();
var myObject = { key: value };
Syntax:
object.propertyName
Example:
var phone = {
modelNo: '1600',
brand: 'Nokai',
color: 'white'
};
var myPhone = phone.brand;
Javscript array and object are mutable, means any change to a copy of an object will also change the original.
var yesterdayCollection = 100;
var todayCollection = yesterdayCollection;
todayCollection = 200;
var yesterdayCollectionObj = {
amount: 100
}
var todayCollectionObj = yersterdayCollection;
todayCollection = {
amount: 200;
}
console.log(yesterdayCollection) //100
console.log(todayCollection) //200
console.log(yesterdayCollectionObje) //obj.amount = 200
console.log(todayCollectionObje) //obj.amount = 200
Docuement is everthing that is inside the html page. Object are the HTML elements and model is relationship between each nodes, elements and attributes.
- getElementById
- getElementByTagName
- getElementByClassName
- querySelector
<div id='firstName'>Im JS</div>
<input type='radio' name='gender' value='male' checked>Male</radio>
<input type='radio' name='gender' value='female'>Femaile</radio>
var myElement = document.getElementById('firstName');
var allDivElement = document.getElementByTagName('div');
var gender = document.querySelector('input[name=gender]:checked');
var myElement = document.getElementById('firstName');
console.log(myElement.innerHTML); // i'm JS
console.log((myElement.style.color = 'red'));
<div>
<input type="text" id='firstName' name="firstName" placeholder="Enter you firstname*" required />
<div class='error_name'> Name cannot be empty</div>
</div>
Getting previous element value.
document.getElementByClassName('error_name')[0].previousElementSibling.attributes['name'].value;
Getting next element value.
document.getElementById('firstName').nextElementSibling.innerHTML = 'Changed sibling text';
It is also good idea to have your HTML code looks like HTML and js code looks like JS code. We should not try to mix match them.
<JS/>
Here in this element, we used javascript function inside the element. This is mixture of HTML and JS.
<button id='btn' onclick='function()'>Click Me</button>
Instead of this, we can write
<button id='btn'>Click Me</button>
var btn = document.getElementById('btn');
function onSubmit() {
console.log('you clicked');
}
btn.onclick = onSubmit;
OR;
btn.addEventListener('click', onSubmit);
The Date() method returns current date
var todayDate = new Date(); //Sat Sep 22 201411:49:05
todayDate.getDay(); //6
todayDate.Date(); // 22
todayDate.getFullYear(); // 2014
todayDate.toLocaleTime(); // "11:48:49 AM"
todayDate.toLocaleDate(); // 9/22/2014
The setTimeOut() method calls a function or evaluates an expression after a specified number of milliseconds.
setTimeout(function, milliseconds, param1, param2, ...)
setTimeout(
function(name) {
alert(name + '10 sec is up');
},
10000,
'ram'
);
The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).
setInterval(function, milliseconds, param1, param2, ...)
// Get live time.
setInterval(function() {
document.body.innerHTML = new Date().toLocaleTimeString();
}, 1000);
The clearInterval() method clears a timer set with the setInterval() method.
clearInterval(setIntervalValue)
// Get live time.
var currentTime = setInterval(function() {
document.body.innerHTML = new Date().toLocaleTimeString();
}, 1000);
clearInterval(currentTime);
You can easily convert number to string with .toString() method. But inorder to convert object into string, you need JSON.stringify()
var myResult = {
math: 100,
science: 100
}
JSON.stringify(myResult) // "{"math":100,"science":100}"
The window object is supported by all browsers. It represents the browser's window.
- innerHeight: Returns the height of the window's content area (viewport) including scrollbars
- innerWidth: Returns the width of a window's content area (viewport) including scrollbars
- location: Returns the Location object for the window.
- localStorage: Allows to save key/value pairs in a web browser. Stores the data with no expiration date
- alert(): Displays an alert box with a message and an OK button.
- close(): Closes the current window.
- blur(): Removes focus from the current window.
// Get url info
window.location;
window.location.host;
window.location.href;
window.location.pathname;
// Get/Set localstorage
window.localStorage;
window.localStorage.setItem(name,'Im jS');
window.localStorage.getItem(name);
// get alert
window.alert('You are alret')
The Math object allows you to perform mathematical tasks.
var x = Math.PI; // Returns PI
var y = Math.sqrt(16); // Returns the square root of 16
var z = Math.pow(5,2); // 25
var a = Math.round(4.7); // 5
var rand = Math.random(); // 0.555