JavaScript Cheatsheet
Introduction:
JavaScript is the most popuplar language in the world for the web. We also call it Scripting Language.
↬ Extension: Save into .js
Types of Scripting Languages
There are two types of Scripting Language:
1. Client Side Scripting Languages such as JavaScript etc.
2. Server Side Scripting Languages such as Php, .Net etc.
JavaScript Libraries
JQuery, React, UnderScore, D3.js, Glimmer.js etc
Uses of JavaScript
Web Development, App Development, Software Development, Game Development etc.
Implementation of JavaScript:
<!-- Inpage JavaScript -->
<script>
document.write("Inpage or Internal JavaScript");
</script>
<!-- External JavaScript -->
<script src="js/script.js"></script>
Add HTML Tags in JavaScript:
document.Write("First Line of JavaScript <br> <br>");
document.Write("<i> <b> Second Line </b> of JavaScript </i>");
1. Comments in JavaScript
// Single Line Comment
/* This is Multi
Line Comment */
2. Variables in JavaScript:
Variable are used to store Data, such as Container. Variable is a name of a Storage Location.
// Initialization
var myName = "Sher Khan Baloch";
var myAge = 18;
// Declare
var myName, myAge;
// Assign Later
myName = "Sher Khan Baloch";
myAge = 18;
document.write(myName + myAge);
Difference Between Var, Let, Const
There are three types of Variables:
1. Var: if we declare a Variable with Var then we can declare it again with the same name and if we want to re-assign it's value then we can do that too.
2. Let: if we declare a variable with Let then we cannot declare it again with the same name but can re-assign it's value.
3. Const: if we declare a variable with Const then can neither declare it again nor can re-assign it's value.
3. Data Types in JavaScript
There are two types of Data Types.
1. Primitive Data Types: String, Number, Boolean, Null, Undefined.
2. Non-Primitive Data Types: Object, Array.
// Primitive Data Types:
var Name = "Sher Khan Baloch";
document.write(typeof Name);
var Age = 18;
document.write(typeof Age);
var isActive = true;
document.write(typeof isActive);
var x = null;
document.write(typeof x);
var x = undefined;
document.write(typeof x);
// Non-Primitive Data Types:
var countries = ["Pakistan", "India", "China", "USA", "Germany"];
document.write(typeof countries);
var Student = {
Name = "Sher Khan Baloch",
Age = 18
};
document.write(typeof Student);
4. Operators:
Operator is a symbol that is used to perform operations according to user requirement. We can perform this in variables or values
Types of Operators
1. Arithmetic Operators:
Arithmetic Operators are: +, -, *, /, ++, --
document.write(5 + 3); // Addition
document.write(5 - 3); // Subtraction
document.write(2 * 5); // Multiplication
document.write(2 / 5); // Divide
var a = 5;
var b = 3;
document.write(a + b);
var a = 5;
a++; // Increament (1 will be added in 5 and it will be 6)
document.write(a);
var a = 5;
a--; // Decreament (1 will be subtract from 5 and it will be 4)
document.write(a);
2. Assignment Operators:
Assignment Operators are: =, +=, -=, /=, etc
// Simple: = and Compound: +=, -=
var a = 6;
var b = 3;
a += b;
a = a + b; // Real Form
a -= b;
a = a - b; // Real Form
document.write(a);
3. Comparison Operators:
Comparison Operators are: <,>, <=,>=, ==, ===, !=, !== etc
// == Equal To
var x = 5;
var y = 5;
console.log(x == y);
// === Equal Value and Equal Type
var x = 5;
var y = "5";
console.log(x === y);
// != Not Equal
var x = 5;
var y = 5;
console.log(x != y);
// !== Not Equal Value or Not Equal Type
var x = 5;
var y = "5";
console.log(x !== y);
// > Greater Than
var x = 6;
var y = 5;
console.log(x > y);
// < Less Than
var x = 4;
var y = 5;
console.log(x < y);
// >= Greater Than or Equal To
var x = 5;
var y = 5;
console.log(x >= y);
// <= Less Than or Equal To
var x = 4;
var y = 5;
console.log(x <= y);
4. Logical Operators:
Logical Operators are: &&, ||, ! etc
// && - And Operator. All Given Conditions Should Be True.
var age = 20;
if (age >= 18 && age <= 40) {
console.log("This Condition Will Retrun True Because Both Conditon Match.")
}
// || - Or Operator. Any Single Condition Form Given Conditions Should Be True.
var x = 5;
var y = 10;
if (x == 5 || y == 15) {
console.log("This Condition Will Retrun True Because First Condition Match")
}
// ! - Not Operator. Make True To False and False To True.
var x = 5;
console.log(!x == 5);
5. Conditional Ternary Operator
Conditional Ternary Operators are: ?:
var age = 15;
var drive = age >= 18 ? 'You Can Drive' : 'You Cannot Drive';
console.log(drive);
5. Conditions In JavaScript
1. If, If Else, If Else If Statement
// 1. If Statement
var x = 5;
var y = 5;
if (x == y) {
console.log("This Will Return True Because X and Y has Same Value and Is Equal To Each Other.");
}
var x = 8;
var y = "5";
if (x === y) {
console.log("This Will Return False Beacuse X and Y Has Different Data Type and Different Values.");
}
// 2. If Else Statement
var x = 5;
var y = 5;
if (x == y) {
console.log("X and Y are equal.");
}
else {
console.log("X and Y are not equal.");
}
// 3. If Else If Statement
var time = 8;
if (time >= 8 && time < 12) {
console.log("Good Morning");
}
else if (time >= 12 && time < 4) {
console.log("Good After Noon");
}
else if (time >= 4 && time < 8) {
console.log("Good Evening");
}
else {
console.log("Good Night");
}
2. Switch Case
// Exmaple One:
var day = 1;
switch (day) {
case (1):
console.log("Monday");
break;
case (2):
console.log("Tuesday");
break;
case (3):
console.log("Wednesday");
break;
case (4):
console.log("Thursday");
break;
case (5):
console.log("Friday");
break;
case (6):
console.log("Saturday");
break;
case (7):
console.log("Sunday");
break;
default:
console.log("No Day Found. Enter Valid Day Number.");
break;
}
// Example Two:
var age = 18;
switch (true) {
case (age >= 18 && age >= 40):
console.log("You Are Eligible.");
break;
default:
console.log("You Are Not Eligible");
break;
}
6. Alert Box in JavaScript
// Simple Alert Box
alert("This Is Simple Alert Box.")
// Conditions In Alert Box.
var a = 8;
var b = 5;
if (a > b) {
alert("A Is Greater Than B.")
}
else {
alert("B Is Greater Than A.")
}
7. Confirm Box in JavaScript
// Simple Confirm Box
confirm("Do you like our website?");
// Comfirm Box With Condition
var a = confirm("Are You 18+ ?");
if (a) {
alert("Welcome To This Website.")
}
else {
alert("This Website Is Not For You. Please Wait Till When You Become 18 Years Old.")
}
8. Prompt Box in JavaScript
// Simple Prompt Box
prompt("What Is Your Name?");
var name = prompt("What Is Your Name?");
alert("Welcome Dear" + name)
// Prompt Box With Condition
var day = prompt("Enter Day Number.");
switch (true) {
case (day == 1):
console.log("Monday");
break;
case (day == 2):
console.log("Tuesday");
break;
case (day == 3):
console.log("Wednesday");
break;
case (day == 4):
console.log("Thursday");
break;
case (day == 5):
console.log("Friday");
break;
case (day == 6):
console.log("Saturday");
break;
case (day == 7):
console.log("Sunday");
break;
default:
console.log("No Day Found. Enter Valid Day Number.");
break;
}
9. Functions in JavaScript
// Creating Function
function myIntro() {
document.write("Hello World! I am Sher Khan Baloch.");
document.write("</b>");
document.write("Sottware & Web Developer.");
}
// Calling Fuction
myIntro();
// ********** Functions With Parameters **********
// Example One:
function fullName(firstName, lastName) {
console.log('Hello ' + firstName + ' ' + lastName);
}
fullName('Sher Khan', 'Baloch');
// Example Two:
function sum(num1, num2) {
console.log(num1 + num2);
}
sum(3, 5);
// Setting Default Names If User Don't Give Any Value
function fullName(firstName = 'Sher Khan', lastName = 'Baloch') {
console.log('Hello ' + firstName + ' ' + lastName);
}
fullName();
// ********** Function With Return Value **********
// Example One:
function fullName(firstName, lastName) {
var a = 'Hello ' + firstName + ' ' + lastName;
return a;
}
var b = fullName('Sher Khan', 'Baloch');
console.log(b);
// Example Two:
function sumMarks(eng, math, urdu, physics, chemistry) {
var total = eng + math + urdu + physics + chemistry;
return total;
}
var printResult = sumMarks(50, 58, 45, 67, 85);
console.log(printResult);
function percentage(obtain) {
var per = obtain / 500 * 100;
return per;
}
var printPercentage = percentage(printResult);
console.log(printPercentage + ' %');
10. Global and Local Varibale in JavaScript
// Global Varibale declare outside the function.
var global = 'This is Global Varibale';
console.log(global)
// Local Varibale declare inside the function.
function abc() {
var local = 'This is Local Varible';
console.log(local);
console.log(global);
}
abc();
// Note: Global Varibale Can Be Used In Any Function, But Local Varible Cannnot be used outside of function.
11. Mouse Events In JavaScript
<div id="box" onclick="func()"></div> <!-- Left Click Event. -->
<div id="box" oncontextmenu="func()"></div> <!-- Right Click Event. -->
<div id="box" ondblclick="func()"></div> <!-- Double Click Event. -->
<div id="box" onmousedown="func()"></div> <!-- Mouse Down Click Event. -->
<div id="box" onmouseup="func()"></div> <!-- Mouse Up Click Event. -->
<div id="box" onmouseover="func()"></div> <!-- Mouse Over Event. -->
<div id="box" onmouseout="func()"></div> <!-- Mouse Out Event. -->
<script>
function func() {
alert('Event Activated.');
}
</script>
12. Keyboard Events In JavaScript
<div id="form">
<!-- Example One: -->
<input type="text" onkeydown="alert(this.value);">
<input type="text" onkeyup="alert(this.value);">
<input type="text" onkeypress="alert(this.value);">
<!-- Example Two: -->
<input type="text" onkeydown="document.getElementById('form').style.backgroundColor = this.value">
<!-- Press Space or Any Key -->
<input type="text" onkeyup="document.getElementById('form').style.backgroundColor = this.value">
<!-- No Need to Press any other Key. -->
<input type="text" onkeypress="document.getElementById('form').style.backgroundColor = this.value">
</div>
13. Windows Events In JavaScript
<button onclick="openWindow()">Open Window</button>
<button onclick="closeWindow()">Close Window</button>
<script>
var myWindow;
function openWindow() {
// window.open();
myWindow = window.open("https://www.google.com", "_blank", "width=500px, height=500px, left=200px, top=200px ");
}
function closeWindow() {
myWindow.close();
}
</script>