[Go to site: main page, start]

0% found this document useful (0 votes)
0 views20 pages

Java Script Notes

This document provides comprehensive notes on JavaScript, covering key topics such as variable declarations, data types, conditional statements, loops, functions, classes, file operations in Node.js, and data structures. It includes examples and syntax for each topic, highlighting best practices and modern features like ES6+. Additionally, a quick reference table summarizes key syntax and use cases for easy access.

Uploaded by

tefulasimba
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views20 pages

Java Script Notes

This document provides comprehensive notes on JavaScript, covering key topics such as variable declarations, data types, conditional statements, loops, functions, classes, file operations in Node.js, and data structures. It includes examples and syntax for each topic, highlighting best practices and modern features like ES6+. Additionally, a quick reference table summarizes key syntax and use cases for easy access.

Uploaded by

tefulasimba
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JAVASCRIPT NOTES

1. VARIABLES

Variables store data values. JavaScript has three ways to declare variables.

Declaration Keywords:

 let – mutable variable, block-scoped (modern, recommended)

 const – immutable variable, block-scoped (cannot be reassigned)

 var – function-scoped (older, avoid in modern code)

Data Types:

 Primitive: string, number, boolean, null, undefined, symbol, bigint

 Reference: object, array, function

Examples:

javascript

// let – can be reassigned

let age = 25;

age = 26; // OK

// const – cannot be reassigned

const PI = 3.14159;

// PI = 3.14; // ERROR!

// var – avoid in modern code

var oldStyle = "legacy";

// Different data types

let name = "Alice"; // string

let count = 42; // number

let isActive = true; // boolean


let data = null; // null

let notDefined; // undefined

// Reference types

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

let colors = ["red", "green", "blue"];

2. PARITY

"Parity" typically refers to checking if a number is even or odd.

Even/Odd Check (Modulo Operator %):

javascript

function checkParity(number) {

if (number % 2 === 0) {

[Link](`${number} is even`);

} else {

[Link](`${number} is odd`);

checkParity(7); // odd

checkParity(10); // even

// Bitwise AND (faster but less readable)

function isEven(num) {

return (num & 1) === 0;

}
[Link](isEven(4)); // true

[Link](isEven(5)); // false

Advanced Parity Examples:

javascript

// Parity of sum

let a = 3, b = 5;

let sumParity = (a + b) % 2 === 0 ? "even sum" : "odd sum";

// Parity of array length

let arr = [1, 2, 3];

let lengthParity = [Link] % 2 === 0 ? "even length" : "odd length";

3. CONDITIONS

Conditional statements control code execution flow.

If-Else Statement:

javascript

let score = 85;

if (score >= 90) {

[Link]("A");

} else if (score >= 80) {

[Link]("B");

} else if (score >= 70) {

[Link]("C");

} else {

[Link]("Fail");

}
Switch Statement:

javascript

let day = "Monday";

switch(day) {

case "Monday":

[Link]("Start of work week");

break;

case "Friday":

[Link]("Weekend soon!");

break;

case "Saturday":

case "Sunday":

[Link]("Weekend!");

break;

default:

[Link]("Midweek");

Ternary Operator:

javascript

let age = 18;

let status = age >= 18 ? "Adult" : "Minor";

[Link](status); // "Adult"

Logical Operators:

javascript

let isLoggedIn = true;

let hasPermission = false;


// AND &&

if (isLoggedIn && hasPermission) {

[Link]("Access granted");

// OR ||

if (isLoggedIn || hasPermission) {

[Link]("Partial access");

// NOT !

if (!isLoggedIn) {

[Link]("Please login");

4. LOOPS

Loops repeat code blocks multiple times.

For Loop:

javascript

// Standard for loop

for (let i = 0; i < 5; i++) {

[Link](`Iteration ${i}`);

// Output: 0,1,2,3,4

// Iterate over array


let fruits = ["apple", "banana", "cherry"];

for (let i = 0; i < [Link]; i++) {

[Link](fruits[i]);

While Loop:

javascript

let countdown = 3;

while (countdown > 0) {

[Link](countdown);

countdown--;

[Link]("Blast off!");

Do-While Loop (executes at least once):

javascript

let x = 10;

do {

[Link]("This runs once even if condition false");

x++;

} while (x < 5);

For...Of Loop (values):

javascript

let colors = ["red", "green", "blue"];

for (let color of colors) {

[Link](color);

For...In Loop (keys/properties):

javascript
let car = { brand: "Toyota", model: "Camry", year: 2022 };

for (let key in car) {

[Link](`${key}: ${car[key]}`);

Break and Continue:

javascript

// break – exit loop

for (let i = 0; i < 10; i++) {

if (i === 5) break;

[Link](i); // 0,1,2,3,4

// continue – skip iteration

for (let i = 0; i < 5; i++) {

if (i === 2) continue;

[Link](i); // 0,1,3,4

5. FUNCTIONS

Functions are reusable blocks of code.

Function Declarations:

javascript

// Basic function

function greet(name) {

return `Hello, ${name}!`;

[Link](greet("Alice"));
// Function with default parameter

function multiply(a, b = 1) {

return a * b;

[Link](multiply(5)); // 5

[Link](multiply(5, 3)); // 15

Function Expressions:

javascript

const square = function(x) {

return x * x;

};

[Link](square(4)); // 16

Arrow Functions (ES6+):

javascript

// Single parameter, single expression

const double = x => x * 2;

// Multiple parameters

const add = (a, b) => a + b;

// Multiple statements need braces and return

const divide = (a, b) => {

if (b === 0) return "Error: Division by zero";

return a / b;

};
[Link](double(5)); // 10

[Link](add(3, 7)); // 10

Higher-Order Functions:

javascript

// Function as parameter

function operate(a, b, operation) {

return operation(a, b);

const result = operate(10, 5, (x, y) => x - y);

[Link](result); // 5

// Function returning function

function multiplier(factor) {

return function(number) {

return number * factor;

};

const triple = multiplier(3);

[Link](triple(7)); // 21

Rest Parameters & Spread:

javascript

// Rest parameter - collects arguments into array

function sumAll(...numbers) {

return [Link]((total, num) => total + num, 0);

}
[Link](sumAll(1, 2, 3, 4)); // 10

// Spread operator - expands array

const nums = [1, 2, 3];

[Link]([Link](...nums)); // 3

6. CLASSES

Classes are blueprints for creating objects (ES6+).

Basic Class Definition:

javascript

class Person {

// Constructor method

constructor(name, age) {

[Link] = name;

[Link] = age;

// Instance method

introduce() {

return `Hi, I'm ${[Link]} and I'm ${[Link]} years old.`;

// Getter

get birthYear() {

return new Date().getFullYear() - [Link];

}
// Setter

set birthYear(year) {

[Link] = new Date().getFullYear() - year;

// Create instance

const alice = new Person("Alice", 30);

[Link]([Link]()); // Hi, I'm Alice and I'm 30 years old.

[Link]([Link]); // 1994 (if current year is 2024)

Inheritance:

javascript

class Animal {

constructor(name) {

[Link] = name;

speak() {

[Link](`${[Link]} makes a sound.`);

class Dog extends Animal {

constructor(name, breed) {

super(name); // Call parent constructor

[Link] = breed;

}
// Override method

speak() {

[Link](`${[Link]} barks!`);

// Additional method

fetch() {

[Link](`${[Link]} fetches the ball.`);

const rex = new Dog("Rex", "German Shepherd");

[Link](); // Rex barks!

[Link](); // Rex fetches the ball.

Static Methods & Properties:

javascript

class MathUtils {

static PI = 3.14159;

static circleArea(radius) {

return [Link] * radius * radius;

[Link]([Link]); // 3.14159

[Link]([Link](5)); // 78.53975
Private Fields (ES2022):

javascript

class BankAccount {

#balance = 0; // Private field

deposit(amount) {

if (amount > 0) {

this.#balance += amount;

getBalance() {

return this.#balance;

const account = new BankAccount();

[Link](100);

[Link]([Link]()); // 100

// [Link](account.#balance); // Syntax Error!

7. FILES ([Link] Environment)

File operations in JavaScript require [Link] runtime.

Reading Files:

javascript

const fs = require('fs');
// Synchronous read

try {

const data = [Link]('[Link]', 'utf8');

[Link](data);

} catch (err) {

[Link]("Error reading file:", err);

// Asynchronous read with callback

[Link]('[Link]', 'utf8', (err, data) => {

if (err) {

[Link](err);

return;

[Link](data);

});

// Promise-based ([Link])

const fsPromises = require('fs').promises;

async function readFileAsync() {

try {

const data = await [Link]('[Link]', 'utf8');

[Link](data);

} catch (err) {

[Link](err);

}
}

readFileAsync();

Writing Files:

javascript

const fs = require('fs');

// Write (overwrites)

[Link]('[Link]', 'Hello World!');

// Append to file

[Link]('[Link]', '\nAnother line');

// Async write

[Link]('[Link]', 'Async content', (err) => {

if (err) throw err;

[Link]('File saved!');

});

Working with JSON Files:

javascript

const fs = require('fs');

// Write JSON

const user = { name: "John", age: 30, city: "NYC" };

[Link]('[Link]', [Link](user, null, 2));

// Read JSON

const rawData = [Link]('[Link]', 'utf8');


const parsedUser = [Link](rawData);

[Link]([Link]); // John

8. STRUCTURES

JavaScript doesn't have "struct" like C/C++, but objects and Maps provide
similar functionality.

Object Literals (Similar to Struct):

javascript

// Basic object as structure

const point = {

x: 10,

y: 20,

// Method

distanceFromOrigin() {

return [Link](this.x * this.x + this.y * this.y);

};

[Link](point.x); // 10

[Link]([Link]()); // 22.36

Factory Functions (Creating struct-like objects):

javascript

function createStudent(name, id, grades) {

return {

name,

id,

grades,
getAverage() {

const sum = [Link]((a, b) => a + b, 0);

return sum / [Link];

};

const student1 = createStudent("Alice", 101, [85, 90, 88]);

[Link]([Link]()); // 87.67

Map (Key-Value Structure):

javascript

// Map allows any type as key

const userMap = new Map();

// Set values

[Link]('name', 'Bob');

[Link](42, 'answer');

[Link](true, 'boolean key');

// Get values

[Link]([Link]('name')); // Bob

[Link]([Link](42)); // answer

// Iterate

[Link]((value, key) => {

[Link](`${key}: ${value}`);

});
// Size and deletion

[Link]([Link]); // 3

[Link]('name');

[Link]([Link]('name')); // false

Set (Unique Values Structure):

javascript

const uniqueNumbers = new Set();

[Link](1);

[Link](2);

[Link](2); // Duplicate – ignored

[Link](3);

[Link](uniqueNumbers); // Set {1, 2, 3}

[Link]([Link](2)); // true

// Convert to array

const array = [...uniqueNumbers]; // [1,2,3]

Custom Data Structure Example:

javascript

// Stack implementation

class Stack {

#items = [];

push(item) {

this.#[Link](item);
}

pop() {

return this.#[Link]();

peek() {

return this.#items[this.#[Link] - 1];

isEmpty() {

return this.#[Link] === 0;

get size() {

return this.#[Link];

const stack = new Stack();

[Link](10);

[Link](20);

[Link]([Link]()); // 20

[Link]([Link]()); // 10

QUICK REFERENCE TABLE


Topic Key Syntax Use Case

Variable let x = 5; const y = 10; Store data

Parity num % 2 === 0 Even/odd check

Condition if/else, switch, ? : Branching logic

Loop for, while, for...of Repetition

Function function name() {} or () => {} Code reuse

Class class Name {} OOP blueprints

File (Node) [Link]() I/O operations

Structure {}, Map, Set Data organization

You might also like