JS FUNDAMENTALS

What is JavaScript?

JavaScript is a programming language used to make websites interactive.


Without JS:

  • HTML → structure
  • CSS → design
  • ❌ No interactivity


With JS:

  • Button click → works
  • Form validation → works
  • Animations → dynamic
  • Data from server → load


JavaScript is Case Sensitive

JavaScript identifiers are case sensitive.

The variables lastName and lastname, are different variables

JavaScript Engine

A JavaScript Engine is a program that:


Reads your JS code

Converts it into machine code

Executes it


Popular JS Engines

  • V8 (Chrome, Node.js)
  • SpiderMonkey (Firefox)
  • JavaScriptCore (Safari)


How Engine Works


How to Execute JavaScript Code ? - GeeksforGeeks


Steps:

  1. You write JS code
  2. Engine parses code
  3. Converts to machine code
  4. Executes instantly 


Runtime

 Runtime (Browser Environment)


JavaScript alone = language

But it needs a runtime to run


Browser = Runtime

Browser gives:

  • DOM (Document Object Model)
  • APIs (fetch, setTimeout, etc.)
  • Event system


Example

console.log("Hello");

console.log() is NOT pure JS

It is provided by the browser runtime


Runtime Components

Includes:

  • Call Stack
  • Web APIs
  • Event Loop
  • Callback Queue


👉 You’ll learn these deeply later (advanced level)

How Browser Executes JavaScript

Flow:

  1. Browser reads HTML
  2. Builds DOM
  3. Finds <script>
  4. Stops HTML parsing ⛔
  5. Executes JS
  6. Continues loading


 JS is blocking by default

That means:

  • If JS takes time → page load slows

Use:

<script defer src="script.js"></script>

👉 defer = run JS after HTML loads

JavaScript Where To

The <script> Tag

In HTML, JavaScript code is inserted between <script> and </script> tags.


JavaScript in <head> or <body>

You can place any number of scripts in an HTML document.

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

JavaScript in <head>

In this example, a JavaScript function is placed in the <head> section of an HTML page.


Example function myFunction() { document.getElementByIHTML Sandbox — click to edit


JavaScript in <body>

In this example, a JavaScript function is placed in the <body> section of an HTML page.


Demo JavaScript in Body A Paragraph Try it function myFuHTML Sandbox — click to edit


External JavaScript

Scripts can also be placed in external files:

External file: myScript.js

function myFunction() {

 document.getElementById("demo").innerHTML = "Paragraph changed.";

}

External scripts are practical when the same code is used in many different web pages.

JavaScript files have the file extension .js.

To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:


Example

<script src="myScript.js"></script>


Advantages

Placing scripts in external files has some advantages:

  • It separates HTML and code
  • It makes HTML and JavaScript easier to read and maintain
  • Cached JavaScript files can speed up page loads


JavaScript Output

JavaScript Display Possibilities

JavaScript can "display" data in different ways:

  • Writing into an HTML element, using innerHTML or innerText.
  • Writing into the HTML output using document.write().
  • Writing into an alert box, using window.alert().
  • Writing into the browser console, using console.log().


Using innerHTML

To access an HTML element, you can use the document.getElementById(id) method.

Use the id attribute to identify the HTML element.

Then use the innerHTML property to change the HTML content of the HTML element:


My First Web Page My First Paragraph document.getElementHTML Sandbox — click to edit

Using innerText

To access an HTML element, use the document.getElementById(id) method.

Then use the innerText property to change the inner text of the HTML element:


My First Web Page My First Paragraph document.getElementHTML Sandbox — click to edit


Use innerHTML when you want to change an HTML element.

Use innerText when you only want to change the plain text.


Using document.write()

For testing purposes, it is convenient to use document.write():


My First Web Page My first paragraph. document.write(5 + 6HTML Sandbox — click to edit


Using window.alert()

You can use an alert box to display data:

My First Web Page My first paragraph. window.alert(5 + 6);HTML Sandbox — click to edit

Using console.log()

For debugging purposes, you can call the console.log() method in the browser to display data.

console.log(5 + 6);HTML Sandbox — click to edit


VARIABLES & DATA TYPES

 Variables (in programming)


A variable is a named container used to store data.


👉 Example (JavaScript):

let name = "Jeeshma";

Here, name is a variable storing a value.


In short:

➡️ Variable = a box that holds data


Data Types


A data type defines what kind of data a variable stores.


👉 Common types:

  • String"Hello"
  • Number25
  • Booleantrue / false
  • Array[1, 2, 3]
  • Object{name: "Jeeshma"}


In short:

➡️ Data Type = type of data inside the box

Variable

 What is a Variable?


A variable is a container that stores data.


 Example

let age = 20;

  • let → keyword
  • age → variable name
  • 20 → value


 var, let, const


1. var (OLD WAY – avoid in modern JS)

var name = "John";

❌ Problems:

  • Function scoped (not block scoped)
  • Can be re-declared
  • Causes bugs
var x = 10;
var x = 20; // ✅ allowed (but dangerous)


2. let (MODERN – use this )

let age = 25;

✅ Features:

  • Block scoped
  • Can be updated
  • Cannot be re-declared
let x = 10;
x = 20; // ✅ allowed

let x = 30; // ❌ error


3. const (CONSTANT – most used )

const pi = 3.14;

✅ Features:

  • Block scoped
  • Cannot be updated
  • Cannot be re-declared
const x = 10;
x = 20; // ❌ error


When to use what?

  • const → default choice ✅
  • let → if value changes
  • var → ❌ avoid


Data Types

 1. Primitive Types


Stored by value


Types:

  • String → "hello"
  • Number → 10
  • Boolean → true / false
  • Undefined → variable declared but no value
  • Null → intentionally empty


Example:

let name = "blackbox";   // String
let age = 20;           // Number
let isStudent = true;   // Boolean
let x;                  // Undefined
let y = null;           // Null


2. Reference Types

👉 Stored by reference (memory address)

Types:

  • Object
  • Array
  • Function

Example:

let user = {
  name: "blackbox",
  age: 20
};

let arr = [1, 2, 3];


Key Difference (VERY IMPORTANT)

Primitive:

let a = 10;
let b = a;

b = 20;

console.log(a); // 10

👉 Copy created → separate memory

Reference:

let obj1 = { name: "John" };
let obj2 = obj1;

obj2.name = "Alex";

console.log(obj1.name); // Alex 😱

👉 Same memory → both change

Type Coercion

 JavaScript automatically converts types when needed


 1. Implicit Coercion (Automatic)

Example:

console.log("5" + 2); 
// "52"

👉 Number → converted to string

console.log("5" - 2);
// 3

👉 String → converted to number

console.log(true + 1);
// 2

👉 true → 1


2. Explicit Coercion (Manual)

You convert types yourself:

Number("10");   // 10
String(100);    // "100"
Boolean(0);     // false




Mini Practice

let a = "10";
let b = 5;

console.log(a + b); 
console.log(a - b);
console.log(a * b);

👉 Try to predict output before running


Quick Rule (VERY IMPORTANT)

  • + → string concatenation if one is string
  • -, *, / → always convert to number


OPERATORS

Operators (JS): symbols that perform actions on values

👉 Types:

  • Arithmetic → + - * / %
  • Comparison → == === > <
  • Logical → && || !
  • Assignment → = += -=


Arithmetic Operators

 Used for mathematical calculations


➕ Basic Operators

let a = 10;
let b = 3;

console.log(a + b); // 13
console.log(a - b); // 7
console.log(a * b); // 30
console.log(a / b); // 3.33...
console.log(a % b); // 1 (remainder)


🔥 Increment / Decrement

let x = 5;

x++; // post-increment
console.log(x); // 6

++x; // pre-increment
console.log(x); // 7


👉 Why?

  • x++ → increases after → becomes 6
  • ++x → increases before → becomes 7


⚠️ Important Difference

let x = 5;

console.log(x++); // 5 (use first, then increase)
console.log(++x); // 7 (increase first, then use)

Step 1: console.log(x++)

  • Current x = 5
  • x++use first → print 5
  • Then increase → x = 6

👉 Output: 5


Step 2: console.log(++x)

  • Now x = 6
  • ++xincrease first → becomes 7
  • Then print → 7

👉 Output: 7


Easy Trick to Remember

  • Post (x++) → "Use → Then Increase"
  • Pre (++x) → "Increase → Then Use"


JavaScript Operators


 Quick Practice

What will this print?

let x = 10;

console.log(++x); 
console.log(x++); 
console.log(x);

Answer:

  • ++x → 11
  • x++ → prints 11, then becomes 12
  • final x → 12


Comparison Operators

 Used to compare values → returns true or false


Basic Comparison

console.log(5 > 3);   // true
console.log(5 < 3);   // false
console.log(5 >= 5);  // true
console.log(5 <= 4);  // false


Logical Operators

Used to combine conditions


AND (&&)

Both must be true

console.log(true && true);   // true
console.log(true && false);  // false


OR (||)

At least one true

console.log(true || false); // true
console.log(false || false); // false


NOT (!)

Reverses value

console.log(!true);  // false
console.log(!false); // true


JavaScript Conditionals

Conditional Statements

Conditional Statements allow us to perform different actions for different conditions.

Conditional statements run different code depending on true or false conditions.

Conditional statements include:

  • if
  • if...else
  • if...else if...else
  • switch
  • ternary (? :)


When to use Conditionals

  • Use if to specify a code block to be executed, if a specified condition is true
  • Use else to specify a code block to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative code blocks to be executed
  • Use (? :) (ternary) as a shorthand for if...else


if Statement

Use if to specify a code block to be executed, if a specified condition is true.


Syntax

if (condition) {

  // code to execute if the condition is true

}


else Statement

Use else to specify a code block to be executed, if the same condition is false.


Syntax

if (condition) {

  // code to execute if the condition is true

else {

  // code to execute if the condition is false

}


else if Statement

Use else if to specify a new condition to test, if the first condition is false.


Syntax

if (condition1) {

  // code to execute if condition1 is true

else if (condition2) {

  // code to execute if the condition1 is false and condition2 is true

else {

  // code to execute if the condition1 is false and condition2 is false

}


switch Statement

Use switch to specify many alternative code blocks to be executed.


Syntax

switch(expression) {

  case x:

    // code block

    break;

  case y:

    // code block

    break;

  default:

   // code block

}


Ternary Operator (? :)

Use (? :) (ternary) as a shorthand for if...else.


Example

condition ? expression1 : expression2