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:

  1. HTML – defines page content

  2. CSS – styles and layouts

  3. 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

<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
  • document.write() – writes directly to the page (testing only)

<script>
document.write(5 + 6);
</script>
  • alert() – shows a popup

<script>
alert(5 + 6);
</script>
  • console.log() – logs output to the browser console

<script>
console.log(5 + 6);
</script>
  • window.print() – prints the current page

<button onclick="window.print()">Print this page</button>

JavaScript Statements

A program is a list of instructions (statements) executed by the browser.

let x = 5;
let y = 6;
let z = x + y;
  • 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:

function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are you?";
}

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.

// Change heading
document.getElementById("myH").innerHTML = "My First Page";

// Change paragraph
document.getElementById("myP").innerHTML = "My first paragraph.";

// You can also comment at the end of a line
let x = 5; // Declare x
let y = x + 2; // Declare y as x + 2


Multi-Line (Block) Comments

Start with /* and end with */. Everything in between is ignored.

/*
This code changes the heading
and paragraph on the web page
*/

document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";

Using Comments to Prevent Execution

You can disable code temporarily for testing:

// Single line disabled
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";

/* Multiple lines disabled
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
*/

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:

let x = 10; // = assigns a value
x += 5; // += adds value to x
x -= 3; // -= subtracts
x *= 2; // *= multiplies
x /= 4; // /= divides
x %= 3; // %= modulus (remainder)
x **= 2; // **= exponent

2. Arithmetic Operators

Perform arithmetic on numbers:

Operator Description
+ Addition
Subtraction
* Multiplication
/ Division
% Modulus (remainder)
** Exponentiation
++ Increment
Decrement
let a = 5, b = 2;
let sum = a + b; // 7
let product = a * b; // 10

3. String Operators

  • + concatenates strings

let text1 = "John";
let text2 = "Doe";
let text3 = text1 + " " + text2; // "John Doe"

let text = "Hello ";
text += "World"; // "Hello World"

  • Adding a number to a string converts the number to a string:

let x = 5 + 5; // 10
let y = "5" + 5; // "55"
let z = "Hello" + 5; // "Hello5"

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

let x = 5;
let y = 2;
let z = x + y; // 7

Subtraction

let z = x - y; // 3

Multiplication

let z = x * y; // 10

Division

let z = x / y; // 2.5

Remainder (modulus)

let z = x % y; // 1

Increment / Decrement

x++; // x = x + 1
x--; // x = x - 1

Exponentiation

let z = x ** 2; // 25
let z2 = Math.pow(x,2); // 25

Operator Precedence

Precedence determines the order operations are performed (like in math).

  • Multiplication/division have higher precedence than addition/subtraction.

  • Parentheses () override precedence.

let x = 100 + 50 * 3; // 250 (multiplication first)
let y = (100 + 50) * 3; // 450 (parentheses first)
let z = 100 + 50 - 3; // 147 (left to right)

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 (=)

let x = 10; // assign 10 to x

Addition assignment (+=)

let x = 10;
x += 5; // x = 15

Subtraction assignment (-=)

let x = 10;
x -= 5; // x = 5

Multiplication assignment (*=)

let x = 10;
x *= 5; // x = 50

Division assignment (/=)

let x = 10;
x /= 5; // x = 2

Remainder assignment (%=)

let x = 10;
x %= 5; // x = 0


JavaScript Data Types

JavaScript variables can hold different types of data: numbers, strings, objects, arrays, and more.

let length = 16; // Number
let lastName = "Johnson"; // String
let x = {firstName:"John", lastName:"Doe"}; // Object

Dynamic Types

JavaScript is dynamically typed, meaning the same variable can hold different types:

let x; // undefined
x = 5; // Number
x = "John"; // String

Strings

Strings are sequences of characters, enclosed in single or double quotes:

let car1 = "Volvo XC60"; // double quotes
let car2 = 'Volvo XC60'; // single quotes
  • Quotes inside a string must differ from the surrounding quotes:

let answer1 = "It's alright";
let answer2 = 'He is called "Johnny"';

Numbers

JavaScript has one number type (integers and floats).

let x1 = 34.00; // with decimals
let x2 = 34; // without decimals
  • Scientific notation:

let y = 123e5; // 12300000
let z = 123e-5; // 0.00123

Booleans

Booleans have only true or false values, often used in conditions:

let x = 5, y = 5, z = 6;
x == y // true
x == z // false

Arrays

Arrays store multiple values, using square brackets:

const cars = ["Saab", "Volvo", "BMW"];
// Indexes start at 0

Objects

Objects store key:value pairs, using curly braces:

const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

The typeof Operator

Use typeof to check a variable’s type:

typeof "John" // "string"
typeof 3.14 // "number"
typeof (3 + 4) // "number"

Undefined

A variable without a value is undefined:

let car; // value and type are undefined
car = undefined; // same

Empty Values

An empty string has a value and a type:

let car = ""; // value is "", type is "string"


JavaScript Functions

A function is a block of code designed to perform a task. It runs only when called (invoked).


Function Syntax

function name(parameter1, parameter2) {
// code to execute
return value; // optional
}
  • Parameters: placeholders listed in parentheses.

  • Arguments: values passed to the function when called.

  • Inside a function, parameters act as local variables.


Example: Multiplication

function myFunction(a, b) {
return a * b; // returns the product
}

let x = myFunction(4, 3); // x = 12


Why Use Functions?

  • Reuse code without rewriting.

  • Use different arguments to produce different results.

function toCelsius(f) {
return (5/9) * (f - 32);
}

document.getElementById("demo").innerHTML = toCelsius(77); // 25

  • Using toCelsius (without ()) refers to the function object.

  • Using toCelsius() returns the function result.


Functions as Values

Functions can be used directly in expressions:

let text = "The temperature is " + toCelsius(77) + " Celsius";

Local Variables

Variables declared inside a function are local and cannot be accessed outside:

function myFunction() {
let carName = "Volvo"; // local variable
}
// carName cannot be used here


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:

const car = {type: "Fiat", model: "500", color: "white"};

const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};

  • Spaces and line breaks don’t matter.


Object Properties

  • Properties are the named values inside an object.

person.firstName; // "John"
person["lastName"]; // "Doe"

Object Methods

  • Methods are functions stored as properties:

const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};

person.fullName(); // "John Doe"

  • this refers to the current object.

    • this.firstNameperson.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:

<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button>

<button onclick="this.innerHTML = Date()">The time is?</button>

  • this.innerHTML refers to the element itself.


Calling Functions with Events

Instead of writing code inline, you can call a function:

<button onclick="displayDate()">The time is?</button>

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:

let text = "John Doe"; // double quotes
let carName1 = "Volvo XC60"; // double quotes
let carName2 = 'Volvo XC60'; // single quotes
  • Quotes inside a string must differ from the surrounding quotes:

let answer1 = "It's alright";
let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';

String Length

Use the length property:

let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length; // 26

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:

let text1 = "We are the so-called \"Vikings\" from the north.";
let text2 = 'It\'s alright.';
let text3 = "The character \\ is called backslash.";

Breaking Long Strings

  • Prefer string addition over \ for readability:

document.getElementById("demo").innerHTML =
"Hello " + "Dolly!";
  • Avoid using \ at the end of a line; it may not work in all browsers.


Strings as Objects

  • Normally, strings are primitive values:

let x = "John";
  • You can create string objects with new (not recommended):

let y = new String("John");
  • Comparison difference:

let x = "John";
let y = new String("John");

x == y; // true
x === y; // false

  • Comparing two string objects always returns false with ===:

let x = new String("John");
let y = new String("John");

x === y; // false

⚠️ 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.

let str = "Please locate where 'locate' occurs!";
str.indexOf("locate"); // 7
str.indexOf("locate", 15); // 21 (start searching from index 15)

2. lastIndexOf()

Returns the index of the last occurrence of a substring. Returns -1 if not found.

let str = "Please locate where 'locate' occurs!";
str.lastIndexOf("locate"); // 21
str.lastIndexOf("locate", 15); // 7 (searches backwards from index 15)

3. search()

Searches for a substring (or regex) and returns the position. Cannot take a starting index.

let str = "Please locate where 'locate' occurs!";
str.search("locate"); // 7

Difference: search() supports regular expressions, indexOf() supports start position.


4. match()

Searches a string against a regular expression and returns matches as an array.

let text = "The rain in SPAIN stays mainly in the plain";
text.match(/ain/g); // ["ain", "ain", "ain", "ain"]
text.match(/ain/gi); // ["ain", "AIN", "ain", "ain"] (case-insensitive)

5. includes()

Returns true if a string contains a substring, false otherwise.

let text = "Hello world, welcome to the universe.";
text.includes("world"); // true
text.includes("world", 12); // false (start searching at index 12)

6. startsWith()

Returns true if a string begins with a substring. Case-sensitive.

let text = "Hello world, welcome to the universe.";
text.startsWith("Hello"); // true
text.startsWith("world"); // false
text.startsWith("world", 6); // true (start checking from index 6)

7. endsWith()

Returns true if a string ends with a substring. Case-sensitive.

let text = "John Doe";
text.endsWith("Doe"); // true

let text2 = "Hello world, welcome to the universe.";
text2.endsWith("world", 11); // true (check first 11 characters)



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.

let txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = txt.length; // 26

2. Extracting String Parts

a) slice(start, end)

Extracts a part of a string; end not included. Negative values count from the end.

let str = "Apple, Banana, Kiwi";
str.slice(7, 13); // "Banana"
str.slice(-12, -6); // "Banana"
str.slice(7); // "Banana, Kiwi"

b) substring(start, end)

Similar to slice(), but negative values are treated as 0.

str.substring(7, 13); // "Banana"

c) substr(start, length)

Second parameter is length of extracted part. Negative start counts from end.

str.substr(7, 6); // "Banana"
str.substr(-4); // "Kiwi"

3. Replacing Content

replace()

Replaces a value with another. Returns a new string. By default: first match, case-sensitive.

let text = "Please visit Microsoft!";
text.replace("Microsoft", "apostube"); // "Please visit apostube!"
text.replace(/MICROSOFT/i, "apostube"); // Case-insensitive
text.replace(/Microsoft/g, "apostube"); // Replace all occurrences

4. Changing Case

let text = "Hello World!";
text.toUpperCase(); // "HELLO WORLD!"
text.toLowerCase(); // "hello world!"

5. Concatenation

concat()

Joins two or more strings. Equivalent to + operator.

let text1 = "Hello";
let text2 = "World";
text1.concat(" ", text2); // "Hello World"

6. Trimming Whitespace

trim()

Removes whitespace from both sides.

let text = " Hello World! ";
text.trim(); // "Hello World!"

7. Padding Strings (ES2017+)

padStart(targetLength, padString)

Pads string at the start.

let text = "5";
text.padStart(4, "0"); // "0005"

padEnd(targetLength, padString)

Pads string at the end.

text.padEnd(4, "0"); // "5000"

8. Extracting Characters

charAt(index)

Returns character at index.

let text = "HELLO";
text.charAt(0); // "H"

charCodeAt(index)

Returns Unicode value (UTF-16) at index.

text.charCodeAt(0); // 72

Property access [ ]

Access like array (read-only). Returns undefined if index invalid.

text[0]; // "H"
text[0] = "A"; // Does nothing

9. Converting String to Array

split(separator)

Splits a string into an array based on a separator.

let text = "Apple, Banana, Kiwi";
text.split(","); // ["Apple", " Banana", " Kiwi"]
text.split(" "); // ["Apple,", "Banana,", "Kiwi"]
text.split(""); // ["A","p","p","l","e",...]


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

let text = `Hello World!`;
  • Use “ instead of " " or ' '.

  • Allows both single and double quotes inside the string without escaping.

let text = `He's often called "Johnny"`;

2. Multiline Strings

Template literals allow strings to span multiple lines:

let text = `The quick
brown fox
jumps over
the lazy dog`
;

No need for \n or string concatenation.


3. String Interpolation

Template literals support variable and expression substitution using ${...}.

a) Variable Substitution

let firstName = "John";
let lastName = "Doe";

let text = `Welcome ${firstName}, ${lastName}!`;
// "Welcome John, Doe!"

  • Automatic replacement of variables with their values is called string interpolation.

b) Expression Substitution

let price = 10;
let VAT = 0.25;

let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`;
// "Total: 12.50"

  • You can include any JavaScript expression inside ${...}.


4. HTML Templates

Template literals are useful for building HTML dynamically:

let header = "Template Literals";
let tags = ["template literals", "javascript", "es6"];

let html = `<h2>${header}</h2><ul>`;
for (const x of tags) {
html += `<li>${x}</li>`;
}
html += `</ul>`;

  • Produces a complete HTML string using variables and loops.


Advantages of Template Literals:

  1. Easier to read and write multiline strings.

  2. Avoids string concatenation (+) for variables.

  3. Supports embedding expressions directly.

  4. 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

let x = 3.14; // Decimal number
let y = 3; // Integer number

Scientific Notation

let x = 123e5; // 12300000
let y = 123e-5; // 0.00123

2. Precision

  • Integers are accurate up to 15 digits:

let x = 999999999999999; // 15 digits → accurate
let y = 9999999999999999; // 16 digits → rounded
  • Floating point arithmetic may have small errors:

let x = 0.2 + 0.1; // 0.30000000000000004
  • Workaround:

let x = (0.2 * 10 + 0.1 * 10) / 10; // 0.3

3. Adding Numbers and Strings

  • + adds numbers or concatenates strings:

let x = 10, y = 20;
let z = x + y; // 30

let a = 10, b = "20";
let c = a + b; // "1020"

  • Left-to-right evaluation matters:

let x = 10, y = 20, z = "30";
let result = x + y + z; // 3030

4. Numeric Strings

JavaScript tries to convert strings to numbers for arithmetic operations:

let x = "100", y = "10";

let sum = x / y; // 10
let mul = x * y; // 1000
let sub = x - y; // 90
let add = x + y; // "10010" (concatenation!)


5. NaN – Not a Number

  • Result of illegal numeric operations:

let x = 100 / "Apple"; // NaN
  • isNaN() checks if a value is NaN:

isNaN(x); // true
  • Note: typeof NaN returns "number".


6. Infinity

  • Calculations beyond the largest number, or division by 0:

let x = 2 / 0; // Infinity
let y = -2 / 0; // -Infinity
typeof Infinity; // "number"

7. Hexadecimal Numbers

  • Prefix with 0x:

let x = 0xFF; // 255
  • Convert numbers to different bases:

let num = 32;
num.toString(2); // "100000" (binary)
num.toString(8); // "40" (octal)
num.toString(10); // "32" (decimal)
num.toString(16); // "20" (hexadecimal)

8. Numbers as Objects

  • Primitive numbers:

let x = 123;
  • Number objects (not recommended):

let y = new Number(123);
  • Comparison:

x == y; // true
x === y; // false
  • Two Number objects:

let a = new Number(500), b = new Number(500);
a === b; // false

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.

let x = 123;
x.toString(); // "123"
(123).toString(); // "123"
(100 + 23).toString(); // "123"

2. toExponential()

Converts a number to exponential notation. Optional parameter defines decimals.

let x = 9.656;
x.toExponential(); // "9.656e+0"
x.toExponential(2); // "9.66e+0"
x.toExponential(4); // "9.6560e+0"
x.toExponential(6); // "9.656000e+0"

3. toFixed()

Formats a number with a fixed number of decimals.

let x = 9.656;
x.toFixed(0); // "10"
x.toFixed(2); // "9.66"
x.toFixed(4); // "9.6560"
x.toFixed(6); // "9.656000"

Great for working with money.


4. toPrecision()

Formats a number with a specified total length.

let x = 9.656;
x.toPrecision(); // "9.656"
x.toPrecision(2); // "9.7"
x.toPrecision(4); // "9.656"
x.toPrecision(6); // "9.65600"

5. valueOf()

Returns the primitive number value of a Number object.

let x = 123;
x.valueOf(); // 123
(123).valueOf(); // 123
(100 + 23).valueOf(); // 123

Usually used internally; rarely needed in code.


Converting Variables to Numbers

Three global methods are used:

  1. Number()

  2. parseInt()

  3. parseFloat()


1. Number()

Converts a value to a number.

Number(true); // 1
Number(false); // 0
Number("10"); // 10
Number(" 10 "); // 10
Number("10.33"); // 10.33
Number("10,33"); // NaN
Number("10 33"); // NaN
Number("John"); // NaN

Number() with Dates

Returns milliseconds since 1970-01-01:

Number(new Date("1970-01-01")); // 0
Number(new Date("1970-01-02")); // 86400000
Number(new Date("2017-09-30")); // 1506720000000

2. parseInt()

Parses a string and returns an integer:

parseInt("-10"); // -10
parseInt("-10.33"); // -10
parseInt("10"); // 10
parseInt("10.33"); // 10
parseInt("10 20 30"); // 10
parseInt("10 years"); // 10
parseInt("years 10"); // NaN

3. parseFloat()

Parses a string and returns a floating-point number:

parseFloat("10"); // 10
parseFloat("10.33"); // 10.33
parseFloat("10 20 30"); // 10
parseFloat("10 years"); // 10
parseFloat("years 10"); // NaN

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:

Number.MAX_VALUE; // 1.7976931348623157e+308
Number.MIN_VALUE; // 5e-324
Number.POSITIVE_INFINITY; // Infinity
Number.NEGATIVE_INFINITY; // -Infinity
Number.NaN; // NaN

Note: Number properties belong to the Number object itself.
Using myNumber.MAX_VALUE will return undefined:

let x = 6;
x.MAX_VALUE; // undefined


JavaScript Date Objects

JavaScript Date objects are used to work with dates and times.

const d = new Date(); // current date and time

1. Creating Date Objects

a) new Date()

Creates a date object with current date and time.

const d = new Date();

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:

const d = new Date(2018, 11, 24, 10, 33, 30, 0);
const d2 = new Date(2018, 15, 24, 10, 33, 30); // automatically adjusts year/month
const d3 = new Date(2018, 5, 35, 10, 33, 30); // automatically adjusts day/month

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:

new Date(99, 11, 24); // 1999-12-24
new Date(9, 11, 24); // 1909-12-24

c) new Date(dateString)

Creates a date object from a date string:

const d = new Date("October 13, 2014 11:13:00");

d) new Date(milliseconds)

Creates a date object as milliseconds since 01 Jan 1970 00:00:00 UTC:

const d = new Date(0); // 1970-01-01
const d2 = new Date(100000000000); // ~1973-03-03
const d3 = new Date(-100000000000); // ~1966-10-31
const d4 = new Date(86400000); // 1 day later

One day = 86,400,000 milliseconds.


2. Displaying Dates

By default, Date objects display as full text strings:

const d = new Date();
d.toString(); // "Tue Jun 14 2022 14:51:25 GMT+0300 (EEST)"

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:

const d = new Date("2015-03-25");
  • ISO 8601 standard is strictly defined and preferred.

  • Can also specify only year and month, or only year:

const d1 = new Date("2015-03"); // year + month
const d2 = new Date("2015"); // only year
  • Can include time:

const d3 = new Date("2015-03-25T12:00:00Z"); // UTC
const d4 = new Date("2015-03-25T12:00:00-06:30"); // Offset from UTC

b) Short Date

  • Format: "MM/DD/YYYY"

  • Example:

const d = new Date("03/25/2015");
  • Warnings:

    • Some browsers may fail if leading zeros are missing: "2015-3-25"

    • "YYYY/MM/DD" is not standard, may return NaN.

    • "DD-MM-YYYY" is also undefined in some browsers.


c) Long Date

  • Formats: "MMM DD YYYY" or "DD MMM YYYY"

  • Examples:

const d1 = new Date("Mar 25 2015");
const d2 = new Date("25 Mar 2015");
const d3 = new Date("January 25 2015");
const d4 = new Date("Jan 25 2015");
  • Commas are ignored; month names are case-insensitive:

const d = new Date("JANUARY, 25, 2015");

2. Time Zones

  • By default, JavaScript uses the browser’s local time zone.

  • UTC time can be specified with Z or +/-HH:MM in 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:

const d = new Date();
d.toString(); // Tue Jun 14 2022 14:51:25 GMT+0300 (EEST)

4. Parsing Dates

  • Use Date.parse() to convert a date string to milliseconds since January 1, 1970:

let msec = Date.parse("March 21, 2012");
const d = new Date(msec);
  • This is useful for calculations or converting to a Date object.


Best Practices:

  1. Prefer ISO 8601 format (YYYY-MM-DD or YYYY-MM-DDTHH:MM:SSZ).

  2. Avoid browser-dependent short or long formats for reliability.

  3. 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

// Get month as a name
const months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
const d = new Date();
let monthName = months[d.getMonth()]; // e.g., "November"

// Get weekday as a name
const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
let dayName = days[d.getDay()]; // e.g., "Monday"

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.PI; // Access constants directly

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
Math.round(4.6); // 5
Math.ceil(4.2); // 5
Math.floor(4.7); // 4
Math.trunc(-4.7); // -4
Math.sign(-10); // -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
Math.pow(2, 3); // 8
Math.sqrt(64); // 8
Math.cbrt(27); // 3

Absolute Value

Method Description
Math.abs(x) Absolute (positive) value
Math.abs(-5.7); // 5.7

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
Math.sin(90 * Math.PI / 180); // 1
Math.cos(0 * Math.PI / 180); // 1

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
Math.min(0, 150, -200); // -200
Math.max(0, 150, -200); // 150
Math.random(); // 0.0–0.999…

Logarithms

Method Description
Math.log(x) Natural logarithm (base E)
Math.log2(x) Base-2 logarithm
Math.log10(x) Base-10 logarithm
Math.log(1); // 0
Math.log2(8); // 3
Math.log10(1000); // 3

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):

Math.random(); // 0 ≤ x < 1
  • 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):

function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
  • Example: getRndInteger(1, 10) → 1–9


2️⃣ Random integer between min and max (both included):

function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
  • 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

for (statement1; statement2; statement3) {
// code block
}
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

for (let i = 0; i < 5; i++) {
console.log("The number is " + i);
}
  • i = 0 → start

  • i < 5 → continue looping

  • i++ → increase i by 1 after each loop

Output:

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4

Advanced for Syntax

1️⃣ Multiple initializations:

for (let i = 0, len = cars.length; i < len; i++) {
console.log(cars[i]);
}

2️⃣ Omitting statement1 (variables defined before the loop):

let i = 2;
for (; i < cars.length; i++) {
console.log(cars[i]);
}

3️⃣ Omitting statement3 (increment inside the loop):

let i = 0;
for (; i < cars.length;) {
console.log(cars[i]);
i++;
}

4️⃣ Omitting statement2 (requires break to avoid infinite loop):

for (;;) {
// infinite loop unless you break
break;
}

Variable Scope in Loops

  • Using var:

var i = 5;
for (var i = 0; i < 10; i++) {
// some code
}
console.log(i); // 10 (loop variable overwrites outer i)
  • Using let:

let i = 5;
for (let i = 0; i < 10; i++) {
// some code
}
console.log(i); // 5 (loop variable is block-scoped)

Tip: Always use let for 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

for (key in object) {
// code using object[key]
}

Example – Object

const person = {fname: "John", lname: "Doe", age: 25};

let text = "";
for (let key in person) {
text += person[key] + " ";
}

console.log(text); // "John Doe 25 "

Explanation:

  • key → each property name (fname, lname, age)

  • person[key] → accesses the value of the property


For for…in Over Arrays

const numbers = [45, 4, 9, 16, 25];

let txt = "";
for (let index in numbers) {
txt += numbers[index] + " ";
}

console.log(txt); // "45 4 9 16 25 "

⚠️ Warning: The order of indices is not guaranteed. Use for or for…of if order matters.


Array.forEach() Alternative

const numbers = [45, 4, 9, 16, 25];

let txt = "";
numbers.forEach(function(value, index, array) {
txt += value + " ";
});
console.log(txt); // "45 4 9 16 25 "

  • Takes 3 arguments: value, index, array

  • You can use just the value if needed:

numbers.forEach(value => txt += value + " ");

JavaScript for…of Loop

The for…of loop iterates over the values of iterable objects like arrays, strings, maps, sets, and more.

Syntax

for (variable of iterable) {
// code using variable
}
  • 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

const cars = ["BMW", "Volvo", "Mini"];

let text = "";
for (let car of cars) {
text += car + " ";
}

console.log(text); // "BMW Volvo Mini "


Example – String

let language = "JavaScript";

let text = "";
for (let char of language) {
text += char + " ";
}

console.log(text); // "J a v a S c r i p t "


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

while (condition) {
// code block to be executed
}

Example

let i = 0;
let text = "";

while (i < 10) {
text += "The number is " + i + "\n";
i++;
}

console.log(text);

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

do {
// code block to be executed
} while (condition);

Example

let i = 0;
let text = "";

do {
text += "The number is " + i + "\n";
i++;
} while (i < 10);

console.log(text);

Key difference:

  • The code always runs at least once, even if the condition is false.


Comparing for, while, and do…while

  • for loop: Good when the number of iterations is known.

  • while loop: Good when the number of iterations is unknown, and the loop depends on a condition.

  • do…while loop: Ensures at least one execution before checking the condition.

Collecting Array Elements Example

Using for loop:

const cars = ["BMW", "Volvo", "Saab", "Ford"];
let i = 0;
let text = "";

for (; cars[i]; ) {
text += cars[i] + " ";
i++;
}

console.log(text); // BMW Volvo Saab Ford

Using while loop:

const cars = ["BMW", "Volvo", "Saab", "Ford"];
let i = 0;
let text = "";

while (cars[i]) {
text += cars[i] + " ";
i++;
}

console.log(text); // BMW Volvo Saab Ford

Observation:

  • while and for can 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

break;

Example – Exiting a Loop

let text = "";
for (let i = 0; i < 10; i++) {
if (i === 3) {
break; // stops the loop when i is 3
}
text += "The number is " + i + "\n";
}

console.log(text);

Output:

The number is 0
The number is 1
The number is 2

Explanation:

  • When i equals 3, the break statement immediately ends the loop.


Continue Statement

The continue statement skips the current iteration and moves to the next iteration of the loop.

Syntax

continue;

Example – Skipping an Iteration

let text = "";
for (let i = 0; i < 10; i++) {
if (i === 3) {
continue; // skips the rest of this iteration when i is 3
}
text += "The number is " + i + "\n";
}

console.log(text);

Output:

The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9

Explanation:

  • The iteration when i is 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

labelName: {
// code block
break labelName; // exit code block
continue labelName; // skip to next iteration of a loop
}

Example – Break with Label

let text = "";
const cars = ["BMW", "Volvo", "Saab", "Ford"];

list: {
text += cars[0] + "\n";
text += cars[1] + "\n";
break list; // jumps out of the labeled block
text += cars[2] + "\n"; // not executed
text += cars[3] + "\n"; // not executed
}

console.log(text);

Output:

BMW
Volvo

Explanation:

  • The break list exits the labeled block list, 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

const letters = new Set(["a", "b", "c"]);
console.log(letters); // Set(3) {"a", "b", "c"}

2. Empty Set and Using add()

const letters = new Set();
letters.add("a");
letters.add("b");
letters.add("c");
console.log(letters); // Set(3) {"a", "b", "c"}

3. Adding Variables

const letters = new Set();
const a = "a", b = "b", c = "c";

letters.add(a);
letters.add(b);
letters.add(c);
console.log(letters); // Set(3) {"a", "b", "c"}


Set Methods

add()

Adds a value to the Set.
Duplicate values are ignored.

letters.add("d");
letters.add("e");
letters.add("a"); // already exists, ignored

delete()

Removes a value from the Set.

letters.delete("b");
console.log(letters); // Set {"a", "c", "d", "e"}

has()

Checks if a value exists in the Set.

console.log(letters.has("a")); // true
console.log(letters.has("b")); // false

forEach()

Executes a callback for each Set element.

let text = "";
letters.forEach(function(value) {
text += value + " ";
});
console.log(text); // "a c d e "

values()

Returns an iterator of all values in the Set.

const iterator = letters.values();
console.log(iterator); // [object Set Iterator]

// Using the iterator
let text = "";
for (const x of iterator) {
text += x + " ";
}
console.log(text); // "a c d e "


Set Properties

size

Returns the number of elements in the Set.

console.log(letters.size); // 4

Key Points

  • Sets store unique values only.

  • Use add() to add, delete() to remove, and has() to check for values.

  • Iteration can be done with forEach(), for...of, or values() iterator.



JavaScript Maps

A Map is a collection of key-value pairs, where keys can be any datatype. Maps remember insertion order.

Creating Maps

// From an array
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);

// Empty map + set() method
const fruits = new Map();
fruits.set("apples", 500);
fruits.set("bananas", 300);
fruits.set("oranges", 200);

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

fruits.set("apples", 200); // updates value
console.log(fruits.get("apples")); // 200
console.log(fruits.size); // number of entries
fruits.delete("apples"); // removes key
console.log(fruits.has("apples")); // false

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:

typeof "John"; // "string"
typeof 3.14; // "number"
typeof NaN; // "number"
typeof true; // "boolean"
typeof [1,2,3]; // "object"
typeof {a:1}; // "object"
typeof new Date(); // "object"
typeof function(){}; // "function"
typeof undefined; // "undefined"
typeof null; // "object" (bug in JS)

constructor Property

Check object type:

[].constructor === Array; // true
(new Date()).constructor === Date; // true
({}).constructor === Object; // true

Undefined vs Null

Concept Value Type
undefined Variable not assigned undefined
null Explicitly empty object
let x; // undefined
let y = null; // null
x == y; // true
x === y; // false

JavaScript Type Conversion

String ↔ Number

Number("3.14"); // 3.14
Number(""); // 0
Number("abc"); // NaN

String(123); // "123"
(123).toString(); // "123"

  • Unary + operator converts to number:

let x = "5";
let y = +x; // 5

Boolean ↔ Number

Number(true); // 1
Number(false); // 0
String(true); // "true"
String(false); // "false"

Dates ↔ Numbers/Strings

let d = new Date();
Number(d); // milliseconds since 1970
d.getTime(); // same as Number(d)
String(d); // "Thu Nov 14 2025 14:51:25 GMT+0300"
d.toString(); // same as above

Automatic Type Conversion

JavaScript converts types automatically in operations:

5 + null; // 5
"5" + null; // "5null"
"5" - 2; // 3
"5" * "2"; // 10


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

try {
// Code to try
}
catch(err) {
// Code to handle errors
}
finally {
// Code to run regardless of try/catch outcome
}

Example

try {
adddlert("Welcome!"); // deliberate typo
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
finally {
console.log("This runs no matter what");
}
  • try → code to attempt

  • catch(err) → code to handle errors

  • finally → always runs


The throw Statement

Used to create custom errors.

throw "Too big"; // throw a string
throw 500; // throw a number
throw true; // throw a boolean
throw {message: "Error"}; // throw an object

Input Validation Example

let x = document.getElementById("demo").value;

try {
if(x === "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {
document.getElementById("p01").innerHTML = "Input is " + err;
}


Error Object

Every error in JS generates an Error object with:

  • name → error type

  • message → descriptive message

try {
undefinedFunction();
}
catch(err) {
console.log(err.name); // e.g., ReferenceError
console.log(err.message); // description
}

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

// RangeError
try { (1).toPrecision(500); }
catch(err) { console.log(err.name); } // "RangeError"

// ReferenceError
let x = 5;
try { x = y + 1; }
catch(err) { console.log(err.name); } // "ReferenceError"

// SyntaxError
try { eval("alert('Hello)"); }
catch(err) { console.log(err.name); } // "SyntaxError"

// TypeError
try { (1).toUpperCase(); }
catch(err) { console.log(err.name); } // "TypeError"

// URIError
try { decodeURI("%%%"); }
catch(err) { console.log(err.name); } // "URIError"


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:

  1. Block Scope

  2. Function Scope (Local Scope)

  3. Global Scope


2. Block Scope

Introduced in ES6 with let and const.

  • Variables declared inside { } cannot be accessed outside the block.

{
let x = 2;
}
// x is NOT accessible here
  • var does not have block scope:

{
var y = 2;
}
// y IS accessible here

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.

function myFunction() {
let carName = "Volvo"; // local variable
console.log(carName); // works
}

console.log(carName); // Error: carName is not defined

  • Variables inside different functions can have the same name without conflict.

  • var, let, and const all have function scope.


4. Global Scope

Variables declared outside any function or block are global.

let carName = "Volvo"; // global variable

function myFunction() {
console.log(carName); // accessible here
}

console.log(carName); // accessible here

  • Global variables can be accessed anywhere in your code.

  • In browsers, the global scope is the window object:

    • var variables become properties of window

    • let and const variables do not attach to window

var a = 1;
let b = 2;

console.log(window.a); // 1
console.log(window.b); // undefined

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):

function myFunction() {
carName = "Volvo"; // automatically global
}

myFunction();
console.log(carName); // "Volvo"

⚠️ 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 let and const over var for 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.

console.log(x); // undefined
var x = 5;

How JavaScript interprets it:

var x; // declaration hoisted
console.log(x); // undefined
x = 5; // initialization stays in place

✅ 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 let and const are 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 (const is a syntax error if uninitialized).

console.log(a); // ReferenceError
let a = 10;
console.log(b); // ReferenceError
const b = 20;

4. Hoisting and Initializations

Only the declaration is hoisted, not the value assignment:

var x = 5;
var y = 7;

console.log(x, y); // 5 7

// vs
var x = 5;
console.log(x, y); // 5 undefined
var y = 7;

  • y is 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 let and const over var for predictable scoping.

function example() {
let x;
const y = 10;
// use variables here
}

Key Takeaways:

  1. var → hoisted and initialized to undefined.

  2. let and const → hoisted, but not initialized, TDZ applies.

  3. Declarations are hoisted, assignments are not.

  4. 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:

hello = function() {
return "Hello World!";
}

Arrow Function:

hello = () => {
return "Hello World!";
}

Shorter Syntax (Single Statement, Implicit Return):

hello = () => "Hello World!";

✅ If the function has only one statement, you can omit {} and return.


3. Arrow Functions with Parameters

Multiple Parameters:

let multiply = (a, b) => a * b;

Single Parameter:

Parentheses are optional:

hello = val => "Hello " + val;

4. Handling this in Arrow Functions

The biggest difference between regular functions and arrow functions is how they handle this:

  • Regular functions:
    this refers to the object that calls the function (window, button, etc.).

  • Arrow functions:
    this refers to the object that defined the function (lexical scope).


Example 1: Regular Function

hello = function() {
console.log(this);
}

window.addEventListener("load", hello); // 'this' is window
document.getElementById("btn").addEventListener("click", hello); // 'this' is button

Example 2: Arrow Function

hello = () => {
console.log(this);
}

window.addEventListener("load", hello); // 'this' is the owner (window)
document.getElementById("btn").addEventListener("click", hello); // 'this' is still the owner (window)

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

  1. Shorter syntax.

  2. Implicit return for single-statement functions.

  3. Lexical this binding makes them ideal for callbacks and event handlers.

  4. Can simplify array methods (map, filter, forEach):

const numbers = [1,2,3];
const doubled = numbers.map(n => n * 2); // [2,4,6]


1. JavaScript Classes (ES6)

Definition

Classes are templates for objects, introduced in ES6.

Syntax

class ClassName {
constructor(parameters) {
// initialization code
}

method1() { ... }
method2() { ... }
}

Creating Objects

let myCar = new Car("Ford", 2014);
  • constructor() is automatically called when an object is created.

  • Class methods can take parameters and use this to access object properties.

Example: Car Age

class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}

age(currentYear) {
return currentYear - this.year;
}
}

let myCar = new Car("Ford", 2014);
let year = new Date().getFullYear();
console.log("My car is " + myCar.age(year) + " years old.");


2. JSON (JavaScript Object Notation)

Definition

  • A lightweight data interchange format, language-independent.

  • Data is stored as name/value pairs.

Syntax Rules

  1. Data is in name/value pairs: "firstName":"John".

  2. Objects use {}; Arrays use [].

  3. Names must be in double quotes.

Example JSON

{
"employees": [
{"firstName":"John","lastName":"Doe"},
{"firstName":"Anna","lastName":"Smith"},
{"firstName":"Peter","lastName":"Jones"}
]
}

Converting JSON to JavaScript Object

let text = '{ "employees": [ {"firstName":"John","lastName":"Doe"} ]}';
const obj = JSON.parse(text);
console.log(obj.employees[0].firstName); // John

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:

const person = {
firstName: "John",
lastName: "Doe",
age: 50
};

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 === in if.

let x = 0;
if (x = 10) { console.log("Oops!"); } // Runs because assignment returns 10 (truthy)
  • Fix: Use == (loose) or === (strict) for comparison.

if (x === 10) { console.log("Correct"); }

2. Loose vs Strict Comparison

  • Loose: == converts types before comparison.

  • Strict: === checks type and value.

10 == "10"; // true
10 === "10"; // false
  • Switch statements use strict comparison.

let x = 10;
switch(x) {
case "10": console.log("Won't run");
}

3. Addition vs Concatenation

  • + operator can add numbers or concatenate strings:

let a = 10 + 5; // 15
let b = 10 + "5"; // "105"

4. Floating Point Precision

  • JS uses 64-bit floats → precision errors:

0.1 + 0.2; // 0.30000000000000004
  • Fix: Multiply/divide to handle decimals:

let z = (0.1 * 10 + 0.2 * 10) / 10; // 0.3

5. Breaking Strings

  • Can’t break a string mid-line without a backslash:

let s = "Hello \
World"
; // Works
  • Incorrect:

let s = "Hello
World"
; // SyntaxError

6. Misplaced Semicolons

  • Semicolon after if or for can break logic:

if(x == 19); { console.log("runs anyway"); }

7. Breaking return Statements

  • JavaScript auto-inserts semicolons at line breaks.

function f() {
return
5; // Returns undefined!
}
  • Fix: Keep return and expression on the same line:

return 5;

8. Arrays with Named Indexes

  • JavaScript arrays use numeric indexes.

const arr = [];
arr["name"] = "John"; // Redefines as object
arr.length; // 0, not 1
  • Use objects for named keys:

const person = {firstName: "John", lastName: "Doe"};

9. Trailing Commas

  • Allowed in ES5 objects/arrays, but breaks IE8 and JSON parsing:

let arr = [1,2,3,]; // Avoid trailing comma
let obj = {a:1,b:2,}; // Avoid trailing comma

10. undefined vs null

  • undefined means variable/property not assigned.

  • null is an explicitly empty value.

  • Safe check for object existence:

if (typeof myObj !== "undefined" && myObj !== null) {
// safe to use myObj
}


1. Reduce Activity in Loops

  • Accessing properties repeatedly inside loops slows performance.

// Bad: accessing length every iteration
for (let i = 0; i < arr.length; i++) { ... }

// Better: store length outside the loop
let l = arr.length;
for (let i = 0; i < l; i++) { ... }


2. Reduce DOM Access

  • Accessing the DOM is slow. Cache DOM references in a variable if you use them multiple times:

const obj = document.getElementById("demo");
obj.innerHTML = "Hello";
// instead of repeatedly calling document.getElementById("demo")

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:

// Bad
let fullName = firstName + " " + lastName;
document.getElementById("demo").innerHTML = fullName;

// Better
document.getElementById("demo").innerHTML = firstName + " " + lastName;


5. Delay JavaScript Loading

  • Scripts block parsing and downloading of other resources if loaded early.

  • Options:

    1. Place scripts at the end of the body.

    2. Use defer for external scripts:

    <script src="myScript.js" defer></script>
    1. Dynamically load scripts after page load:

    window.onload = function() {
    const element = document.createElement("script");
    element.src = "myScript.js";
    document.body.appendChild(element);
    };

6. Avoid Using with

  • with slows performance and can cause scope confusion.

  • Not allowed in strict mode:

// Avoid this
with (obj) {
prop = 5;
}

💡 Key idea: Minimize repeated work (loops, DOM access), reduce page parsing overhead, and follow strict mode rules for faster, cleaner JavaScript.