
“Discover the ultimate JavaScript Cheat Sheet by Dr. Zeeshan Bhatti, designed specifically for absolute beginners eager to learn JavaScript from scratch. This comprehensive guide covers essential syntax, core functions, and practical tips to streamline your coding experience. Whether you’re aiming to master the basics or need a quick reference on variables, operators, loops, functions, or DOM manipulation, this cheat sheet provides a clear and concise roadmap for JavaScript programming. With Dr. Bhatti’s insights, beginners can build confidence and a solid foundation in JavaScript, enabling them to tackle projects, web applications, and further programming challenges. Start your JavaScript journey with this essential guide!”
Table of Contents
- 1. JavaScript Introduction
- 2. JavaScript Where To
- 3. JavaScript Output
- 4. JavaScript Comments
- 5. JavaScript Variables
- 6. JavaScript Let
- 7. JavaScript Const
- 8. JavaScript Operators
- 9. JavaScript Arithmetic
- 10. JavaScript Assignment
- 11. JavaScript Data Types
- 12. JavaScript typeof Operator
- 13. JavaScript Functions
- 14. JavaScript Function Return
- 15. JavaScript Events
- 16. JavaScript Strings
- 17. JavaScript String Methods
- 18. JavaScript Objects
- 19. JavaScript Arrays
- 20. JavaScript Array Methods
- 21. JavaScript Dates
- 22. JavaScript Comparisons
- 23. JavaScript If Else
- 24. JavaScript Switch
- 25. JavaScript Loop For
- 26. JavaScript Loop For In
- Conclusion:
1. JavaScript Introduction
- JavaScript is the world’s most popular programming language.
- JavaScript is the programming language of the Web.
- JavaScript is used to program the behavior of web pages
- JavaScript provides interactivity to web pages
2. JavaScript Where To
- The
- In HTML, JavaScript code is inserted between <script> and </script> tags.
<script>
document.getElementById(“demo”).innerHTML = “My First JavaScript”;
</script>
- You can place any number of scripts in an HTML document.
- Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.
- External JavaScript:
<script src=”myScript.js”></script>
- External JavaScript Advantages: Placing scripts in external files has some advantages:
- It separates HTML and code
- It makes HTML and JavaScript easier to read and maintain
- Cached JavaScript files can speed up page loads
3. JavaScript Output
- JavaScript can “display” data in different ways:
- Writing into an HTML element, using innerHTML.
- Writing into the HTML output using document.write().
- Writing into an alert box, using window.alert().
- Writing into the browser console, using console.log().
- Using innerHTML: document.getElementById(“demo”).innerHTML = 5 + 6;
- Using document.write(): document.write(5 + 6);
- Using window.alert(): window.alert(5 + 6);
- Using console.log(): console.log(5 + 6);
4. JavaScript Comments
- Single line comments start with //
- Any text between // and the end of the line will be ignored by JavaScript (will not be executed)
- Multi-line comments start with /* and end with */.
- Any text between /* and */ will be ignored by JavaScript.
5. JavaScript Variables
- Variables are containers for storing data (storing data values).
- 4 Ways to Declare a JavaScript Variable:
- Using var: var x = 5;
- Using let : let x = 5;
- Using const: const price1 = 5;
- Using nothing : x = 5;
- If you want a general rule: always declare variables with const.
- If you think the value of the variable can change, use let.
- Variables declared with the var keyword can NOT have block scope
- 4 Ways to Declare a JavaScript Variable:
var x = 10;
// Here x is 10
{
var x = 2;
// Here x is 2
}
// Here x is 2
6. JavaScript Let
- The let keyword was introduced in ES6 (2015).
- Variables defined with let cannot be Redeclared( two variables with same name).
- Variables defined with let must be Declared before use.
- Variables defined with let have Block Scope.
- let x = “John Doe”;
7. JavaScript Const
- The const keyword was introduced in ES6 (2015).
- JavaScript const variables must be assigned a value when they are declared:
- const PI = 3.14159265359;
- Variables defined with const cannot be Redeclared.
- Variables defined with const cannot be Reassigned.
- Variables defined with const have Block Scope.
- JavaScript const variables must be assigned a value when they are declared:
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
8. JavaScript Operators
- There are different types of JavaScript operators:
- Arithmetic Operators (+, -, *,/)
- Assignment Operators (=)
- Comparison Operators
- Logical Operators
- Conditional Operators
- Type Operators
9. JavaScript Arithmetic
- Arithmetic operators perform arithmetic on numbers (literals or variables).
Operator Description
+ Addition
– Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Remainder)
++ Increment
— Decrement
10. JavaScript Assignment
- Assignment operators assign values to JavaScript variables.
Operator | Example | Same As |
= | x = y | x = y |
+= | X += Y | x = x + y |
-= | x -= y | x = x – y |
*= | x *= y | x = x * y |
/= | x /= y | x = x / y |
%= | x %= y | x = x % y |
**= | x **= y | x = x ** y |
- Logical Assignment Operators
Operator | Example | Same As |
&&= | x &&= y | x = x && (x = y) |
||= | x ||= y | x = x || (x = y) |
??= | x ??= y | x = x ?? (x = y) |
11. JavaScript Data Types
- A JavaScript variable can hold any type of data
- JavaScript has 8 Datatypes
1. String let color = “Yellow”;
2. Number let length = 16;
3. Bigint let x = BigInt(“123456789012345678901234567890”);
4. Boolean let x = true;
5. Undefined let car; // Value is undefined, type is undefined
6. Null
7. Symbol
8. Object
- The Object Datatype
- 1. An object // Object: const person = {firstName:”John”, lastName:”Doe”};
- 2. An array const cars = [“Saab”, “Volvo”, “BMW”];
- 3. A date const date = new Date(“2022-03-25”);
- When adding a number and a string, JavaScript will treat the number as a string.
- JavaScript evaluates expressions from left to right. Different sequences can produce different results:
- let x = 16 + “Volvo”; // 16Volvo
- let x = “Volvo” + 16; // Volvo16
- let x = 16 + 4 + “Volvo”; // 20Volvo
- let x = “Volvo” + 16 + 4; // Volvo164
- JavaScript has dynamic types. This means that the same variable can be used to hold different data types:
let x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String
12. JavaScript typeof Operator
- You can use the JavaScript typeof operator to find the type of a JavaScript variable.
- The typeof operator returns the type of a variable or an expression:
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof "John Doe" // Returns "string"
typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
13. JavaScript Functions
- A JavaScript function is a block of code designed to perform a particular task.
- A JavaScript function is executed when “something” invokes it (calls it)
- A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
- The code to be executed, by the function, is placed inside curly brackets: {}
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
o // Function to compute the product of p1 and p2
function myFunction(p1, p2) {
return p1 * p2;
}
- Why Functions? You can reuse code: Define the code once, and use it many times.
- You can use the same code many times with different arguments, to produce different results.
- Local Variables: Variables declared within a JavaScript function, become LOCAL to the function.
- Local variables can only be accessed from within the function.
// code here can NOT use carName
function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}
// code here can NOT use carName
14. JavaScript Function Return
- When JavaScript reaches a return statement, the function will stop executing.
- If the function was invoked from a statement, JavaScript will “return” to execute the code after the invoking statement.
- Functions often compute a return value. The return value is “returned” back to the “caller”:
let x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
15. JavaScript Events
- HTML events are “things” that happen to HTML elements.
- When JavaScript is used in HTML pages, JavaScript can “react” on these events.
- HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
<element event=“some JavaScript“>
// In the following example, an onclick attribute (with code), is added to a <button> element:
<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button>
- In the next example, the code changes the content of its own element (using this.innerHTML):
<button onclick="this.innerHTML = Date()">The time is?</button>
- You can call a function from within the event attribute as well.
<p id="demo"></p>
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
- Common HTML Events
Event | Description |
onchange | An HTML element has been changed |
onclick | The user clicks an HTML element |
onmouseover | The user moves the mouse over an HTML element |
onmouseout | The user moves the mouse away from an HTML element |
onkeydown | The user pushes a keyboard key |
onload | The browser has finished loading the page |
16. JavaScript Strings
- JavaScript strings are for storing and manipulating text.
- A JavaScript string is zero or more characters written inside quotes.
- let text = “John Doe”;
- let length = text.length;
17. JavaScript String Methods
- There are several String Methods
String length | let length = text.length; |
String slice(start, end) | text.slice(7, 13); // slice out the rest of the string: text.slice(7); |
String substring(start, end) substring() is similar to slice(). The difference is that start and end values less than 0 are treated as 0 in substring(). | str.substring(7, 13); |
String substr(start, length) substr() is similar to slice(). The difference is that the second parameter specifies the length of the extracted part. | str.substr(7, 6); |
String replace() | let text = “Please visit Microsoft!”; let newText = text.replace(“Microsoft”, “W3Schools”); |
String replaceAll() | text.replaceAll(“Cats”,”Dogs”); |
String toUpperCase() | let text2 = text1.toUpperCase(); |
String toLowerCase() | let text2 = text1.toLowerCase(); |
String concat() | let text1 = “Hello”; let text2 = “World”; let text3 = text1.concat(” “, text2); text = “Hello” + ” ” + “World!”; text = “Hello”.concat(” “, “World!”); |
String trim() | let text1 = ” Hello World! “; let text2 = text1.trim(); |
String trimStart() String trimEnd() | let text1 = ” Hello World! “; let text2 = text1.trimStart(); let text2 = text1.trimEnd(); |
String padStart() String padEnd() | let text = “5”; let padded = text.padStart(4,”x”); //output: xxx5 let text = “5”; let padded = text.padEnd(4,”x”); //output: 5xxx |
String charAt() | let text = “HELLO WORLD”; let char = text.charAt(0); |
String charCodeAt() //returns the unicode of the character | let text = “HELLO WORLD”; let char = text.charCodeAt(0); |
String split() | text.split(“,”) // Split on commas text.split(” “) // Split on spaces text.split(“|”) // Split on pipe |
String indexOf() String lastIndexOf() String search() String match() String matchAll() String includes() String startsWith() String endsWith() |
18. JavaScript Objects
- Objects are variables too. But objects can contain many values.
- The values are written as name:value pairs (name and value separated by a colon).
- const car = {type:”Fiat”, model:”500″, color:”white”};
- You define (and create) a JavaScript object with an object literal:
- const person = {firstName:”John”, lastName:”Doe”, age:50, eyeColor:”blue”};
- Accessing Object Properties: You can access object properties in two ways:
- objectName.propertyName i.e person.lastName;
- OR objectName[“propertyName”] i.e. person[“lastName”];
19. JavaScript Arrays
- An array is a special variable, which can hold more than one value:
- const cars = [“Saab”, “Volvo”, “BMW”];
myArray = ["zero", "one", "two"];
window.alert(myArray[0]); // 0 is the first element of an array
// in this case, the value would be "zero"
myArray = ["John Doe", "Billy"];
elementNumber = 1;
window.alert(myArray[elementNumber]); // Billy
20. JavaScript Array Methods
- The JavaScript method toString() converts an array to a string of (comma separated) array values.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
- The join() method also joins all array elements into a string.
document.getElementById("demo").innerHTML = fruits.join(" * ");
- The pop() method removes the last element from an array:
fruits.pop();
- The pop() method returns the value that was “popped out”:
let fruit = fruits.pop();
- The push() method adds a new element to an array (at the end):
fruits.push(“Kiwi”);
- The push() method returns the new array length:
let length = fruits.push(“Kiwi”);
21. JavaScript Dates
- JavaScript Date Objects let us work with dates
- const d = new Date();
- const d = new Date(“2022-03-25”);
22. JavaScript Comparisons
Operator | Description | Comparing | Returns |
== | equal to | x == 8 | false |
x == 5 | true | ||
x == “5” | true | ||
=== | equal value and equal type | x === 5 | true |
x === “5” | false | ||
!= | not equal | x != 8 | true |
!== | not equal value or not equal type | x !== 5 | false |
x !== “5” | true | ||
x !== 8 | true | ||
> | greater than | x > 8 | false |
< | less than | x < 8 | true |
>= | greater than or equal to | x >= 8 | false |
<= | less than or equal to | x <= 8 | true |
- Logical Operators
Operator | Description | Example |
&& | And | (x < 10 && y > 1) is true |
|| | Or | (x == 5 || y == 5) is false |
! | Not | (x == 5 || y == 5) is false |
23. JavaScript If Else
In JavaScript we have the following conditional statements:
- Use if to specify a block of code to be executed, if a specified condition is true
- Use else to specify a block of code to be executed, if the same condition is false
- Use else if to specify a new condition to test, if the first condition is false
- Use switch to specify many alternative blocks of code to be executed
if (condition) {
// block of code to be executed if the condition is true
}
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
24. JavaScript Switch
- The switch statement is used to perform different actions based on different conditions.
- This is how it works:
- The switch expression is evaluated once.
- The value of the expression is compared with the values of each case.
- If there is a match, the associated block of code is executed.
- If there is no match, the default code block is executed.
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
25. JavaScript Loop For
- Loops can execute a block of code a number of times
- JavaScript supports different kinds of loops:
- for – loops through a block of code a number of times
- for/in – loops through the properties of an object
- for/of – loops through the values of an iterable object
- while – loops through a block of code while a specified condition is true
- do/while – also loops through a block of code while a specified condition is true
for (expression 1; expression 2; expression 3) {
// code block to be executed
}
26. JavaScript Loop For In
- The JavaScript for in statement loops through the properties of an Object:
for (key in object) {
// code block to be executed
}
const person = {fname:"John", lname:"Doe", age:25};
let text = "";
for (let x in person) {
text += person[x];
}
- Example Explained
- The for in loop iterates over a person objectEach iteration returns a key (x)The key is used to access the value of the key
- The value of the key is person[x]
- For In Over Arrays: The JavaScript for in statement can also loop over the properties of an Array:
- for (variable in array) {
code
} - Example:
const numbers = [45, 4, 9, 16, 25];
let txt = "";
for (let x in numbers) {
txt += numbers[x];
}
- JS Loop For Of
- The JavaScript for of statement loops through the values of an iterable object.
- It lets you loop over iterable data structures such as Arrays, Strings, Maps, NodeLists, and more
for (variable of iterable) {
// code block to be executed
}
- Example
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x;
}
Example
let language = "JavaScript";
let text = "";
for (let x of language) {
text += x;
}
- JS Loop While
- The while loop loops through a block of code as long as a specified condition is true
- while (condition) {
// code block to be executed
} - The do while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
do {
// code block to be executed
}
while (condition);
- JS Break & Continue
- The break statement “jumps out” of a loop.
- The continue statement “jumps over” one iteration in the loop.
Conclusion:
This Concludes the JavaScript Master Cheat Sheet. In this short and quick course, we covered all major concepts of JavaScript with direct examples.