Lecture 7
The Basics of JavaScript
Lecturer: Dr G Marandu
Overview
● Overview of JavaScript
● Object Orientation
● Syntactic Characteristics
● Primitives, Operations and Expressions
● Math, Number, String and Date objects
● Screen Output
● Control Statements, Arrays and Functions
Origins of JavaScript
● Originally developed by Netscape, as
LiveScript
● Became a joint venture of Netscape and Sun
in 1995, renamed JavaScript
● Now standardized by the European Computer
Manufacturers Association as ECMA-262
● An HTML-embedded scripting language
● We’ll call collections of JavaScript code
scripts, not programs
JavaScript and Java
● JavaScript and Java are only related
through syntax
● JavaScript is dynamically typed
● JavaScript’s support for objects is very
different
● JavaScript is interpreted
• Source code is embedded inside HTML
doc, there is no compilation
JavaScript and TypeScript
● Core Concept:
• JavaScript: Dynamic, interpreted
language for web interactivity
• TypeScript: Microsoft-developed
superset of JavaScript adding static
typing
● Main Differences:
• Types: JavaScript checks at runtime:
TypeScript checks at compile time.
• Excution: JavaScript runs natively:
Continue...
● When to Use:
• JavaScript: Small projects, rapid
prototyping or simple scripts.
• TypeScript: Large codebases, big teams
and enterprise applications
JavaScript Execution
Environment
● JavaScript scripts are executed entirely
by the browser (e.g Chrome, FireFox).
● The browser provides:
• Memory (variables, functions)
• APIs (DOM, timers, events)
● Scripts are downloaded from the server
and run locally in the browser.
● After loading, excution happens entirely
on the client side.
JavaScript Engines
● A JavaScript engine is a program that
reads and execute JS code
● Example:
• V8(Chrome),
• SpiderMonkey(FireFox)
● Responsibilities:
• Parse Code
• Interpet
• Execute instructions
Execution Behavior in
Browser
● JavaScript runs after being downloaded.
● No constant communication with server
during execution.
● However, JavaScript can send HTTP
requests for:
• Fetch data (APIs)
• Load new Pages
● Enables dynamic and interactive web
applications.
Executing JavaScript
Outside Browser & Impact
● JavaScript can run outside browser
using runtime environment called
[Link].
● Used for:
• Backend development
• File Systems
• Servers
● Impact:
• Enable Full stack development with one
language.
Continue…
● Impact continue…:
• Improves scalability and performance
• Full System access (unlike browser
sandbox)
• Faster execution (no ui overhead)
Uses of JavaScript
● Frontend Development (Client side)
• Create Interactive and dynamic web pages
in the browser
● Backend Development (server-side)
• Handles server logic, APIs and data
processing e.g [Link]
● User interaction and Events
• Capture actions like clicks, typing and form
input
• Enables features such as input validation
and real time feedback
Continue...
● DOM Manipulation
• Dynamically updates HTML and CSS to
modify page content and structure.
● e.t.c
Object Orientation
● JavaScript is NOT an object-oriented
programming language
• Rather object-based
● Does not support class-based inheritance
• Cannot support polymorphism
● JavaScript objects are collections of properties,
which are like the members of classes in Java
• Data and method properties
● JavaScript has primitives for simple types
● The root object in JavaScript is Object – all
objects are derived from Object
Embedding in HTML docs
● Either directly, as in
<script type = “text/javascript”>
-- JavaScript script –
</script>
● Or indirectly, as a file specified in the
src attribute of <script>, as in
<script type = “text/javascript”
src = “[Link]”>
</script>
Embedding in HTML docs
● Example
<html>
<head><title>Hello World</title></head>
<body>
<script type="text/javascript">
[Link]("Hello World")
</script>
</body>
</html>
JavaScript Syntax (Key
Rules)
● Case sensitivity:
– JavaScripts treats name, Name and NAME as different
identifiers
● Comments:
– Single-line: // comment
– Multi-line: /* comment */
● Scripts are usually hidden from browsers that do not include
JavaScript interpreters by putting them in special comments
<!--
-- JavaScript script –
//-->
● Semicolons:
• Optional but recommended
• JavaScript may automatically insert them
• Can sometimes cause unexpected behavior.
Variables in JavaScript
● Variables are named storage locations for data values
● Used to store, update and reuse information in programs
● Variables can be declared using:
– Var → Old way, function-scoped, can be redeclared
– Let → Modern, block-scoped, value can change.
– Const → Block-scoped, fixed value (can not be
reassigned)
● Examples:
• var x = 40;
• let age = 30;
• const name = “John”;
Rules for Naming Variables
● Must begin with letter, _, or $
● Can not start with a number
● Case-sensitive
● Reserved keywords can not be used as variable name
● Use meaningful names
● Examples:
– let studentName = “Alice”;
– let _score = 90;
– let $price = 100;
JavaScript Data Types
● Primitives types (single values)
– String: “Hello”
– Number: 25
– Boolean: true / false
– Null: null
– Undefined: variable declared but not assigned
● Non-primitives types:
– Objects, Arrays
Continue...
● let text = “HI”;
● let num = 10;
● let obj = {
name: “John”,
age: 20
}
Memory in JavaScript (Stack
& Heap)
● Stack memory
– Stores primitives values
– Fast access and fixed sizes
● Heap memory
– Stores objects and complex data
● Example
– Let x = 10; // stored in stack
– Let person = {name: “John”} // object stored in heap
Continue...
JavaScript Operators
● Operators are symbols used to perform operations on
values/variables
● Example:
– let a = 10 + 5
– “+” is an operator operations on values 10 and 5
● Operators include, Arithmetic Operators, Assignment
Operator, Comparison Operators, Logical Operators e.t.c
Arithmetic Operators
● Used for mathematical Operations
● They include
– “ + “ → For addition
– “ - “→ For Subtraction
– “ * ” → For Multiplication
– “ / ” → For Division
– “ % ” → For modulus
Assignment Operators
● Used to assign or update Values
● They include =, +=, -=, *=, /=
● Example
– let x = 10;
– x += 5; // x = 15
– x *= 2; // x = 30
Comparison Operators
● Used to compare values and return either true or false
● Include ==, ===, !=, >, <, >=, <=
● Example:
– [Link](5 == “5”) // true
– [Link](5 === “5”) // false
Logical Operators
● Used to combine conditions
● && (AND), || (OR), !(NOT)
● Example:
let age = 20;
[Link](age > 18 && age < 30); // true
Numeric Operators
Precedence
Math and Number Objects
Overview
● JavaScript provides built-in objects for
numeric operations
– Math → advanced mathematical functions
– Number → Number handling and
formatting
Math Object
● Used for mathematical calculations
● No need to create (built-in)
● Common methods
– [Link]() → rounds number
– [Link]() → rounds down
– [Link]() → rounds up
– [Link]() → random number (0,- 1)
● Examples
– [Link]([Link](4.6); // 5
– [Link]([Link]()); // 0 to 1
More Math Functions
● [Link]() → largest value
● [Link]() → Smallest value
● [Link]() → Power of a number
● [Link]() → square root
● Examples
– [Link]([Link](3, 7, 2)); // 7
– [Link]([Link](16)); // 4
– [Link]([Link](2, 3)); // 8
Number Object
● Represents numeric values
● Provides methods for formatting and
conversion
● Common methods:
– toFixed(n) → decimal places
– toString() → convert to string
– parseInt() → String to integer
● Examples:
– let num = 12.3456;
– [Link]([Link](2); // 12.35
String Object
● Used to work with text
● Strings can be created using quotes (single
or double)
● Common methods
– length → number of characters
– toUpperCase() / toLowerCase()
– includes() → check text
– slice() → extract part of the string
Continue...
● Examples:
– let text = “Hello world”;l
– [Link]([Link]());// HELLO
WORLD
● More String operations
– replace() → replace text
– trim() → remove spaces
– charAt() → get character at position
Date Object
● Used to work with dates and time
● Create using new Date()
● Example:
– let now = new Date();
– [Link](now);
● Date methods includes
– getFullYear() → Year
– getMonth() → month(0 – 11)
– getDate() → day of month
– getHours() → hour
Screen Output
● JavaScript models the HTML document with the Document object
● The model for the browser display window is the Window object
• The Window object has two properties, document and window,
which refer to the Document and Window objects, respectively
● The Document object has a method, write, which dynamically
creates content
• The parameter is a string, often concatenated from parts, some of
which are variables
[Link]("Answer: “, result, "<br>");
• The parameter is sent to the browser, so it can be anything that can
appear in an HTML document (any HTML tags)
Screen Output
● The Window object has three methods for
creating dialog boxes
1. Alert
alert(“The sum is:” + sum + ”\n");
• Parameter is plain text, not HTML
• Opens a dialog box which displays the
parameter string and an OK button
• It waits for the user to press the OK button
Screen Output
2. Confirm
const question = confirm("Do you
want to continue this download?");
• Opens a dialog box and displays the
parameter and two buttons, OK and Cancel
• Returns a Boolean value, depending on
which button was pressed (it waits for one)
Screen Output
3. Prompt
prompt("What is your name?", “ ");
• Opens a dialog box and displays its string parameter,
along with a text box and two buttons, OK and Cancel
• The second parameter is for a default response if the
user presses OK without typing a response in the text
box (waits for OK)
Conditionals
● Selection statements – “if” and “if…else“
if (a > b)
[Link](“a is greater than b <br>”);
else {
a = b;
[Link](“a was not greater than b, now
they are equal <br>”);
}
● The switch statement
[Link]
Conditionals : The switch statement
switch (bordersize) {
case "0":[Link]("<table>");
break;
let bordersize;
case "1": [Link]("<table
bordersize =
border = '1'>");
prompt("Select a table
break;
border size \n" +
case "4": [Link]("<table
"0 (no border)," +
border = '4'>");
"1 (1 pixel border), " + break;
"4 (4 pixel border), "+ case "8": [Link]("<table
"8 (8 pixel border)"); border = '8'>");
break;
default: [Link]("Error -
invalid choice: ",
bordersize, "<br>");
}
Loops
● while (control_expression)
statement or compound stmt
● for (init; control; increment)
statement or cmpnd stmt
• init can have declarations, but the scope of
such variables is the whole script
• [Link]
● do statement or compound
while (control_expression)
Arrays
● Array elements can be primitive values or
references to other objects
● Array objects can be created in two ways, with
new, or by assigning an array literal
var myList = new Array(24, "bread", true);
var myList2 = new Array(24);
var myList3 = [24, "bread", true];
● Length is dynamic - the length property stores
the length
• length property is writeable
[Link] = 150;
Functions
function function_name([formal_parameters]) {
-- body –
}
● Return value is the parameter of return
• If there is no return or if return has no
parameter, undefined is returned
● We place all function definitions in the head of
the HTML document
• Calls to functions appear in the document body
● Variables explicitly declared in a function are
local
Functions – parameters
● Parameters are passed by value, but when a
reference variable is passed, the semantics
are pass-by-reference
● There is no type checking of parameters, nor
is the number of parameters checked
• excess actual parameters are ignored, excess
formal parameters are set to undefined
● All parameters are sent through a property
array, arguments, which has the length
property
[Link]
Summary
● Overview of JavaScript
● Object Orientation
● Syntactic Characteristics
● Primitives, Operations and Expressions
● Math, Number, String and Date objects
● Screen Output
● Control Statements, Arrays and
Functions