0% found this document useful (0 votes)
2 views9 pages

JavaScript Course Notes With Code Examples

The document provides comprehensive notes on JavaScript, covering its introduction, basic syntax, data types, operators, control structures, functions, arrays, and more. It includes code examples to illustrate concepts like variable declarations, loops, string manipulation, form handling, and best practices in development. Additionally, it touches on advanced topics such as cookies, sessions, password hashing, and database connections using Node.js.

Uploaded by

sammunroe2014
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)
2 views9 pages

JavaScript Course Notes With Code Examples

The document provides comprehensive notes on JavaScript, covering its introduction, basic syntax, data types, operators, control structures, functions, arrays, and more. It includes code examples to illustrate concepts like variable declarations, loops, string manipulation, form handling, and best practices in development. Additionally, it touches on advanced topics such as cookies, sessions, password hashing, and database connections using Node.js.

Uploaded by

sammunroe2014
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
You are on page 1/ 9

JavaScript Course Notes with Code

Examples

1. Introduction to JavaScript
 JavaScript is a client-side scripting language used to create dynamic and interactive web
pages.
 Runs inside web browsers but can also run on servers (Node.js).
 It’s loosely typed and interpreted.

2. Basic Syntax & Variables


 JavaScript statements end with a semicolon ; (optional but recommended).
 Variables can be declared with var, let, or const.

javascript
CopyEdit
// Variable declarations
var name = "Alice"; // function-scoped, old style
let age = 25; // block-scoped, preferred
const PI = 3.14; // constant, block-scoped

console.log(name, age, PI);

3. Data Types
 Common types: Number, String, Boolean, Null, Undefined, Object, Array, Function.

javascript
CopyEdit
let number = 10; // Number
let message = "Hello!"; // String
let isActive = true; // Boolean
let empty = null; // Null
let notDefined; // Undefined

console.log(typeof number); // "number"


console.log(typeof message); // "string"

4. Operators
 Arithmetic: +, -, *, /, %
 Assignment: =, +=, -=, etc.
 Comparison: ==, ===, !=, !==, <, >, <=, >=
 Logical: &&, ||, !

5. Control Structures
if / else
javascript
CopyEdit
let score = 85;

if (score >= 90) {


console.log("Grade A");
} else if (score >= 75) {
console.log("Grade B");
} else {
console.log("Grade C or below");
}

switch
javascript
CopyEdit
let fruit = "apple";

switch (fruit) {
case "banana":
console.log("Banana is yellow");
break;
case "apple":
console.log("Apple is red");
break;
default:
console.log("Unknown fruit");
}

6. Loops
for loop
javascript
CopyEdit
for (let i = 0; i < 5; i++) {
console.log("Number:", i);
}
while loop
javascript
CopyEdit
let count = 0;
while (count < 3) {
console.log("Count is", count);
count++;
}

7. Functions
javascript
CopyEdit
// Function declaration
function greet(name) {
return "Hello " + name + "!";
}

console.log(greet("Alice"));

// Arrow function (ES6)


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

console.log(add(3, 4));

8. Arrays & Associative Arrays (Objects)


Array
javascript
CopyEdit
let fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // apple

// Loop through array


fruits.forEach((fruit) => console.log(fruit));

Object (Associative Array)


javascript
CopyEdit
let person = {
name: "Bob",
age: 30,
city: "New York"
};

console.log(person.name); // Bob
console.log(person["age"]); // 30
9. String Manipulation
javascript
CopyEdit
let text = "Hello, World!";

console.log(text.length); // 13
console.log(text.toUpperCase()); // "HELLO, WORLD!"
console.log(text.toLowerCase()); // "hello, world!"
console.log(text.indexOf("World")); // 7
console.log(text.slice(7, 12)); // "World"

10. Form Handling (GET vs POST)


 Typically done in HTML + JavaScript with event listeners.
 GET sends data via URL, POST sends data in request body.

html
CopyEdit
<form id="myForm">
<input type="text" name="username" />
<button type="submit">Submit</button>
</form>

<script>
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault(); // Prevent form from submitting normally

let formData = new FormData(event.target);


let username = formData.get("username");
console.log("Submitted username:", username);
});
</script>

11. Input Validation & Sanitization


javascript
CopyEdit
function isValidEmail(email) {
let regex = /^\S+@\S+\.\S+$/;
return regex.test(email);
}

console.log(isValidEmail("[email protected]")); // true
console.log(isValidEmail("[email protected]")); // false
12. Cookies & Sessions (Basics)
 Cookies: small data stored in browser, accessible via document.cookie.

javascript
CopyEdit
// Set a cookie
document.cookie = "username=Alice; expires=Fri, 31 Dec 2025 23:59:59 GMT;
path=/";

// Read cookies
console.log(document.cookie);

 Sessions typically managed on server side (Node.js/Express, PHP, etc.).

13. Password Hashing & Authentication (Overview)


 Usually done on server side for security.
 Client sends password over secure connection (HTTPS).
 Server hashes passwords (e.g., bcrypt) before storing.
 Authentication involves verifying stored hash matches provided password.

14. Database Connection and Queries (MySQLi example in


PHP)
 JavaScript (Node.js) uses libraries like mysql or sequelize.
 Example with Node.js mysql module:

javascript
CopyEdit
const mysql = require('mysql');

const connection = mysql.createConnection({


host: "localhost",
user: "user",
password: "password",
database: "mydb"
});

connection.connect((err) => {
if (err) throw err;
console.log("Connected!");

connection.query("SELECT * FROM users", (err, results) => {


if (err) throw err;
console.log(results);
});
});

YOUTUBE NOTES

1. JavaScript Overview
JavaScript is one of the core technologies of the web (alongside HTML and CSS).

 Purpose: It allows developers to create interactive and dynamic web pages, rather than
just static ones.
 Where it Runs:
o Browser → Front-end development (controls things like animations, forms, pop-
ups).
o Node.js → Back-end development (handles databases, APIs, authentication).
 Evolution:
o Originally, JavaScript was purely for browser use.
o Now, it can be used to create mobile apps, desktop apps, and real-time services
like chat applications.
 Why It’s Important: The language has a huge ecosystem, lots of developer support, and
frequent updates that keep it modern.
 ECMAScript Standard: JavaScript follows this specification. Think of ECMAScript as
the “rulebook” that defines how JavaScript should work.

2. Best Practices in JavaScript Development


 Script Placement:
Place <script> tags at the end of the <body> so the HTML loads first, avoiding errors
like null when trying to access elements that don’t exist yet.
 Comments:
o // → Single-line comments.
o /* ... */ → Multi-line comments.
These are for explaining your code logic without affecting execution.
 Separation of Concerns:
Keep HTML for structure, CSS for styling, and JavaScript for behavior. This improves
maintainability and makes it easier to debug.
 Node.js:
A runtime that lets you execute JavaScript outside of the browser — essential for
building APIs, servers, and handling back-end tasks.
3. Variables in JavaScript
 Declaration Rules:
o Avoid using reserved words (let, var, if, else, etc.) as variable names.
o Pick names that clearly describe what the variable stores (e.g., userName is better
than x).
 Case Sensitivity:
JavaScript treats age and Age as two different variables — consistency is key.
 Primitive Types:

1. String: Text — "Hello World".


2. Number: Numeric — 42, 3.14.
3. Boolean: True/false — true, false.
4. Undefined: Declared but no value assigned.
5. Null: Explicitly empty value.

4. Dynamic Typing
JavaScript doesn’t require you to declare variable types in advance — they can change while the
program runs.
Example:

javascript
CopyEdit
let data = "Hello"; // string
data = 42; // number

 Type Checking: The typeof operator tells you the current data type.
 Value Types:
o Primitive: Stored directly in memory (string, number, boolean, undefined, null).
o Reference: Stored as references to memory (objects, arrays, functions).

5. Objects
 Objects store data in key-value pairs.
 Example:

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

 Keys act like labels; values can be any data type (including arrays or other objects).
 This makes data organized, like a “real-life entity” representation.

6. Arrays
 Dynamic: Can change size or type during execution.
 Example:

javascript
CopyEdit
let mix = [1, "hello", true];

 Indexing: Starts at 0. The first element is array[0].


 Special Nature: Arrays are a type of object, meaning they have built-in methods like
.push() (add item) or .pop() (remove last item).

7. Functions
 Purpose: Encapsulate reusable blocks of code to perform tasks or return values.
 Parameters: Allow functions to handle different inputs.
 Execution: Must be called for the code inside to run.
 Example:

javascript
CopyEdit
function greet(name) {
return "Hello " + name;
}
console.log(greet("Sam")); // Hello Sam

 Real applications combine many functions to work together.

You might also like