0% found this document useful (0 votes)
5 views24 pages

JavaScript Basics: Language Overview

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)
5 views24 pages

JavaScript Basics: Language Overview

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

Introduction to JavaScript

Definition:
JavaScript is a lightweight, interpreted, object-oriented programming language designed for
creating dynamic web pages and enhancing user interaction. It runs directly in the web browser
and forms one of the three core technologies of the web:
 HTML for content
 CSS for styling
 JavaScript for behavior

History and Evolution


 1995: Created by Brendan Eich at Netscape under the name Mocha.
 Renamed to LiveScript, then to JavaScript to leverage the popularity of Java.
 1997: Standardized by ECMA (as ECMAScript).
 2009: [Link] introduced, enabling JavaScript on the server side.
 2023: Latest standard is ECMAScript 14 (ES14).

Client-Side vs. Server-Side Scripting


Feature Client-Side JavaScript Server-Side Scripting
Execution Runs in the browser Runs on the web server
Speed Fast, no server request May involve network delay
Usage DOM manipulation, validation, interactivity Database, authentication, file handling
Examples Form validation, animations Data storage, processing

Key Features of JavaScript


 Interpreted: No need for compilation.
 Dynamically Typed: No need to declare variable types.
 Single-threaded: Executes one command at a time.
 Event-Driven: Responds to user actions.
 Platform Independent: Runs on any browser and OS.
 Object-Based: Uses built-in objects like Array, Math, Date.
Advantages of Client-Side JavaScript
✅ Less server load: Reduces requests sent to the server.
✅ Immediate feedback: Validates data before submission.
✅ Increased interactivity: Reacts to user events like clicks or hovers.
✅ Richer interfaces: Allows the creation of sliders, pop-ups, and animations.
✅ Quick execution: Code runs immediately in the browser.

Limitations of JavaScript
❌ Cannot access local files or system resources.
❌ Not suitable for secure operations (e.g., authentication).
❌ Visible and editable in the browser (can be misused).
❌ Browser compatibility issues (though minimized with modern JS frameworks).
❌ No true multithreading (though Web Workers can help).

Ways to Include JavaScript in HTML


1. Inline JavaScript
Placed directly inside an HTML element.
Example:
<button onclick="alert('Welcome!')">Click Me</button>

2. Internal JavaScript
Placed within <script> tags in the HTML document.
Example:
<!DOCTYPE html>
<html>
<head>
<script>
function greetUser() {
alert("Hello, User!");
}
</script>
</head>
<body>
<button onclick="greetUser()">Greet</button>
</body>
</html>

3. External JavaScript
Stored in a separate .js file and linked via <script src="[Link]">.
HTML File:
<script src="[Link]"></script>
[Link]:
function showMessage() {
alert("Hello from external file!");
}

Real-World Use Cases of JavaScript


Use Case Description
Form Validation Ensure data correctness before sending it to the server.
Dynamic Content Update page content without reloading.
Event Handling React to user input like clicks or keystrokes.
Animation and Effects Create dynamic visual feedback.
Data Visualization Charts and graphs using libraries like [Link] or [Link].

Sample Example – Dynamic HTML Update


<!DOCTYPE html>
<html>
<body>

<h2 id="greeting">Hello!</h2>
<button onclick="[Link]('greeting').innerHTML = 'Welcome to
JavaScript!'">Change Text</button>

</body>
</html>

Explanation:
 The JavaScript code changes the inner HTML of the <h2> element when the button is
clicked.

Summary
JavaScript is a crucial technology for enhancing user interaction and creating responsive
websites. As a client-side scripting language, it allows developers to make real-time changes,
validate data instantly, and improve user experiences without burdening the server.

Recommended Tools for JavaScript Development


 Text Editors: Visual Studio Code, Sublime Text, Notepad++
 Debugging: Chrome Developer Tools, Firefox Developer Tools
 Libraries & Frameworks: jQuery, [Link], [Link], Angular

What are JavaScript Statements?


Definition:
A JavaScript statement is an instruction that the browser executes. A script is a series of such
statements. They are executed in the order they appear, unless control flow statements like loops
or conditionals are used.
Think of a statement as a sentence in the language of JavaScript.

Basic Syntax of Statements


 Statements usually end with a semicolon (;).
 Multiple statements can be written on a single line if separated by semicolons, but it's
best to write one per line for clarity.
 JavaScript ignores spaces and new lines, but uses curly braces {} to group blocks of
statements.
Example:
let x = 5;
let y = 10;
let sum = x + y;
[Link](sum); // Output: 15

Types of JavaScript Statements


a) Declaration Statements
Used to declare variables.
Example:
let name = "Lindah";
const PI = 3.14;
var age = 25;

b) Assignment Statements
Used to assign a value to a variable.
Example:
let score;
score = 95;

c) Expression Statements
An expression followed by a semicolon; it gets evaluated and produces a result.
Example:
x = y + 5;

d) Conditional Statements
Used to perform different actions based on different conditions.
Example:
let age = 20;
if (age >= 18) {
[Link]("Adult");
} else {
[Link]("Minor");
}

e) Looping Statements
Used to repeat a block of code as long as a condition is true.
Example:
for (let i = 0; i < 3; i++) {
[Link]("Iteration " + i);
}

f) Function Statements
Used to define reusable blocks of code.
Example:
function greet(name) {
[Link]("Hello " + name);
}
greet("Lindah");

g) Control Flow Statements


Used to control the flow of execution:
 break
 continue
 return
 try...catch
Example (break):
for (let i = 0; i < 10; i++) {
if (i === 5) break;
[Link](i);
}

JavaScript Statement Blocks


A block is a group of statements enclosed in curly braces {}. Blocks are used with functions,
loops, and conditionals.
Example:
if (true) {
let message = "This is a block";
[Link](message);
}

Case Sensitivity
JavaScript is case-sensitive, so let name and let Name are different.

Whitespace and Line Breaks


JavaScript ignores extra spaces and new lines, but good formatting improves readability.
Bad Practice:
let a=1;let b=2;let c=a+b;
Good Practice:
let a = 1;
let b = 2;
let c = a + b;

Examples of JavaScript Statements in Action


Example 1: Simple Math Operation
let length = 20;
let width = 10;
let area = length * width;
[Link]("Area: " + area); // Output: Area: 200

Example 2: Conditional Statement


let temp = 35;

if (temp > 30) {


[Link]("It's hot!");
} else {
[Link]("It's cool.");
}

Example 3: Looping Statement


for (let i = 1; i <= 5; i++) {
[Link]("Number: " + i);
}

Summary
Concept Description
Statement A JavaScript command that performs an action
Ends with Semicolon ; (recommended)
Grouped using Curly braces {}
Types Declaration, Assignment, Expression, Conditional, Loop, Function, Control Flow

In-Class Activities / Assignments


1. Write a script that declares two numbers, adds them, and prints the result.
2. Create a loop that prints numbers 1 to 10.
3. Write a function that takes a name and prints "Hello, Name".

What are JavaScript Comments?


Comments are lines in the code that are not executed. They are meant for:
 Explaining code functionality.
 Improving code readability.
 Debugging by temporarily disabling code.
 Adding reminders or TODO notes.
JavaScript comments are ignored by the browser when the code runs.

Types of JavaScript Comments


a) Single-Line Comments
 Start with //
 Everything after // on the same line is ignored
Example:
// This is a single-line comment
let x = 10; // Assign 10 to x

b) Multi-Line Comments
 Start with /* and end with */
 Can span across multiple lines
Example:
/* This is a multi-line comment.
It can be used to describe
complex logic or disable blocks of code. */
let y = 20;

Best Practices for Using Comments


✅ Write meaningful comments that explain why, not just what
✅ Keep comments updated as code changes
✅ Use comments to explain tricky or non-obvious logic
✅ Don’t over-comment simple or self-explanatory code
Example (Good Commenting):
// Calculate the area of a rectangle
let length = 10;
let width = 5;
let area = length * width; // Area = Length × Width
Example (Over-commenting – Avoid):
// Set x to 10
let x = 10; // Declare variable x and assign it 10

Commenting Out Code (Debugging Technique)


Sometimes, developers comment out parts of the code to test or debug.
Example:
// let result = 10 + 20;
[Link]("Testing output");
This is useful when you want to temporarily disable code without deleting it.

Practical Examples
Example 1: Single-line comment
let name = "Lindah"; // Store user's name

Example 2: Multi-line comment for complex logic


/*
This function calculates the square
of a given number and returns it
*/
function square(num) {
return num * num;
}

Example 3: Using comments for debugging


let num = 50;
// [Link](num * 2); // Temporarily disabled
[Link]("Debugging complete");

Summary
Type of Comment Syntax Usage
Single-line // Short, inline or one-line explanations
Multi-line /* */ Longer notes or disabling code blocks
 Comments make your code easier to understand for you and others.
 They are an essential part of clean and maintainable code.

What is a Variable?
A variable is a container for storing data values (like numbers, text, objects, etc.) that can be
used and manipulated in a program.
Think of a variable as a labeled box that holds a value.

Declaring Variables in JavaScript


JavaScript provides three keywords to declare variables:
Keyword Scope Reassignable
var Function-scoped ✅ Yes
let Block-scoped ✅ Yes
const Block-scoped ❌ No (must be assigned at declaration)
Syntax:
let x = 10;
const name = "Lindah";
var age = 25;

Variable Naming Rules


 Must begin with a letter, underscore _, or dollar sign $
 Can contain numbers (but not start with them)
 Case-sensitive (myVar ≠ myvar)
 Cannot be a reserved keyword (like let, for, return)

Naming Conventions: Camel Case vs Pascal Case


Naming conventions help make code consistent, readable, and maintainable. The most
commonly used cases are:
🔹 1. Camel Case (camelCase)
 Definition: The first word is lowercase, and each subsequent word starts with an
uppercase letter.
 Commonly used for:
✅ Variables, ✅ Functions, ✅ Object properties
✅ Example:
let userName = "Lindah";
function calculateTotal() {
// function code
}
let studentScore = 90;
🔸 Notice: First word is lowercase: user, then Name.
🔹 2. Pascal Case (PascalCase)
 Definition: Each word starts with an uppercase letter, including the first one.
✅ Example:
class StudentDetails {
constructor(name) {
[Link] = name;
}
}
function PrintReport() {
// function code
}
🔸 Notice: Every word starts with a capital letter: StudentDetails, PrintReport.

🔸 Comparison Table
Format Example Name Usage
camelCase totalAmount variables, functions, properties
PascalCase TotalAmount classes, constructors, components
snake_case total_amount (Used in Python, not JS standard)
kebab-case total-amount (Used in CSS, not allowed in JS vars)

Examples:
let firstName = "Lindah"; // valid
let _age = 30; // valid
let $salary = 40000; // valid
// let 1name = "Invalid"; // ❌ Invalid

Variable Initialization
You can declare a variable and assign a value later:
Example:
let score;
score = 100;
Or declare and initialize together:
let score = 100;

Dynamic Typing in JavaScript


JavaScript is a dynamically typed language. This means:
 Variables do not need a type declaration
 You can store different types of values in the same variable
Example:
let value = 5; // number
value = "hello"; // string
value = true; // boolean

Variable Scope
Scope defines where in your program a variable is accessible.
a) Global Scope
Declared outside any function/block; accessible everywhere.
let globalVar = "I am global";

b) Function Scope
Variables declared with var inside a function.
function test() {
var localVar = "Only inside this function";
}

c) Block Scope
Variables declared with let or const inside {}.
javascript
CopyEdit
if (true) {
let blockVar = "Accessible only in this block";
}

var vs let vs const – Key Differences


Feature var let const

Scope Function Block Block


Redeclaration Allowed Not Allowed Not Allowed
Reassignment Allowed Allowed Not allowed
Yes (value Yes (no access before Yes (no access before
Hoisting
undefined) declaration) declaration)

Examples
Example 1: Declaring and Using Variables
let studentName = "Lindah";
let studentAge = 22;
[Link](studentName + " is " + studentAge + " years old.");

Output:
Lindah is 22 years old.

Example 2: Using const


const PI = 3.14159;
let radius = 5;
let area = PI * radius * radius;
[Link]("Area = " + area);

Example 3: Scope Difference


function testScope() {
if (true) {
var a = 10;
let b = 20;
}
[Link](a); // ✅ 10
// [Link](b); ❌ ReferenceError
}
testScope();

Best Practices for Using Variables


 Use let for variables that may change.
 Use const for values that should remain constant.
 Avoid var in modern code unless necessary.
 Choose meaningful variable names (userAge, totalMarks, etc.).
 Declare variables at the top of their scope.

Summary
Concept Description
Variable A container for storing data
let Preferred for changing data
const For constants and fixed values
var Older keyword, function-scoped
Scope Where the variable is accessible (global, block, function)
Dynamically Typed Variable types can change

Class Exercises
1. Declare three variables: name, age, and city. Print them in a full sentence.
2. Write a program that calculates the circumference of a circle using const for π.
3. Demonstrate the difference between let and var in block scope.
Client-Side Scripting: JavaScript Operators
Lecture Objectives:
By the end of this lecture, students should be able to:
 Understand what operators are in JavaScript.
 Identify and use various types of JavaScript operators.
 Apply operators in expressions to manipulate values and make decisions.

What are JavaScript Operators?


Operators are special symbols or keywords used to perform operations on variables and values.
These operations include:
 Arithmetic (addition, subtraction, etc.)
 Comparisons (equal to, greater than, etc.)
 Logical operations (and, or, not)
 Assignments (store a value in a variable)
 Others (type, concatenation, conditionals)
Example:
let x = 10 + 5; // Here, '+' is an arithmetic operator

Types of JavaScript Operators


Operator Type Description
Arithmetic Operators Perform basic mathematical operations
Assignment Operators Assign values to variables
Comparison Operators Compare two values
Logical Operators Combine multiple conditions
String Operators Used for string concatenation
Unary Operators Operate on a single operand
Ternary Operator Shortcut for if...else condition
Type Operators Determine data types
Operator Type Description
Bitwise Operators Perform binary operations (advanced)

3. Arithmetic Operators
Operator Description Example (x = 10, y = 5) Result
+ Addition x + y 15

- Subtraction x - y 5

* Multiplication x * y 50

/ Division x / y 2

% Modulus (remainder) x % y 0

** Exponentiation x ** 2 100

++ Increment ++x 11

-- Decrement --x 9

Example:
let a = 7, b = 3;
[Link](a + b); // 10
[Link](a % b); // 1

Assignment Operators
Operator Description Example Equivalent To
= Assign value x = 10 x = 10

+= Add and assign x += 5 x = x + 5

-= Subtract and assign x -= 2 x = x - 2


*= Multiply and assign x *= 3 x = x * 3
/= Divide and assign x /= 4 x = x / 4

%= Modulus and assign x %= 2 x = x % 2


Example:
let x = 10;
x += 5; // x becomes 15

Comparison Operators
Used to compare two values, returning a boolean (true or false).
Operator Description Example Result
== Equal to (loose comparison) 5 == '5' true
=== Equal value and type 5 === '5' false

!= Not equal 5 != '5' false

!== Not equal value or type 5 !== '5' true

> Greater than 10 > 5 true

< Less than 2 < 3 true

>= Greater than or equal to 5 >= 5 true

<= Less than or equal to 4 <= 3 false

Logical Operators
Used to combine conditions, mostly in control flow.
Operator Description Example Result
&& Logical AND (a > 5 && b < 10) true if both true
` ` Logical OR
! Logical NOT !(a > b) Inverts result
Example:
let a = 10, b = 20;
if (a < 15 && b > 15) {
[Link]("Both conditions are true");
}

String Operators
The + operator is used to concatenate strings.
Example:
javascript
CopyEdit
let firstName = "Lindah";
let lastName = "Sawe";
let fullName = firstName + " " + lastName;
[Link](fullName); // Output: Lindah Sawe
Unary Operators
Operate on a single operand.
Operator Description Example Result
typeof Returns data type typeof 123 "number"
! Logical NOT !true false

++ Increment x++ Adds 1


-- Decrement x-- Subtracts 1

Ternary Operator (?:)


A shortcut for if...else statements.
Syntax:
condition ? value_if_true : value_if_false;
Example:
let age = 18;
let access = (age >= 18) ? "Granted" : "Denied";
[Link](access); // Output: Granted

Type Operators
Operator Description
typeof Returns the type of a variable
instanceof Checks if an object is an instance of a class or constructor

Example:
let num = 10;
[Link](typeof num); // "number"
[Link]([] instanceof Array); // true

Bitwise Operators (Advanced)


Used for binary operations.
Operator Symbol Description
AND & Bits that are set in both
OR | Bits that are set in either
XOR ^ Bits set in one, not both
NOT ~ Inverts all the bits
Shift Left << Shifts bits left
Shift Right >> Shifts bits right

Summary
Operator Type Common Examples Usage Example
Arithmetic +, -, *, / x + y

Assignment =, +=, -= x += 10

Comparison ==, ===, >, < a === b

Logical &&, `

String + for concatenation "Hi " + name

Ternary ? : age >= 18 ? "Yes" : "No"

Unary/Type typeof, ! typeof x, !true

Practice Exercises
1. Declare two variables and use arithmetic operators to calculate their sum, difference,
product, and quotient.
2. Use comparison and logical operators in an if statement to check if a user is eligible to
vote.
3. Concatenate a first name and last name using the string + operator.
4. Use a ternary operator to assign a message based on a score (>=50 = "Pass", else "Fail").
5. Use typeof to check the data types of a string, a number, and a boolean.

JavaScript Functions – Detailed Lecture Notes


Introduction to Functions
A function is a block of code designed to perform a particular task. It is executed when it is
"called" or "invoked".
✅ Why Use Functions?
 Reusability: Define once, use many times.
 Modularity: Break a program into smaller, manageable chunks.
 Maintainability: Easier to update and debug.
Defining a Function
Syntax:
function functionName(parameters) {
// code to be executed
}
Example:
function greet(name) {
[Link]("Hello, " + name + "!");
}

Calling/Invoking a Function
To execute a function, use its name followed by parentheses:
greet("Lindah"); // Output: Hello, Lindah!

Function Parameters and Arguments


 Parameters are placeholders in function definitions.
 Arguments are actual values passed to the function.
Example:
function add(a, b) {
return a + b;
}
[Link](add(5, 3)); // Output: 8

Return Statement
 The return statement ends function execution and specifies a value to be returned.
Example:
function square(x) {
return x * x;
}
[Link](square(4)); // Output: 16
⚠️Functions that do not have a return statement return undefined.
Function Expressions
Functions can be assigned to variables. These are called function expressions.
Example:
const multiply = function(x, y) {
return x * y;
};
[Link](multiply(3, 4)); // Output: 12

Arrow Functions
A shorter syntax for writing function expressions.
Syntax:
const functionName = (parameters) => {
// code
};
Example:
const greet = (name) => {
[Link]("Hello, " + name);
};
greet("Sawe"); // Output: Hello, Sawe
If there’s only one parameter and one return statement:
const square = x => x * x;
[Link](square(5)); // Output: 25

Function Scope
 Local Scope: Variables declared inside a function are local to that function.
 Global Scope: Variables declared outside any function are global.
Example:
let globalVar = "I am global";

function testScope() {
let localVar = "I am local";
[Link](globalVar); // Accessible
[Link](localVar); // Accessible
}

testScope();
[Link](localVar); // Error: localVar is not defined

Default Parameters
Functions can have default values for parameters.
Example:
function greet(name = "Guest") {
[Link]("Hello, " + name);
}
greet(); // Output: Hello, Guest

Rest Parameters and Arguments Object


Used to represent an indefinite number of arguments:
function sum(...numbers) {
return [Link]((a, b) => a + b);
}
[Link](sum(1, 2, 3, 4)); // Output: 10
✅ arguments Object:
Available in traditional functions only, not arrow functions.
function showArgs() {
[Link](arguments);
}
showArgs("a", "b", "c");

Recursive Functions
A function that calls itself.
Example:
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
[Link](factorial(5)); // Output: 120
Immediately Invoked Function Expressions
Executed right after being defined.
Example:
(function() {
[Link]("IIFE executed!");
})();

Callback Functions
A function passed as an argument to another function.
Example:
function greetUser(name, callback) {
[Link]("Hello, " + name);
callback();
}

function sayBye() {
[Link]("Goodbye!");
}

greetUser("Lindah", sayBye);

Anonymous Functions
Functions without names, often used as callbacks.
setTimeout(function() {
[Link]("This runs after 2 seconds");
}, 2000);

Pure vs Impure Functions


 Pure: Same input always gives same output, no side effects.
 Impure: Depends on external state or causes side effects.

✅ Summary Table
Concept Description Example
Function Declaration function name() {} function greet() {}

Function Expression Assign function to variable const f = function() {}

Arrow Function Short form for function expressions const f = () => {}


Parameters Placeholders in function definition function sum(a, b)
Arguments Actual values passed sum(5, 3)

Return Statement Returns a value from a function return x + y;

Scope Where variables are accessible local vs global

IIFE Runs immediately after definition (function() {})();

Callback Function as argument setTimeout(callback, 1000)

You might also like