Your cart is currently empty!
Learn JavaScript (Full Tutorial)

JavaScript Tutorial
JavaScript is the world’s most popular programming language, used to program the behavior of web pages. It’s easy to learn and essential for all web developers alongside HTML and CSS.
This tutorial teaches JavaScript from basic to advanced, with examples you can edit and run using our “Try it Yourself” editor.
Why Learn JavaScript?
Every web developer must know:
-
HTML – defines page content
-
CSS – styles and layouts
-
JavaScript – controls behavior and interactivity
Learning tip: Practice every example. Code, experiment, and repeat.
Displaying Output
JavaScript can display data in several ways:
-
innerHTML – insert content into HTML elements
-
document.write() – writes directly to the page (testing only)
-
alert() – shows a popup
-
console.log() – logs output to the browser console
-
window.print() – prints the current page
JavaScript Statements
A program is a list of instructions (statements) executed by the browser.
-
Semicolons end statements (
;) – optional but recommended -
Whitespace improves readability – ignored by JavaScript
-
Line breaks: break long lines after operators for clarity
Code Blocks
Statements can be grouped in code blocks {…}, for example inside functions:
Tip: Use consistent indentation (2 spaces recommended).
JavaScript Keywords
Keywords are reserved words that perform actions and cannot be used as variable names. Common ones include:
| Keyword | Purpose |
|---|---|
var |
Declare variable |
let |
Declare block-scoped variable |
const |
Declare constant |
if |
Conditional execution |
switch |
Multi-case execution |
for |
Loops |
function |
Declare a function |
return |
Exit a function |
try |
Error handling |
JavaScript Comments
Comments are used to explain code, improve readability, or temporarily disable code.
Single-Line Comments
Start with //. Everything after // on the line is ignored by JavaScript.
Multi-Line (Block) Comments
Start with /* and end with */. Everything in between is ignored.
Using Comments to Prevent Execution
You can disable code temporarily for testing:
Tip: Single-line comments are most common; block comments are useful for documentation or disabling multiple lines.
JavaScript Operators
Operators perform operations on values or variables.
1. Assignment Operators
Assign values to variables:
2. Arithmetic Operators
Perform arithmetic on numbers:
| Operator | Description |
|---|---|
| + | Addition |
| – | Subtraction |
| * | Multiplication |
| / | Division |
| % | Modulus (remainder) |
| ** | Exponentiation |
| ++ | Increment |
| — | Decrement |
3. String Operators
-
+ concatenates strings
-
Adding a number to a string converts the number to a string:
4. Comparison Operators
Compare values:
| Operator | Description |
|---|---|
| == | equal to |
| === | equal value and type |
| != | not equal |
| !== | not equal value or type |
| > | greater than |
| < | less than |
| >= | greater than or equal to |
| <= | less than or equal to |
| ? | ternary operator |
5. Logical Operators
| Operator | Description |
|---|---|
| && | AND |
| || | OR |
| ! | NOT |
6. Type Operators
| Operator | Description |
|---|---|
| typeof | Returns the type of a variable |
| instanceof | Checks if an object is an instance of a type |
7. Bitwise Operators
Operate on 32-bit numbers:
| Operator | Description | Example | Result |
|---|---|---|---|
| & | AND | 5 & 1 | 1 |
| | | OR | 5 | 1 | 5 |
| ~ | NOT | ~5 | -6 |
| ^ | XOR | 5 ^ 1 | 4 |
| << | Left shift | 5 << 1 | 10 |
| >> | Right shift | 5 >> 1 | 2 |
| >>> | Unsigned right shift | 5 >>> 1 | 2 |
Note: JavaScript uses 32-bit signed integers, so ~5 returns -6, not 10.
JavaScript Arithmetic
Arithmetic operators perform calculations on numbers (literals or variables).
Arithmetic Operators
| Operator | Description |
|---|---|
| + | Addition |
| – | Subtraction |
| * | Multiplication |
| / | Division |
| % | Modulus (remainder) |
| ** | Exponentiation |
| ++ | Increment |
| — | Decrement |
Examples
Addition
Subtraction
Multiplication
Division
Remainder (modulus)
Increment / Decrement
Exponentiation
Operator Precedence
Precedence determines the order operations are performed (like in math).
-
Multiplication/division have higher precedence than addition/subtraction.
-
Parentheses
()override precedence.
Operator Precedence Table (Summary)
| Precedence | Operators |
|---|---|
| 21 | ( ) Expression grouping |
| 20 | . [] () new Member/Call/Create |
| 18-17 | ++ -- Postfix/Prefix, !, typeof |
| 16 | ** Exponentiation |
| 15 | * / % |
| 14 | + - |
| 13 | << >> >>> Shift |
| 12 | < <= > >= in instanceof |
| 11 | == === != !== |
| 10-8 | `& ^ |
| 7-6 | `&& |
| 5 | ?? Nullish coalescing |
| 4 | ? : Conditional |
| 3 | = += -= *= /= %= <<= >>= ... Assignment |
| 2 | yield Pause function |
| 1 | , Comma operator |
Tip: Expressions inside parentheses are always evaluated first.
JavaScript Assignment Operators
Assignment operators assign or update values of variables.
| Operator | Example | Equivalent To |
|---|---|---|
| = | 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 |
| >>= | x >>= y |
x = x >> y |
| >>>= | x >>>= y |
x = x >>> y |
| &= | x &= y |
x = x & y |
| ^= | x ^= y |
x = x ^ y |
| |= | `x | = y` |
| **= | x **= y |
x = x ** y |
Examples
Basic assignment (=)
Addition assignment (+=)
Subtraction assignment (-=)
Multiplication assignment (*=)
Division assignment (/=)
Remainder assignment (%=)
JavaScript Data Types
JavaScript variables can hold different types of data: numbers, strings, objects, arrays, and more.
Dynamic Types
JavaScript is dynamically typed, meaning the same variable can hold different types:
Strings
Strings are sequences of characters, enclosed in single or double quotes:
-
Quotes inside a string must differ from the surrounding quotes:
Numbers
JavaScript has one number type (integers and floats).
-
Scientific notation:
Booleans
Booleans have only true or false values, often used in conditions:
Arrays
Arrays store multiple values, using square brackets:
Objects
Objects store key:value pairs, using curly braces:
The typeof Operator
Use typeof to check a variable’s type:
Undefined
A variable without a value is undefined:
Empty Values
An empty string has a value and a type:
JavaScript Functions
A function is a block of code designed to perform a task. It runs only when called (invoked).
Function Syntax
-
Parameters: placeholders listed in parentheses.
-
Arguments: values passed to the function when called.
-
Inside a function, parameters act as local variables.
Example: Multiplication
Why Use Functions?
-
Reuse code without rewriting.
-
Use different arguments to produce different results.
-
Using
toCelsius(without()) refers to the function object. -
Using
toCelsius()returns the function result.
Functions as Values
Functions can be used directly in expressions:
Local Variables
Variables declared inside a function are local and cannot be accessed outside:
JavaScript Objects
Objects are variables that can store multiple values as properties and methods.
Real-Life Example
A car is an object:
| Object | Properties | Methods |
|---|---|---|
| car | name, model, weight, color | start(), drive(), brake(), stop() |
-
Properties describe the object (e.g., color, weight).
-
Methods are actions the object can perform (e.g., start, stop).
Object Definition
Objects are created using object literals with name:value pairs:
-
Spaces and line breaks don’t matter.
Object Properties
-
Properties are the named values inside an object.
Object Methods
-
Methods are functions stored as properties:
-
thisrefers to the current object.-
this.firstName→person.firstName
-
JavaScript Events
JavaScript can react to “events” that happen on HTML elements.
What Are HTML Events?
HTML events are things that happen in the browser or by the user:
-
Page has finished loading (
onload) -
Input field value changed (
onchange) -
Button clicked (
onclick) -
Mouse moves over/out of an element (
onmouseover,onmouseout) -
Keyboard key pressed (
onkeydown)
Using Event Attributes
You can attach JavaScript code directly in HTML:
-
this.innerHTMLrefers to the element itself.
Calling Functions with Events
Instead of writing code inline, you can call a function:
Common HTML Events
| Event | Description |
|---|---|
| onchange | Element value changed |
| onclick | User clicks an element |
| onmouseover | Mouse moves over an element |
| onmouseout | Mouse moves away from an element |
| onkeydown | User presses a key |
| onload | Browser finished loading the page |
Event Handlers in JavaScript
Event handlers let you perform actions when events occur:
-
Run code when a page loads
-
Execute actions when a user clicks a button
-
Verify user input
-
Stop or control events
Methods to handle events:
-
HTML event attributes calling code directly
-
HTML event attributes calling JavaScript functions
-
Assigning event handler functions in JavaScript
-
Preventing events from being handled
JavaScript Strings
Strings store and manipulate text. They are zero or more characters enclosed in single or double quotes:
-
Quotes inside a string must differ from the surrounding quotes:
String Length
Use the length property:
Escape Characters
Use \ to include special characters in a string:
| Code | Result | Description |
|---|---|---|
| ‘ | ‘ | Single quote |
| “ | “ | Double quote |
| \ | \ | Backslash |
| \b | Backspace | Backspace |
| \f | Form Feed | Form feed |
| \n | New Line | New line |
| \r | Carriage Return | Carriage return |
| \t | Tab | Horizontal tab |
| \v | Vertical tab | Vertical tab |
Examples:
Breaking Long Strings
-
Prefer string addition over
\for readability:
-
Avoid using
\at the end of a line; it may not work in all browsers.
Strings as Objects
-
Normally, strings are primitive values:
-
You can create string objects with
new(not recommended):
-
Comparison difference:
-
Comparing two string objects always returns false with
===:
⚠️ Do not use
new String(). It complicates code and slows execution.
JavaScript String Search
JavaScript provides several methods to search and check strings.
1. indexOf()
Returns the index of the first occurrence of a substring. Returns -1 if not found.
2. lastIndexOf()
Returns the index of the last occurrence of a substring. Returns -1 if not found.
3. search()
Searches for a substring (or regex) and returns the position. Cannot take a starting index.
Difference:
search()supports regular expressions,indexOf()supports start position.
4. match()
Searches a string against a regular expression and returns matches as an array.
5. includes()
Returns true if a string contains a substring, false otherwise.
6. startsWith()
Returns true if a string begins with a substring. Case-sensitive.
7. endsWith()
Returns true if a string ends with a substring. Case-sensitive.
JavaScript String Methods
Strings are sequences of characters. JavaScript provides many methods and properties to manipulate them.
1. String Length
Returns the number of characters in a string.
2. Extracting String Parts
a) slice(start, end)
Extracts a part of a string; end not included. Negative values count from the end.
b) substring(start, end)
Similar to slice(), but negative values are treated as 0.
c) substr(start, length)
Second parameter is length of extracted part. Negative start counts from end.
3. Replacing Content
replace()
Replaces a value with another. Returns a new string. By default: first match, case-sensitive.
4. Changing Case
5. Concatenation
concat()
Joins two or more strings. Equivalent to + operator.
6. Trimming Whitespace
trim()
Removes whitespace from both sides.
7. Padding Strings (ES2017+)
padStart(targetLength, padString)
Pads string at the start.
padEnd(targetLength, padString)
Pads string at the end.
8. Extracting Characters
charAt(index)
Returns character at index.
charCodeAt(index)
Returns Unicode value (UTF-16) at index.
Property access [ ]
Access like array (read-only). Returns undefined if index invalid.
9. Converting String to Array
split(separator)
Splits a string into an array based on a separator.
JavaScript Template Literals
Template literals (also called template strings or string templates) are a modern way to work with strings in JavaScript using back-ticks (“) instead of quotes.
1. Back-Ticks Syntax
-
Use “ instead of
" "or' '. -
Allows both single and double quotes inside the string without escaping.
2. Multiline Strings
Template literals allow strings to span multiple lines:
No need for \n or string concatenation.
3. String Interpolation
Template literals support variable and expression substitution using ${...}.
a) Variable Substitution
-
Automatic replacement of variables with their values is called string interpolation.
b) Expression Substitution
-
You can include any JavaScript expression inside
${...}.
4. HTML Templates
Template literals are useful for building HTML dynamically:
-
Produces a complete HTML string using variables and loops.
Advantages of Template Literals:
-
Easier to read and write multiline strings.
-
Avoids string concatenation (
+) for variables. -
Supports embedding expressions directly.
-
Makes dynamic HTML generation simpler.
JavaScript Numbers
JavaScript has only one number type, which is always a 64-bit floating point (double precision) following the IEEE 754 standard.
1. Number Syntax
Scientific Notation
2. Precision
-
Integers are accurate up to 15 digits:
-
Floating point arithmetic may have small errors:
-
Workaround:
3. Adding Numbers and Strings
-
+adds numbers or concatenates strings:
-
Left-to-right evaluation matters:
4. Numeric Strings
JavaScript tries to convert strings to numbers for arithmetic operations:
5. NaN – Not a Number
-
Result of illegal numeric operations:
-
isNaN()checks if a value is NaN:
-
Note:
typeof NaNreturns"number".
6. Infinity
-
Calculations beyond the largest number, or division by 0:
7. Hexadecimal Numbers
-
Prefix with
0x:
-
Convert numbers to different bases:
8. Numbers as Objects
-
Primitive numbers:
-
Number objects (not recommended):
-
Comparison:
-
Two Number objects:
Tip: Avoid using
new Number(); it slows code and can produce unexpected behavior.
JavaScript Number Methods
JavaScript provides methods to work with numbers. Even though primitive numbers are not objects, JavaScript temporarily wraps them to allow method execution.
1. toString()
Converts a number to a string.
2. toExponential()
Converts a number to exponential notation. Optional parameter defines decimals.
3. toFixed()
Formats a number with a fixed number of decimals.
Great for working with money.
4. toPrecision()
Formats a number with a specified total length.
5. valueOf()
Returns the primitive number value of a Number object.
Usually used internally; rarely needed in code.
Converting Variables to Numbers
Three global methods are used:
-
Number() -
parseInt() -
parseFloat()
1. Number()
Converts a value to a number.
Number() with Dates
Returns milliseconds since 1970-01-01:
2. parseInt()
Parses a string and returns an integer:
3. parseFloat()
Parses a string and returns a floating-point number:
Number Properties
JavaScript Number constants provide useful numeric limits:
| Property | Description |
|---|---|
Number.MAX_VALUE |
Largest possible number |
Number.MIN_VALUE |
Smallest possible number |
Number.POSITIVE_INFINITY |
Infinity (overflow) |
Number.NEGATIVE_INFINITY |
-Infinity (overflow) |
Number.NaN |
Not-a-Number |
Examples:
Note: Number properties belong to the
Numberobject itself.
UsingmyNumber.MAX_VALUEwill returnundefined:
JavaScript Date Objects
JavaScript Date objects are used to work with dates and times.
1. Creating Date Objects
a) new Date()
Creates a date object with current date and time.
b) new Date(year, month, day, hours, minutes, seconds, milliseconds)
Create a date with specific values.
Note:
-
Months are 0-indexed (0 = January, 11 = December).
-
Overflow is handled automatically:
You can supply fewer numbers:
| Numbers Provided | Example |
|---|---|
| 6 numbers | new Date(2018, 11, 24, 10, 33, 30) |
| 5 numbers | new Date(2018, 11, 24, 10, 33) |
| 4 numbers | new Date(2018, 11, 24, 10) |
| 3 numbers | new Date(2018, 11, 24) |
| 2 numbers | new Date(2018, 11) |
| 1 number | treated as milliseconds since 1970 |
Previous century:
1- or 2-digit years are interpreted as 19xx:
c) new Date(dateString)
Creates a date object from a date string:
d) new Date(milliseconds)
Creates a date object as milliseconds since 01 Jan 1970 00:00:00 UTC:
One day = 86,400,000 milliseconds.
2. Displaying Dates
By default, Date objects display as full text strings:
Other display formats:
| Method | Description | Example Output |
|---|---|---|
toUTCString() |
Converts date to UTC string | “Tue, 14 Jun 2022 11:51:25 GMT” |
toDateString() |
Converts date to readable format | “Tue Jun 14 2022” |
toISOString() |
Converts date to ISO standard | “2022-06-14T11:51:25.000Z” |
3. Key Notes
-
Date objects are static; the time in the computer keeps ticking, but the object does not update automatically.
-
JavaScript internally stores dates as milliseconds since 1970-01-01 00:00:00 UTC.
-
Overflow in months or days is automatically handled.
JavaScript Date Formats
JavaScript allows several ways to input dates. Output is typically standardized to a full text string.
1. Date Input Formats
a) ISO Date (Recommended)
-
Format:
"YYYY-MM-DD" -
Example:
-
ISO 8601 standard is strictly defined and preferred.
-
Can also specify only year and month, or only year:
-
Can include time:
b) Short Date
-
Format:
"MM/DD/YYYY" -
Example:
-
Warnings:
-
Some browsers may fail if leading zeros are missing:
"2015-3-25" -
"YYYY/MM/DD"is not standard, may returnNaN. -
"DD-MM-YYYY"is also undefined in some browsers.
-
c) Long Date
-
Formats:
"MMM DD YYYY"or"DD MMM YYYY" -
Examples:
-
Commas are ignored; month names are case-insensitive:
2. Time Zones
-
By default, JavaScript uses the browser’s local time zone.
-
UTC time can be specified with
Zor+/-HH:MMin ISO strings. -
Dates are automatically converted to the local time zone when displayed.
3. Date Output
-
Independent of input format, the default display is full text string:
4. Parsing Dates
-
Use
Date.parse()to convert a date string to milliseconds since January 1, 1970:
-
This is useful for calculations or converting to a
Dateobject.
✅ Best Practices:
-
Prefer ISO 8601 format (
YYYY-MM-DDorYYYY-MM-DDTHH:MM:SSZ). -
Avoid browser-dependent short or long formats for reliability.
-
Always consider time zone differences when parsing or displaying dates.
JavaScript Get Date Methods
These methods allow you to extract information from a Date object.
| Method | Description | Example |
|---|---|---|
getFullYear() |
Returns the year (4 digits) | const d = new Date(); d.getFullYear(); // 2025 |
getMonth() |
Returns the month (0–11) | const d = new Date(); d.getMonth(); // 0 = Jan, 11 = Dec |
getDate() |
Returns the day of the month (1–31) | const d = new Date(); d.getDate(); |
getDay() |
Returns the day of the week (0–6) | const d = new Date(); d.getDay(); // 0 = Sunday |
getHours() |
Returns the hour (0–23) | const d = new Date(); d.getHours(); |
getMinutes() |
Returns the minutes (0–59) | const d = new Date(); d.getMinutes(); |
getSeconds() |
Returns the seconds (0–59) | const d = new Date(); d.getSeconds(); |
getMilliseconds() |
Returns the milliseconds (0–999) | const d = new Date(); d.getMilliseconds(); |
getTime() |
Returns the time in milliseconds since January 1, 1970 | const d = new Date(); d.getTime(); |
Date.now() |
Returns the current time in milliseconds (ECMAScript 5) | Date.now(); |
Examples of Using getMonth() and getDay() with Names
Note:
getMonth()counts from 0 to 11,getDay()counts from 0 (Sunday) to 6 (Saturday).
JavaScript Math Object
The Math object provides properties and methods for mathematical operations.
It has no constructor, meaning you do not create an instance.
Math Properties (Constants)
| Property | Description |
|---|---|
Math.E |
Euler’s number (≈ 2.718) |
Math.PI |
PI (≈ 3.14159) |
Math.SQRT2 |
√2 |
Math.SQRT1_2 |
√(1/2) |
Math.LN2 |
Natural log of 2 |
Math.LN10 |
Natural log of 10 |
Math.LOG2E |
Base-2 log of E |
Math.LOG10E |
Base-10 log of E |
Rounding Numbers
| Method | Description |
|---|---|
Math.round(x) |
Round to nearest integer |
Math.ceil(x) |
Round up to nearest integer |
Math.floor(x) |
Round down to nearest integer |
Math.trunc(x) |
Return integer part only |
Math.sign(x) |
Returns sign: -1, 0, 1 |
Powers and Roots
| Method | Description |
|---|---|
Math.pow(x, y) |
x raised to the power y |
Math.sqrt(x) |
Square root |
Math.cbrt(x) |
Cube root |
Absolute Value
| Method | Description |
|---|---|
Math.abs(x) |
Absolute (positive) value |
Trigonometry (Radians)
Convert degrees → radians:
radians = degrees * Math.PI / 180
| Method | Description |
|---|---|
Math.sin(x) |
Sine |
Math.cos(x) |
Cosine |
Math.tan(x) |
Tangent |
Math.asin(x) |
Arcsine |
Math.acos(x) |
Arccosine |
Math.atan(x) |
Arctangent |
Math.atan2(y, x) |
Arctangent of y/x |
Min, Max, Random
| Method | Description |
|---|---|
Math.min(a, b, c…) |
Returns smallest |
Math.max(a, b, c…) |
Returns largest |
Math.random() |
Random number 0 ≤ x < 1 |
Logarithms
| Method | Description |
|---|---|
Math.log(x) |
Natural logarithm (base E) |
Math.log2(x) |
Base-2 logarithm |
Math.log10(x) |
Base-10 logarithm |
Summary Table of Common Math Methods
| Method | Description |
|---|---|
abs(x) |
Absolute value |
ceil(x) |
Round up |
floor(x) |
Round down |
round(x) |
Round nearest |
trunc(x) |
Integer part |
pow(x, y) |
x^y |
sqrt(x) |
Square root |
cbrt(x) |
Cube root |
sin(x) |
Sine |
cos(x) |
Cosine |
tan(x) |
Tangent |
asin(x) |
Arcsine |
acos(x) |
Arccosine |
atan(x) |
Arctangent |
atan2(y, x) |
Arctangent of y/x |
random() |
Random number [0,1) |
min(x, y…) |
Minimum value |
max(x, y…) |
Maximum value |
log(x) |
Natural log |
log2(x) |
Base 2 log |
log10(x) |
Base 10 log |
sign(x) |
Sign (-1,0,1) |
Math.random()
-
Returns a random number between 0 (inclusive) and 1 (exclusive):
-
Never reaches 1, always less than 1.
Random Integers
Combine Math.random() with Math.floor() to generate integers:
| Example | Description |
|---|---|
Math.floor(Math.random() * 10) |
0–9 |
Math.floor(Math.random() * 11) |
0–10 |
Math.floor(Math.random() * 100) |
0–99 |
Math.floor(Math.random() * 101) |
0–100 |
Math.floor(Math.random() * 10) + 1 |
1–10 |
Math.floor(Math.random() * 100) + 1 |
1–100 |
Math.floor()rounds down, so the highest value is always one less than the multiplier, unless you add 1.
Reusable Random Integer Functions
1️⃣ Random integer between min (included) and max (excluded):
-
Example:
getRndInteger(1, 10)→ 1–9
2️⃣ Random integer between min and max (both included):
-
Example:
getRndInteger(1, 10)→ 1–10
💡 Tip:
Whenever you need random integers in a range, using a function is safer and reusable. You can just call getRndInteger(min, max) instead of repeating the formula each time.
JavaScript For Loop
The for loop is used to execute a block of code multiple times.
Syntax
| Statement | Purpose |
|---|---|
| statement1 | Executed once before the loop starts (usually for variable initialization). |
| statement2 | Condition checked before each iteration; loop runs while true. |
| statement3 | Executed after each iteration (usually increment/decrement). |
Basic Example
-
i = 0→ start -
i < 5→ continue looping -
i++→ increaseiby 1 after each loop
Output:
Advanced for Syntax
1️⃣ Multiple initializations:
2️⃣ Omitting statement1 (variables defined before the loop):
3️⃣ Omitting statement3 (increment inside the loop):
4️⃣ Omitting statement2 (requires break to avoid infinite loop):
Variable Scope in Loops
-
Using
var:
-
Using
let:
Tip: Always use
letfor loop counters to avoid scope issues.
Why use for loops?
-
Iterating over arrays, lists, or ranges of numbers.
-
When you know exactly how many times you want to repeat code.
JavaScript for…in Loop
The for…in loop iterates over the keys (property names) of an object.
Syntax
Example – Object
Explanation:
-
key→ each property name (fname,lname,age) -
person[key]→ accesses the value of the property
For for…in Over Arrays
⚠️ Warning: The order of indices is not guaranteed. Use
fororfor…ofif order matters.
Array.forEach() Alternative
-
Takes 3 arguments: value, index, array
-
You can use just the value if needed:
JavaScript for…of Loop
The for…of loop iterates over the values of iterable objects like arrays, strings, maps, sets, and more.
Syntax
-
variable→ gets the value of each element in the iterable -
iterable→ an object that can be iterated
Supported in modern browsers (Chrome 38+, Edge 12+, Firefox 51+, Safari 7+). Not supported in IE.
Example – Array
Example – String
Key Difference Between for…in and for…of
| Feature | for…in |
for…of |
|---|---|---|
| Loops over | keys / property names | values |
| Use with | Objects, Arrays | Arrays, Strings, Maps, Sets, NodeLists |
| Order guaranteed | No | Yes (for arrays and strings) |
| IE Support | Yes | No |
JavaScript While Loop
The while loop executes a block of code as long as a specified condition is true.
Syntax
Example
Important:
-
If the variable in the condition (
i) is not updated, the loop becomes infinite and may crash your browser.
JavaScript Do…While Loop
The do…while loop is similar to while, but executes the code block once before checking the condition.
Syntax
Example
Key difference:
-
The code always runs at least once, even if the condition is
false.
Comparing for, while, and do…while
-
forloop: Good when the number of iterations is known. -
whileloop: Good when the number of iterations is unknown, and the loop depends on a condition. -
do…whileloop: Ensures at least one execution before checking the condition.
Collecting Array Elements Example
Using for loop:
Using while loop:
Observation:
-
whileandforcan be interchangeable when you manage the variable initialization and increment manually.
Break Statement
The break statement exits a loop entirely or exits a switch statement.
Syntax
Example – Exiting a Loop
Output:
Explanation:
-
When
iequals 3, thebreakstatement immediately ends the loop.
Continue Statement
The continue statement skips the current iteration and moves to the next iteration of the loop.
Syntax
Example – Skipping an Iteration
Output:
Explanation:
-
The iteration when
iis 3 is skipped, but the loop continues afterward.
Labels in JavaScript
Labels can be used with break or continue to jump out of or skip iterations in a named code block.
Syntax
Example – Break with Label
Output:
Explanation:
-
The
break listexits the labeled blocklist, skipping the rest of the code inside it.
✅ Key Points
-
break→ exits the loop or code block immediately. -
continue→ skips current iteration and continues with the loop. -
Labels allow targeted breaks or continues for nested loops or code blocks.
What is a Set?
A Set in JavaScript is a collection of unique values.
-
Each value can only appear once in a Set.
-
A Set can store any type of values: numbers, strings, objects, etc.
Creating a Set
1. From an Array
2. Empty Set and Using add()
3. Adding Variables
Set Methods
add()
Adds a value to the Set.
Duplicate values are ignored.
delete()
Removes a value from the Set.
has()
Checks if a value exists in the Set.
forEach()
Executes a callback for each Set element.
values()
Returns an iterator of all values in the Set.
Set Properties
size
Returns the number of elements in the Set.
✅ Key Points
-
Sets store unique values only.
-
Use
add()to add,delete()to remove, andhas()to check for values. -
Iteration can be done with
forEach(),for...of, orvalues()iterator.
JavaScript Maps
A Map is a collection of key-value pairs, where keys can be any datatype. Maps remember insertion order.
Creating Maps
Common Map Methods
| Method | Description |
|---|---|
set(key, value) |
Adds or updates a key-value pair |
get(key) |
Retrieves the value for a key |
delete(key) |
Removes a key-value pair |
has(key) |
Checks if a key exists |
forEach(callback) |
Executes a function for each key-value pair |
entries() |
Returns an iterator for [key, value] pairs |
size |
Returns number of elements |
Example
Objects vs Maps
| Feature | Object | Map |
|---|---|---|
| Iterable | No | Yes |
| Size | No | Yes (size) |
| Key Types | Strings/Symbols only | Any datatype |
| Key Order | Not guaranteed | Maintained |
| Defaults | Have default keys | None |
JavaScript Data Types
Primitive Types
-
string,number,boolean,undefined,null,symbol,bigint -
Single value, no methods (but wrappers exist).
Complex Types (Objects)
-
Object,Array,Date,Function, etc. -
Can hold multiple values and properties.
typeof Operator
Returns a string indicating the type:
constructor Property
Check object type:
Undefined vs Null
| Concept | Value | Type |
|---|---|---|
undefined |
Variable not assigned | undefined |
null |
Explicitly empty | object |
JavaScript Type Conversion
String ↔ Number
-
Unary
+operator converts to number:
Boolean ↔ Number
Dates ↔ Numbers/Strings
Automatic Type Conversion
JavaScript converts types automatically in operations:
JavaScript Errors Overview
JavaScript errors occur when something goes wrong during code execution. Common types:
-
Coding errors (syntax mistakes, wrong variable references)
-
Runtime errors (invalid operations, wrong input)
-
Custom errors (developer-defined using
throw)
try…catch…finally
Syntax
Example
-
try→ code to attempt -
catch(err)→ code to handle errors -
finally→ always runs
The throw Statement
Used to create custom errors.
Input Validation Example
Error Object
Every error in JS generates an Error object with:
-
name→ error type -
message→ descriptive message
Error Name Values
| Name | Description |
|---|---|
| EvalError | Error in eval() function |
| RangeError | Number out of range |
| ReferenceError | Illegal reference to a variable |
| SyntaxError | Code has a syntax mistake |
| TypeError | Value type mismatch |
| URIError | Invalid URI function usage |
Examples of Common Errors
Non-Standard Error Properties (browser-specific)
-
fileName,lineNumber,columnNumber,stack(Mozilla) -
description,number(Microsoft)
⚠️ Avoid these in production; not supported across all browsers.
1. What is Scope?
Scope determines where a variable, object, or function is accessible in your code.
JavaScript has three main types of scope:
-
Block Scope
-
Function Scope (Local Scope)
-
Global Scope
2. Block Scope
Introduced in ES6 with let and const.
-
Variables declared inside
{ }cannot be accessed outside the block.
-
vardoes not have block scope:
Key point: Always use let or const for block-scoped variables.
3. Function Scope (Local Scope)
Variables declared inside a function are local to that function.
-
Variables inside different functions can have the same name without conflict.
-
var,let, andconstall have function scope.
4. Global Scope
Variables declared outside any function or block are global.
-
Global variables can be accessed anywhere in your code.
-
In browsers, the global scope is the
windowobject:-
varvariables become properties ofwindow -
letandconstvariables do not attach towindow
-
Warning: Avoid creating unnecessary global variables—they can be overwritten.
5. Automatically Global
If you assign a value to a variable without declaring it, it becomes global (unless in strict mode):
⚠️ In Strict Mode, this behavior is prevented. Always declare variables explicitly.
6. Lifetime of Variables
-
Function (local) variables → deleted when the function finishes.
-
Global variables → exist until the browser tab/window is closed.
-
Function arguments → act as local variables inside the function.
✅ Key Tips:
-
Prefer
letandconstovervarfor predictable scoping. -
Limit the use of global variables to avoid conflicts.
-
Understand the lifetime of your variables to avoid memory issues or bugs.
1. What is Hoisting?
Hoisting is JavaScript’s default behavior of moving all declarations to the top of the current scope (script or function) during the compilation phase.
-
Only declarations are hoisted.
-
Initializations/assignments are not hoisted.
2. Hoisting with var
Variables declared with var are hoisted and initialized with undefined.
How JavaScript interprets it:
✅ You can use a var variable before it’s declared, but its value is undefined until initialization.
3. Hoisting with let and const
-
Variables declared with
letandconstare hoisted but not initialized. -
They are in a Temporal Dead Zone (TDZ) from the start of the block until the declaration is encountered.
-
Using them before declaration causes a
ReferenceError(constis a syntax error if uninitialized).
4. Hoisting and Initializations
Only the declaration is hoisted, not the value assignment:
-
yis declared due to hoisting, but its value is undefined until the assignment.
5. Best Practice
To avoid confusion and bugs caused by hoisting:
-
Always declare all variables at the top of their scope (function or block).
-
Prefer
letandconstovervarfor predictable scoping.
✅ Key Takeaways:
-
var→ hoisted and initialized toundefined. -
letandconst→ hoisted, but not initialized, TDZ applies. -
Declarations are hoisted, assignments are not.
-
Declare variables at the top of scope to prevent bugs.
1. What Are Arrow Functions?
Arrow functions were introduced in ES6 (2015) to provide a shorter syntax for writing functions.
2. Basic Syntax
Regular Function:
Arrow Function:
Shorter Syntax (Single Statement, Implicit Return):
✅ If the function has only one statement, you can omit {} and return.
3. Arrow Functions with Parameters
Multiple Parameters:
Single Parameter:
Parentheses are optional:
4. Handling this in Arrow Functions
The biggest difference between regular functions and arrow functions is how they handle this:
-
Regular functions:
thisrefers to the object that calls the function (window, button, etc.). -
Arrow functions:
thisrefers to the object that defined the function (lexical scope).
Example 1: Regular Function
Example 2: Arrow Function
✅ Takeaway: Use arrow functions when you want this to remain lexical (from the surrounding scope). Use regular functions when you want this to depend on the caller.
5. Summary of Benefits
-
Shorter syntax.
-
Implicit return for single-statement functions.
-
Lexical
thisbinding makes them ideal for callbacks and event handlers. -
Can simplify array methods (
map,filter,forEach):
1. JavaScript Classes (ES6)
Definition
Classes are templates for objects, introduced in ES6.
Syntax
Creating Objects
-
constructor()is automatically called when an object is created. -
Class methods can take parameters and use
thisto access object properties.
Example: Car Age
2. JSON (JavaScript Object Notation)
Definition
-
A lightweight data interchange format, language-independent.
-
Data is stored as name/value pairs.
Syntax Rules
-
Data is in name/value pairs:
"firstName":"John". -
Objects use
{}; Arrays use[]. -
Names must be in double quotes.
Example JSON
Converting JSON to JavaScript Object
3. JavaScript Style Guide
Variable Naming
-
Use camelCase for variables and functions:
firstName. -
Constants:
UPPERCASE:PI.
Spacing & Indentation
-
Use 2 spaces per indentation level.
-
Put spaces around operators:
let x = y + z;.
Statements
-
End simple statements with a semicolon.
-
Opening bracket for functions/loops: same line, closing bracket: new line.
Objects
-
Use colon + space:
firstName: "John". -
No comma after the last property.
-
Example:
Line Length
-
Keep lines < 80 characters.
-
Break after operators or commas if necessary.
File & HTML Conventions
-
HTML:
.html -
CSS:
.css -
JS:
.js -
Use lowercase file names for portability.
-
Be consistent with IDs and classes in HTML vs JavaScript.
1. Assignment vs Comparison
-
Mistake: Using
=instead of==or===inif.
-
Fix: Use
==(loose) or===(strict) for comparison.
2. Loose vs Strict Comparison
-
Loose:
==converts types before comparison. -
Strict:
===checks type and value.
-
Switch statements use strict comparison.
3. Addition vs Concatenation
-
+operator can add numbers or concatenate strings:
4. Floating Point Precision
-
JS uses 64-bit floats → precision errors:
-
Fix: Multiply/divide to handle decimals:
5. Breaking Strings
-
Can’t break a string mid-line without a backslash:
-
Incorrect:
6. Misplaced Semicolons
-
Semicolon after
iforforcan break logic:
7. Breaking return Statements
-
JavaScript auto-inserts semicolons at line breaks.
-
Fix: Keep
returnand expression on the same line:
8. Arrays with Named Indexes
-
JavaScript arrays use numeric indexes.
-
Use objects for named keys:
9. Trailing Commas
-
Allowed in ES5 objects/arrays, but breaks IE8 and JSON parsing:
10. undefined vs null
-
undefinedmeans variable/property not assigned. -
nullis an explicitly empty value. -
Safe check for object existence:
1. Reduce Activity in Loops
-
Accessing properties repeatedly inside loops slows performance.
2. Reduce DOM Access
-
Accessing the DOM is slow. Cache DOM references in a variable if you use them multiple times:
3. Reduce DOM Size
-
Smaller DOM → faster rendering and faster element searches.
-
Avoid unnecessary nested elements.
4. Avoid Unnecessary Variables
-
Don’t create variables if you don’t need to reuse values:
5. Delay JavaScript Loading
-
Scripts block parsing and downloading of other resources if loaded early.
-
Options:
-
Place scripts at the end of the body.
-
Use
deferfor external scripts:
-
Dynamically load scripts after page load:
-
6. Avoid Using with
-
withslows performance and can cause scope confusion. -
Not allowed in strict mode:
💡 Key idea: Minimize repeated work (loops, DOM access), reduce page parsing overhead, and follow strict mode rules for faster, cleaner JavaScript.
