JS_Notes
JS_Notes
Comments
Comments are annotations in the code that are not executed. They are used to explain code,
making it easier to understand for others (and yourself).
/* This is a
multi-line comment */
Variables
Variables are used to store data values. In JavaScript, you can declare variables using three
keywords: var, let, and const.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
// Reassigning variables
name = "Bob"; // Allowed
age = 31; // Allowed
// isEmployed = false; // Not allowed, will throw an error
Output:
Data Types
JavaScript is a dynamically typed language, which means you don't have to specify the data type
of a variable when you declare it. Here are the primary data types in JavaScript:
Output:
str: "Hello, World!", num: 42, bool: false, nothing: null, und: undefine
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
2. Operators
Arithmetic Operators
Output:
Comparison Operators
Used to compare two values. They return a boolean value (true or false).
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
let isNotEqual = (5 != 3); // Not equal to
let isGreater = (5 > 3); // Greater than
let isLessOrEqual = (5 <= 5); // Less than or equal to
Output:
Logical Operators
let a = true;
let b = false;
Output:
Assignment Operators
Used to assign values to variables. The basic assignment operator is =. Here are some compound
assignment operators:
=: Assigns a value.
+=: Adds and assigns.
-=: Subtracts and assigns.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
*=: Multiplies and assigns.
/=: Divides and assigns.
%=: Modulus and assigns.
let x = 10;
x += 5; // x = x + 5
x -= 2; // x = x - 2
x *= 2; // x = x * 2
x /= 4; // x = x / 4
x %= 3; // x = x % 3
Output:
x: 1
3. Functions
A function is a block of code designed to perform a particular task. It is executed when something
invokes (calls) it.
function greet(name) {
let message = "Hello, " + name; // Concatenate string
return message; // Return the message
}
Output:
Function Expressions
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
let add = function(a, b) {
return a + b;
};
Output:
sum: 8
Arrow Functions
Introduced in ES6, arrow functions provide a more concise syntax for writing functions:
Output:
product: 20
Objects
An object is a collection of properties, where each property is a key-value pair. Objects can
represent real-world entities:
let person = {
name: "Alice",
age: 30,
isEmployed: true,
greet: function() {
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
return "Hello, " + this.name;
}
};
Output:
Arrays
An array is a special type of object used for storing ordered collections. Arrays can hold multiple
values in a single variable:
Output:
firstFruit: "apple"
5. Control Structures
Conditional Statements
Conditional statements are used to perform different actions based on different conditions:
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
} else {
console.log("Grade: C");
}
Output:
Grade: B
Loops
Loops allow you to execute a block of code multiple times. The for loop is commonly used:
Output:
0
1
2
3
4
Conclusion
Understanding these fundamental concepts will help you build a solid foundation in JavaScript
programming. Practice writing code to get comfortable with these topics!
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
JavaScript Fundamentals
let: Block-scoped. Can be updated but not re-declared in the same block.
var a = 10;
let b = 20;
const c = 30;
a = 15; // Allowed
b = 25; // Allowed
// c = 35; // Error: Assignment to constant variable.
console.log(a); // Output: 15
console.log(b); // Output: 25
console.log(c); // Output: 30
Output:
15
25
30
function checkValue(val) {
if (val) {
console.log(val + " is truthy.");
} else {
console.log(val + " is falsy.");
}
}
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
checkValue(0); // Output: 0 is falsy.
checkValue("hello"); // Output: hello is truthy.
checkValue(null); // Output: null is falsy.
checkValue({}); // Output: [object Object] is truthy.
Output:
0 is falsy.
hello is truthy.
null is falsy.
[object Object] is truthy.
Short-circuit evaluation occurs when evaluating logical expressions. If the first operand determines
the result, the second operand is not evaluated.
let x = true;
let y = false;
Output:
true
false
Output:
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
true
false
true
false
Pass by value: Primitive types (e.g., number, string) are passed by value.
let obj = { a: 1 };
function modifyObject(o) {
o.a = 2; // Changes original object
}
modifyObject(obj);
console.log(obj.a); // Output: 2
Output:
10
2
JavaScript automatically converts primitive values to their respective object types when methods
are called.
Output:
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
5
123
forEach
Output:
2
4
6
map
Creates a new array populated with the results of calling a provided function on every element.
Output:
[2, 4, 6]
filter
Creates a new array with all elements that pass the test implemented by the provided function.
Output:
[2]
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
reduce
Executes a reducer function on each element of the array, resulting in a single output value.
Output:
1. Function Hoisting
function hoistedFunction() {
console.log("I am hoisted");
}
Output:
I am hoisted
(function() {
console.log("I am an IIFE");
})(); // Output: "I am an IIFE"
Output:
I am an IIFE
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
3. Closures
Closures allow a function to access variables from an outer function's scope even after the outer
function has returned.
function outerFunction() {
let outerVariable = "I am outside!";
return function innerFunction() {
console.log(outerVariable);
};
}
Output:
I am outside!
4. Callback Functions
greet("Alice", function() {
console.log("This is a callback function.");
});
// Output:
// Hello, Alice!
// This is a callback function.
Output:
Hello, Alice!
This is a callback function.
5. Constructor Functions
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Constructor functions are used to create objects. By convention, their names start with a capital
letter.
Output:
Alice
JavaScript uses prototypes for inheritance. Every object can have a prototype object.
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name + " makes a noise.");
};
Output:
ES6 introduced class syntax for defining objects and handling inheritance more elegantly.
class Animal {
constructor(name) {
this.name = name;
}
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
speak() {
console.log(this.name + " makes a noise.");
}
}
Output:
Rex barks.
8. Functional Programming
Functional programming emphasizes functions as the primary building blocks of the program.
Higher-order functions, which can accept or return other functions, are common.
Output:
9. Object-Oriented Programming
JavaScript supports object-oriented programming through prototypes and class syntax. It allows
encapsulation, inheritance, and polymorphism.
class Vehicle {
constructor(make) {
this.make = make;
}
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
displayMake() {
console.log("Make: " + this.make);
}
}
Output:
Make: Toyota
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Modern JavaScript
ECMAScript
ECMAScript is the standardized scripting language specification upon which JavaScript is based. It
introduces various features and improvements in different versions (e.g., ES5, ES6).
Symbols
Symbols are unique and immutable data types that can be used as object property keys,
preventing name clashes.
BigInts
BigInt is a data type that can represent integers larger than the maximum safe integer in
JavaScript.
Sets
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Maps
Iterators are objects that allow traversal of a collection, while generators are functions that can be
paused and resumed.
function* numberGenerator() {
let i = 0;
while (i < 5) {
yield i++;
}
}
const gen = numberGenerator();
for (const num of gen) {
console.log(num); // 0, 1, 2, 3, 4
}
Proxies enable you to create a proxy for an object to intercept and redefine fundamental
operations, while Reflect is a built-in object that provides methods for interceptable JavaScript
operations.
const handler = {
get: function(target, property) {
return property in target ? target[property] : 'Property not found';
}
};
const target = { name: 'Alice' };
const proxy = new Proxy(target, handler);
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
console.log(proxy.name); // Alice
console.log(proxy.age); // Property not found
// Spread Operator
const array1 = [1, 2];
const array2 = [3, 4];
const combined = [...array1, ...array2]; // [1, 2, 3, 4]
// Rest Parameters
function sumAll(...args) {
return args.reduce((a, b) => a + b, 0);
}
console.log(sumAll(1, 2, 3)); // 6
// Destructuring
const person = { name: 'Alice', age: 30 };
const { name, age } = person;
console.log(name); // Alice
console.log(age); // 30
// Nullish Coalescing
const value = null;
const result = value ?? 'default'; // default
console.log(result);
// Optional Chaining
const user = { profile: { age: 25 } };
console.log(user?.profile?.age); // 25
// Arrow Functions
const multiply = (x, y) => x * y;
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
console.log(multiply(2, 3)); // 6
// Modules (Assuming `module.js` exists)
// Importing a function from another file
import { myFunction } from './module.js';
Asynchronous Programming
Synchronous vs Asynchronous
Synchronous code runs sequentially, while asynchronous code allows other tasks to run while
waiting for an operation to complete.
console.log('Start');
setTimeout(() => {
console.log('Timeout');
}, 2000);
console.log('End');
// Output: Start, End, Timeout
The JavaScript engine executes JavaScript code, while the environment provides the context, like
the browser or Node.js.
Timers
setTimeout(() => {
console.log('Executed after 1 second');
}, 1000);
setInterval(() => {
console.log('Executed every 2 seconds');
}, 2000);
Call Stack
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
function firstFunction() {
secondFunction();
}
function secondFunction() {
console.log('Second function executed');
}
firstFunction();
// Output: Second function executed
Event Loop
The event loop allows asynchronous operations to be executed after the call stack is empty.
console.log('First');
setTimeout(() => {
console.log('Second');
}, 0);
console.log('Third');
// Output: First, Third, Second
The task queue holds tasks from asynchronous operations, while the microtask queue handles
promises and other microtasks.
console.log('Start');
Promise.resolve().then(() => {
console.log('Microtask 1');
});
setTimeout(() => {
console.log('Task 1');
}, 0);
Promise.resolve().then(() => {
console.log('Microtask 2');
});
// Output: Start, Microtask 1, Microtask 2, Task 1
Callback Hell
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Callback hell occurs when callbacks are nested, leading to difficult-to-read code.
asyncFunction1((result1) => {
asyncFunction2(result1, (result2) => {
asyncFunction3(result2, (result3) => {
console.log(result3);
});
});
});
Promises
Promises represent a value that may be available now, or in the future, or never.
Async/Await
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Deep Dives
Execution Contexts
The execution context is the environment in which a piece of JavaScript code is evaluated.
function execute() {
const x = 10;
console.log(x);
}
execute();
// Output: 10
The this keyword refers to the context in which a function is executed. call , apply , and bind
are methods to control this .
const person = {
name: 'Alice',
greet() {
console.log(`Hello, ${this.name}`);
}
};
person.greet(); // Hello, Alice
const greetAlice = person.greet.bind(person);
greetAlice(); // Hello, Alice
Static typing means types are checked at compile time, while dynamic typing means types are
checked at runtime.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Overview of TypeScript
TypeScript is a superset of JavaScript that adds static typing, improving code quality and
maintainability.
JIT Compilation
WebAssembly (WASM) allows code written in languages like C/C++ to run in the browser
alongside JavaScript.
Memory Management
JavaScript uses garbage collection for automatic memory management, reclaiming memory when
it is no longer needed.
Node.js vs Browser
Node.js is a JavaScript runtime built on Chrome's V8 engine, enabling server-side scripting, while
browsers run JavaScript for client-side interactions.
Global Object
The global object is the top-level scope in JavaScript environments, providing access to global
variables and functions.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Manipulating the Document Object Model (DOM)
The DOM represents the structure of the document, allowing JavaScript to manipulate HTML and
CSS.
Event propagation includes capturing and bubbling phases. Event handling allows functions to
respond to events.
Form Handling
Submit
{
event.preventDefault();
alert('Form submitted!');
});
LocalStorage and SessionStorage provide storage for key-value pairs, while IndexedDB is a more
complex database for larger amounts of structured data.
// LocalStorage
localStorage.setItem('username', 'Alice');
console.log(localStorage.getItem('username')); // Alice
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
// SessionStorage
sessionStorage.setItem('sessionKey', 'sessionValue');
console.log(sessionStorage.getItem('sessionKey')); // sessionValue
Service Workers
Service workers allow the interception of network requests and enable offline capabilities for web
applications.
Web Workers
WebSockets
WebSockets provide a way to open a persistent connection between the client and server for real-
time communication.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
console.log('Message from server:', event.data);
};
WebGL is used for rendering 2D and 3D graphics in the browser. The Canvas API allows drawing
graphics on the fly.
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF