JavaScript Notes
JavaScript Notes
1. Syntax
Case Sensitivity
JavaScript is a case-sensitive language, meaning that variables and function
names are distinguished by their capitalization. For example, myVariable and
myvariable would be treated as two separate identifiers.
Statements
Statements in JavaScript are terminated by a semicolon (;). However, JavaScript
has automatic semicolon insertion (ASI), which means that semicolons are often
optional. It is generally recommended to include them for better code
readability.
Comments
Comments in JavaScript can be single-line or multi-line. Single-line comments
start with //, while multi-line comments are enclosed between /* and */. Comments
are ignored by the JavaScript interpreter and are useful for adding explanations
or disabling code temporarily.
Code Formatting
JavaScript code can be included directly in an HTML file using <script>
tags, either in the <head> section or just before the closing </body>
tag. Alternatively, JavaScript code can be placed in an external file with a .js
extension and linked to the HTML file using the <script
src="filename.js"></script> tag.
2. Data Types
Primitive Data Types
JavaScript has several primitive data types:
Concatenation
Example 1:
Example 2:
let num1 = 5;
Template Literals:
in JavaScript allow for embedded expressions and multiline strings, making
string interpolation more concise. They are enclosed in backticks (`) and can
contain placeholders (${expression}) for dynamic values.
- Expressions within `${}` are evaluated and inserted into the string.
- Multiline strings: `const text = `Line 1
Line 2`;`
● Example:
const name = 'John';
const message = `My name is ${name} and I'm ${age} years old.`;
console.log(message);
● .
For example:
let person = {
name: ‘John Doe’;,
age: 30,
job: “Software Engineer”;
};
3. Variables
Variables are declared using the var, let, or const keyword.
● var was the original way to declare variables but has some quirks related
to scope. It is function-scoped, meaning that variables declared with var
are accessible throughout the entire function in which they are defined.
●
● let and const were introduced in ECMAScript 6 and provide block-scoping.
Variables declared with let are limited to the block they are defined in (e.g.,
within an if statement or loop). const creates a read-only variable with
block scope that cannot be reassigned.
Variables can store values of any data type, and their values can be
assigned and modified using the assignment operator (=).
For example:
let age = 25; // Declares a variable 'age' and assigns the value 25 to
it.
age = 30; // Modifies the value of 'age' to 30.
4. Operators
JavaScript supports a wide range of operators that perform various operations
on operands.
Arithmetic operators
Perform mathematical operations on numbers, such as addition (+), subtraction
(-), multiplication (*), division (/), modulus (%), increment (++), and decrement (--).
Assignment operators
Assign values to variables. The most common assignment operator is the equals
sign (=), but there are also compound assignment operators like +=, -=, *=, /=, and
more.
Comparison operators
Compare values and return a Boolean result. They include == (equal to), ===
(strictly equal to), != (not equal to), !== (strictly not equal to), >, <, >=, and <=.
Logical operators
Used to combine and manipulate Boolean values. The logical AND (&&), logical
OR (||), and logical NOT (!) operators are commonly used in conditional
statements and loops.
Increment (++)
Increases the value by one.
let x = 5;
x++; // x is now 6
Decrement (--)
Decreases the value by one.
let y = 10;
y--; // y is now 9
Negation (-)
Changes the sign of the operand.
let z = -5;
Typeof
Returns the type of the operand as a string.
Using these unary operators, you can perform specific operations on individual
operands to manipulate values and obtain desired results.
Examples
## Arithmetic Operators
## Assignment Operators
## Comparison Operators
## Logical Operators
Examples:
● Valid identifiers:
○ myVariable
○ _counter
○ $totalAmount
● Invalid identifiers:
○ 123abc
○ var
○ function()
○ my-variable
Note: Identifiers play a crucial role in JavaScript code and must adhere to these
rules to ensure proper syntax and avoid errors.
5. Methods in JavaScript
Methods in JavaScript are functions that are associated with objects or data
types. They allow you to perform actions, manipulate data, or retrieve
information associated with a specific object. Here are some commonly used
methods in JavaScript:
String Methods
String methods operate on string values and can be used to manipulate and
retrieve information from strings.
Array Methods
Array methods are used to manipulate and retrieve information from arrays.
Math Methods
Math methods provide mathematical operations and functions in JavaScript.
Date Methods
Date methods allow you to work with dates and times.
Object Methods
Object methods are functions that are associated with objects and allow you to
perform operations on those objects.
By using methods, you can perform various operations and retrieve information
from different data types in JavaScript. Understanding and utilising these
methods is essential for efficient coding and manipulating data effectively.
Please note that the code examples provided here are brief and simplified. For
detailed syntax and additional parameters of each method, it is recommended to
refer to the official JavaScript documentation or relevant resources.
6. Control Structures
Conditional statements
Loops
● The for loop is commonly used when the number of iterations is known or
determined in advance.
●
● The while loop executes a block of code as long as a specified condition is
true.
●
● The do-while loop is similar to the while loop but guarantees that the code
block is executed at least once, even if the condition is initially false.
● The break statement is used to exit the loop immediately, skipping any
remaining iterations.
●
● The continue statement is used to skip the current iteration and move to
the next iteration of the loop.
2. Creating Arrays
● You can create an array using square brackets [] and
comma-separated values inside.
● Example:
javascript
3. Accessing Elements
● Elements in an array are accessed using their index, starting from 0.
● Use square brackets and the index to retrieve the element at that
position.
● Example:
javascript
4. Modifying Elements
● You can modify elements in an array by assigning new values to
specific indexes.
● Example:
javascript
5. Array Length
● The length property of an array gives the number of elements it
contains.
● Example:
javascript
console.log(fruits.length); // Output: 3
6. Adding Elements
● Use the .push() method to add elements to the end of an array.
● Use the .unshift() method to add elements to the beginning of an
array.
● Example:
javascript
javascript
8. Slicing Arrays
● The .slice() method extracts a portion of an array into a new array
without modifying the original.
● Example:
javascript
9. Combining Arrays
● You can combine arrays using the .concat() method or the spread
operator (...).
● Example:
javascript
javascript
});
/* Output:
Index 0: apple
Index 1: banana
Index 2: orange
*/
Conclusion
Arrays are versatile data structures in JavaScript, offering powerful
capabilities to store and manipulate collections of data. With arrays, you
can easily access, modify, add, and remove elements as needed. By
understanding array methods and iterating techniques, you can
efficiently work with arrays in your JavaScript programs and build
complex data-driven applications.
8. Objects
For example:
let person = {
name: “John”;,
age: 30,
};
Or:
let person = new Object( );
person.name = “John”;
person.age = 30;
For example:
console.log(person.name); // Output: John
console.log(person.age); // Output: 30
For example:
let person = {
name: “John”,
age: 30,
address: {
}
};
For example:
let person = {
name: “John”,
age: 30,
greet: function() {
};
Math Object
The Math object is a global object that contains properties and methods for
performing mathematical operations. Some of the properties of the Math object
include:
function greet() {
console.log(“Hello!”);
}
Parameters
Parameters can be passed into functions to provide inputs for the function's
logic. Parameters are listed inside the parentheses when defining the function.
For example:
function greet(name) {
console.log(“Hello”, + name + “!”);
}
Return value
Functions can return a value using the return statement. The return value can be
assigned to a variable or used directly. For example:
function add(a, b) {
return a + b;
}
let sum = add(3, 5);
console.log(sum); // Output: 8
Function expressions
Anonymous functions
setTimeout(function() {
console.log(“Delayed message”);
}, 2000);
Conclusion
1. Arrow Function
● Arrow functions are a concise and convenient way to define functions in
JavaScript.
● They were introduced in ES6 (ECMAScript 2015) and provide a shorter
syntax compared to regular function expressions.
1.1 Syntax
javascript
return a + b;
};
// Arrow function
2. Timeout Function
● The `setTimeout` function is used to schedule the execution of a function
after a specified delay (in milliseconds).
2.1 Syntax
javascript
setTimeout(callbackFunction, delay);
2.2 Usage
javascript
function showMessage() {
setTimeout(showMessage, 2000);
3. Interval Function
3.1 Syntax
javascript
setInterval(callbackFunction, interval);
3.2 Usage
javascript
function showMessage() {
setInterval(showMessage, 3000);
clearInterval(intervalId);
4. "this" with Arrow Function
● Arrow functions handle the this keyword differently than regular functions.
● In arrow functions, this is lexically (statically) scoped, meaning it retains the
value of this from its surrounding context.
4.1 Example
javascript
const person = {
name: "John",
sayHello: function () {
},
sayHelloArrow: () => {
},
};
4.2 Explanation
● In the sayHello method (regular function), this refers to the person object,
so this.name correctly accesses the name property within the object.
● In the sayHelloArrow method (arrow function), this is lexically bound to the
surrounding context, which is the global context in this case (unless
person was defined in the global context). As a result, this.name returns
undefined.
Remember that arrow functions are not suitable for methods that require
dynamic this binding, such as object methods, event handlers, and prototype
methods. In such cases, use regular functions to ensure proper this context.
1.4 Closures
● Closures are functions that "remember" the environment in which they were
created.
● They have access to variables from their outer (enclosing) scope even after
that scope has finished executing.
● Closures are powerful and often used to create private variables and data
encapsulation.
2. Higher-Order Functions
2.1 What are Higher-Order Functions?
1. map:
javascript
// Transforms each element of an array using a provided function and returns a new array.
2. filter:
javascript
// Creates a new array containing elements that pass a test implemented by the provided
function.
3. reduce:
javascript
console.log(sum); // Output: 15
4. forEach:
javascript
numbers.forEach((num) => {
console.log(num * 2);
});
// Output:
// 2
// 4
// 6
// 8
// 10
5. sort:
javascript
3. Try-Catch in JavaScript
● The try block contains the code that might throw an exception (error).
● If an error occurs in the try block, the control is immediately transferred to
the catch block.
3.5 Example:
javascript
try {
// Code that may throw an exception
const result = someFunction();
console.log(result);
} catch (error) {
// Handle the error
console.error("An error occurred:", error.message);
} finally {
// Cleanup operations (optional)
console.log("This will be executed regardless of errors.");
}
● You can also throw custom errors using the throw keyword.
● Custom errors can be useful for better error handling and conveying
specific error conditions.
javascript
function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero is not allowed.");
}
return a / b;
}
try {
const result = divide(10, 0);
console.log(result);
} catch (error) {
console.error("An error occurred:", error.message);
}
Remember that the best practice is to use specific error types that inherit from
the Error object for custom errors.
These are the essential concepts related to scopes, higher-order functions, and
try-catch in JavaScript. Understanding these topics will help you write more
robust and maintainable code.
1.1 Definition
● The spread operator (...) is a powerful feature introduced in ES6 (ECMAScript
2015) for working with arrays and objects in a more concise and flexible way.
1.4 Note
● The spread operator performs a shallow copy, meaning nested objects or
arrays are still referenced and not cloned.
2. Rest Parameter
2.1 Definition
● The rest parameter is also denoted by the three dots (...) but used in function
definitions to handle an arbitrary number of function arguments as an array.
2.2 Usage
javascript
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
2.3 Note
● The rest parameter must be the last parameter in the function declaration, as
it collects all remaining arguments into an array.
javascript
Understanding the spread and rest concepts allows you to manipulate arrays and
function arguments more efficiently and elegantly in JavaScript.
● Example:
html
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<script>
</script>
</body>
</html>
● Example:
html
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<script>
</script>
</body>
</html>
● Example:
html
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<script>
</script>
</body>
</html>
● Example:
html
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<script>
</script>
</body>
</html>
● Example:
html
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<script>
function changeText() {
</script>
</body>
</html>
● Example:
html
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<script>
function changeImage() {
myImage.setAttribute('src', 'new_image.jpg');
}
</script>
</body>
</html>
● Example:
html
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<script>
function changeStyle() {
myDiv.style.backgroundColor = "yellow";
myDiv.style.fontSize = "24px";
</script>
</body>
</html>
● Example:
html
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
function addClass() {
myDiv.classList.add('highlight');
function removeClass() {
myDiv.classList.remove('highlight');
</script>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
</style>
</body>
</html>
3. Navigation on Page:
● Example:
html
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
</ul>
<script>
</script>
</body>
</html>
3.2. Siblings:
● Use the previousSibling and nextSibling properties to access an
element's siblings.
● Example:
html
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<script>
</script>
</body>
</html>
● Example:
html
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<script>
function addNewElement() {
myDiv.appendChild(newElement);
</script>
</body>
</html>
● Example:
html
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
</ul>
<script>
function removeListItem() {
myList.removeChild(listItemToRemove);
</script>
</body>
</html>
These are some fundamental concepts for interacting with the DOM using
JavaScript. Understanding and utilizing these methods and properties
will allow you to create dynamic and engaging web applications.
javascript
document.getElementById('myButton').addEventListener('click', function(event) {
});
javascript
document.getElementById('myElement').addEventListener('mouseover', function(event) {
javascript
document.getElementById('myElement').addEventListener('mouseout', function(event) {
});
javascript
document.getElementById('myElement').addEventListener('mousemove', function(event) {
});
javascript
document.getElementById('myElement').addEventListener('click', function(event) {
});
javascript
function clickHandler(event) {
document.getElementById('myButton').addEventListener('click', clickHandler);
document.getElementById('myButton').removeEventListener('click', clickHandler);
4. The 'this' Keyword in Event Listeners
The 'this' keyword in an event listener refers to the element to which the
event listener is attached. It allows you to access and manipulate
properties and attributes of the current element.
javascript
document.querySelectorAll('.myClass').forEach(function(element) {
element.addEventListener('click', function(event) {
this.classList.toggle('active');
});
});
5. Keyboard Events
Keyboard events are triggered by user interactions with the keyboard.
javascript
document.addEventListener('keydown', function(event) {
// Your keydown event handling code here
});
● keyup: Fired when a key is released. Useful for detecting when a user
releases a key after pressing it down.
javascript
document.addEventListener('keyup', function(event) {
});
● keypress: Similar to keydown, but this event is not fired for all keys. It
is only triggered for keys that produce a character value
(alphanumeric keys).
javascript
document.addEventListener('keypress', function(event) {
});
6. Form Events
Form events are triggered by interactions with HTML forms.
javascript
document.getElementById('myForm').addEventListener('submit', function(event) {
});
javascript
document.getElementById('myInput').addEventListener('change', function(event) {
});
7. Other Events
There are many other events available, such as:
● load: Fired when the page finishes loading. Useful for triggering
actions after the page has loaded completely.
javascript
window.addEventListener('load', function(event) {
});
javascript
window.addEventListener('resize', function(event) {
});
javascript
document.getElementById('myElement').addEventListener('scroll', function(event) {
});
Conclusion
Understanding DOM events, event listeners, and handling various types
of events is crucial for building interactive and responsive web
applications. By leveraging these concepts, you can create engaging user
experiences that respond to user actions and inputs effectively.
● Functions are added to the call stack when they are called and
removed when they complete execution.
● When a new function is called, it is pushed onto the top of the stack.
3. Breakpoints in JavaScript
● Breakpoints are markers set in the source code to pause the
execution of a script at a specific line.
4. JavaScript is Single-Threaded
● JavaScript is a single-threaded language, meaning it executes one
operation at a time.
5. Callback Hell
● Callback hell refers to deeply nested callbacks, leading to
unreadable and hard-to-maintain code.
javascript
getData(function(data) {
getMoreData(data, function(moreData) {
getEvenMoreData(moreData, function(evenMoreData) {
// and so on...
});
});
});
16. Promises
6. Setting Up Promises
● Promises are a way to handle asynchronous operations more
elegantly and avoid callback hell.
● A promise represents a value that may not be available yet but will
resolve or reject in the future.
javascript
const fetchData = new Promise((resolve, reject) => {
// Asynchronous operation
setTimeout(() => {
// reject(new Error('Data not found')); // Error: Reject the promise with an error
}, 2000);
});
javascript
function fetchData() {
// Asynchronous operation
setTimeout(() => {
const data = { name: 'John', age: 30 };
// reject(new Error('Data not found')); // Error: Reject the promise with an error
}, 2000);
});
javascript
fetchData()
.then((data) => {
console.log(data);
})
.catch((error) => {
});
9. Promise Chaining
● Promise chaining allows multiple asynchronous operations to be
executed in sequence.
javascript
fetchData()
.then((data) => {
// First operation
console.log(data);
})
.then((additionalData) => {
// Second operation
console.log(additionalData);
.then((finalData) => {
// Third operation
console.log(finalData);
})
.catch((error) => {
console.error(error);
});
● Use .then() to handle the resolved data and .catch() to handle errors in
promises.
Conclusion
Understanding the call stack, using breakpoints, and adopting promises
can greatly improve your JavaScript coding experience. Promises provide
a cleaner and more maintainable way to handle asynchronous operations,
reducing the likelihood of callback hell. With promises, you can efficiently
manage both successful results and error handling in your asynchronous
code. By visualizing the call stack and effectively utilizing promises, you
can write more reliable and readable JavaScript applications.