JavaScript Fundamentals
Function names are highlighted in a bold reddish color.
Class names are highlighted in a blue color.
Variables are highlighted in a reddish-brown color.
Method names are highlighted in a green color.
1. Basic Syntax and Structure
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).
Single-line comments: Use // to comment a single line.
Multi-line comments: Use /* ... */ for comments that span multiple lines.
// This is a single-line comment
/* 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.
var: Declares a variable that can be re-assigned. It has function scope.
let: Introduced in ES6, let is block-scoped and can be re-assigned.
const: Also block-scoped, const is used to declare variables that cannot be re-assigned.
var name = "Alice"; // Using var
let age = 30; // Using let
const isEmployed = true; // Using 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:
name: "Bob", age: 31, isEmployed: true
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:
String: Represents text. Enclosed in quotes.
Number: Represents numeric values (both integers and floats).
Boolean: Represents a logical entity and can be either true or false.
Null: Represents the intentional absence of any object value.
Undefined: A variable that has been declared but not assigned a value has the value
undefined.
Object: A collection of key-value pairs, which can contain multiple values.
Array: A special type of object used for storing ordered collections.
let str = "Hello, World!"; // String
let num = 42; // Number
let bool = false; // Boolean
let nothing = null; // Null
let und; // Undefined
let obj = { name: "Alice" }; // Object
let arr = [1, 2, 3]; // Array
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
These operators are used to perform mathematical operations.
+ (Addition): Adds two values.
- (Subtraction): Subtracts one value from another.
* (Multiplication): Multiplies two values.
/ (Division): Divides one value by another.
% (Modulus): Returns the remainder of a division.
let sum = 5 + 3; // Addition
let difference = 5 - 3; // Subtraction
let product = 5 * 3; // Multiplication
let quotient = 5 / 3; // Division
let remainder = 5 % 3; // Modulus
Output:
sum: 8, difference: 2, product: 15, quotient: 1.6667, remainder: 2
Comparison Operators
Used to compare two values. They return a boolean value (true or false).
==: Equal to (checks value).
===: Strict equal to (checks value and type).
!=: Not equal to.
!==: Strict not equal to.
>: Greater than.
<: Less than.
>=: Greater than or equal to.
<=: Less than or equal to.
let isEqual = (5 == 5); // Equal to
let isStrictEqual = (5 === "5"); // Strict equal to (type matters)
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:
isEqual: true, isStrictEqual: false, isNotEqual: true, isGreater: true,
Logical Operators
These operators are used to perform logical operations on boolean values.
&&: Logical AND.
||: Logical OR.
!: Logical NOT.
let a = true;
let b = false;
let andResult = a && b; // Logical AND
let orResult = a || b; // Logical OR
let notResult = !a; // Logical NOT
Output:
andResult: false, orResult: true, notResult: false
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
}
let greeting = greet("Alice");
Output:
greeting: "Hello, Alice"
Function Expressions
Functions can also be defined as expressions. These can be assigned to variables:
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
let add = function(a, b) {
return a + b;
};
let sum = add(5, 3);
Output:
sum: 8
Arrow Functions
Introduced in ES6, arrow functions provide a more concise syntax for writing functions:
let multiply = (a, b) => a * b;
let product = multiply(4, 5);
Output:
product: 20
4. Objects and Arrays
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;
}
};
let greeting = person.greet();
Output:
greeting: "Hello, Alice"
Arrays
An array is a special type of object used for storing ordered collections. Arrays can hold multiple
values in a single variable:
let fruits = ["apple", "banana", "cherry"];
let firstFruit = fruits[0]; // Accessing the first element
Output:
firstFruit: "apple"
5. Control Structures
Conditional Statements
Conditional statements are used to perform different actions based on different conditions:
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
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:
for (let i = 0; i < 5; i++) {
console.log(i);
}
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
1. Let vs Const vs Var
var: Function-scoped or globally scoped. Can be re-declared and updated.
let: Block-scoped. Can be updated but not re-declared in the same block.
const: Block-scoped. Cannot be re-declared or updated (constant reference).
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
2. Truthy & Falsy Values
In JavaScript, values can be categorized as "truthy" or "falsy":
Falsy values: false, 0, "", null, undefined, NaN
Truthy values: Any value that is not falsy (e.g., 1, "hello", {}, [], etc.)
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.
3. Short Circuit Evaluation
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;
console.log(x || y); // Output: true (y is not evaluated)
console.log(x && y); // Output: false (y is evaluated)
Output:
true
false
4. Type Equality & Coercion
Strict equality (===): Compares both value and type.
Loose equality (==): Compares value after type coercion.
console.log(5 == "5"); // Output: true (coerced)
console.log(5 === "5"); // Output: false (not coerced)
console.log(null == undefined); // Output: true
console.log(null === undefined); // Output: false
Output:
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
true
false
true
false
5. Pass by Value vs Pass by Reference
Pass by value: Primitive types (e.g., number, string) are passed by value.
Pass by reference: Objects and arrays are passed by reference.
let num = 10;
function modifyValue(n) {
n = 20; // Changes local copy
}
modifyValue(num);
console.log(num); // Output: 10
let obj = { a: 1 };
function modifyObject(o) {
o.a = 2; // Changes original object
}
modifyObject(obj);
console.log(obj.a); // Output: 2
Output:
10
2
6. Autoboxing & Primitive Wrapper Objects
JavaScript automatically converts primitive values to their respective object types when methods
are called.
let str = "hello";
console.log(str.length); // Output: 5 (str is autoboxed to String object)
let num = 123;
console.log(num.toString()); // Output: "123" (num is autoboxed to Number object)
Output:
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
5
123
7. Advanced Array Methods (forEach, map, filter, reduce)
forEach
Executes a provided function once for each array element.
let numbers = [1, 2, 3];
numbers.forEach(num => console.log(num * 2)); // Output: 2, 4, 6
Output:
2
4
6
map
Creates a new array populated with the results of calling a provided function on every element.
let doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6]
Output:
[2, 4, 6]
filter
Creates a new array with all elements that pass the test implemented by the provided function.
let evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // Output: [2]
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.
let sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // Output: 6
Output:
Advanced Functions & Objects
1. Function Hoisting
Function declarations are hoisted to the top of their containing scope.
hoistedFunction(); // Output: "I am hoisted"
function hoistedFunction() {
console.log("I am hoisted");
}
Output:
I am hoisted
2. IIFEs (Immediately Invoked Function Expressions)
IIFEs are functions that run as soon as they are defined.
(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);
};
}
let closureFunc = outerFunction();
closureFunc(); // Output: "I am outside!"
Output:
I am outside!
4. Callback Functions
Functions passed as arguments to other functions are called callback functions.
function greet(name, callback) {
console.log("Hello, " + name + "!");
callback();
}
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.
function Person(name, age) {
this.name = name;
this.age = age;
}
const person1 = new Person("Alice", 30);
console.log(person1.name); // Output: "Alice"
Output:
Alice
6. Objects and Prototypes
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.");
};
const dog = new Animal("Dog");
dog.speak(); // Output: "Dog makes a noise."
Output:
Dog makes a noise.
7. Classes & Inheritance
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.");
}
}
class Dog extends Animal {
speak() {
console.log(this.name + " barks.");
}
}
const dog = new Dog("Rex");
dog.speak(); // Output: "Rex barks."
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.
const add = (a) => (b) => a + b;
const addFive = add(5);
console.log(addFive(3)); // Output: 8
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);
}
}
const car = new Vehicle("Toyota");
car.displayMake(); // Output: "Make: Toyota"
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).
const calculateSum = (a, b) => a + b;
console.log(calculateSum(5, 10)); // 15
Symbols
Symbols are unique and immutable data types that can be used as object property keys,
preventing name clashes.
const uniqueID = Symbol('id');
const user = {
[uniqueID]: 12345,
name: 'Alice'
};
console.log(user[uniqueID]); // 12345
BigInts
BigInt is a data type that can represent integers larger than the maximum safe integer in
JavaScript.
const bigNumber = BigInt(123456789012345678901234567890);
console.log(bigNumber); // 123456789012345678901234567890n
Sets
A Set is a collection of unique values, which can be of any type.
const mySet = new Set([1, 2, 3, 2, 1]);
mySet.add(4);
console.log(mySet); // Set(4) { 1, 2, 3, 4 }
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
Maps
A Map is a collection of key-value pairs where keys can be of any type.
const myMap = new Map();
myMap.set('name', 'Alice');
myMap.set('age', 25);
console.log(myMap.get('name')); // Alice
Iterators & Generators
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
}
Proxy and Reflect
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
Other ES6+ Features
Spread Operator: Expands iterable elements.
Rest Parameters: Collects all remaining elements into an array.
Destructuring: Unpacks values from arrays or properties from objects.
Nullish Coalescing: Returns the right-hand side operand when the left is null or undefined.
Optional Chaining: Accesses deeply nested properties without explicit checks.
Arrow Functions: Short syntax for writing functions.
Modules: Enables modular programming.
// 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
JavaScript Engine & JavaScript Environment
The JavaScript engine executes JavaScript code, while the environment provides the context, like
the browser or Node.js.
Timers
Timers are used to execute code after a specified delay.
setTimeout(() => {
console.log('Executed after 1 second');
}, 1000);
setInterval(() => {
console.log('Executed every 2 seconds');
}, 2000);
Call Stack
The call stack keeps track of function calls in JavaScript.
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
Task Queue & MicroTask Queue
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.
const myPromise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve('Success!');
} else {
reject('Failure!');
}
});
myPromise.then((message) => {
console.log(message);
}).catch((error) => {
console.error(error);
});
Async/Await
Async/await is syntax for working with promises more comfortably.
const fetchData = async () => {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
};
fetchData();
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
this Keyword & Call, Apply, Bind
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 vs Dynamic Typing
Static typing means types are checked at compile time, while dynamic typing means types are
checked at runtime.
// Example of Dynamic Typing
let dynamicVar = 10;
dynamicVar = 'Now I am a string';
console.log(dynamicVar); // Now I am a string
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.
function add(a: number, b: number): number {
return a + b;
}
console.log(add(2, 3)); // 5
JIT Compilation
Just-In-Time (JIT) compilation improves performance by compiling code at runtime instead of
beforehand.
Integrating JavaScript with Other Languages (WASM)
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.
JavaScript For Web
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.
console.log(window); // In the browser
console.log(global); // In Node.js
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.
document.querySelector('h1').textContent = 'New Heading';
document.body.style.backgroundColor = 'lightblue';
Event Propagation & Handling
Event propagation includes capturing and bubbling phases. Event handling allows functions to
respond to events.
document.querySelector('button').addEventListener('click', (event) => {
alert('Button clicked!');
});
Form Handling
JavaScript can be used to handle form submissions and validations.
const form = document.querySelector('form');
Submit
{
event.preventDefault();
alert('Form submitted!');
});
LocalStorage, SessionStorage, and IndexedDB
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.
// Registering a service worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js').then(registration => {
console.log('Service Worker registered with scope:', registration.scope);
});
}
Web Workers
Web workers enable running scripts in the background, preventing UI blocking.
// Creating a web worker
const worker = new Worker('worker.js');
worker.postMessage('Start');
worker.onmessage = function(event) {
console.log(event.data);
};
WebSockets
WebSockets provide a way to open a persistent connection between the client and server for real-
time communication.
const socket = new WebSocket('ws://example.com/socket');
socket.onopen = function() {
console.log('WebSocket connection opened');
};
socket.onmessage = function(event) {
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF
console.log('Message from server:', event.data);
};
WebGL API, Canvas API & More Web APIs
WebGL is used for rendering 2D and 3D graphics in the browser. The Canvas API allows drawing
graphics on the fly.
// Creating a canvas and drawing a rectangle
const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
context.fillStyle = 'blue';
context.fillRect(10, 10, 100, 100);
Explore our developer-friendly HTML to PDF API Printed using PDFCrowd HTML to PDF