0% found this document useful (0 votes)
18 views16 pages

JavaScript Basics: Interactive Web Programming

Introduction to javascript notes

Uploaded by

Steve Kinyanjui
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)
18 views16 pages

JavaScript Basics: Interactive Web Programming

Introduction to javascript notes

Uploaded by

Steve Kinyanjui
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 high-level, dynamic programming language used to


make web pages interactive. It is a core technology of the World Wide Web,
alongside HTML and CSS.

JavaScript is a versatile, dynamically typed programming language used for


interactive web applications, supporting both client-side and server-
side development, and integrating seamlessly with HTML, CSS, and a rich
standard library.

 JavaScript is a single-threaded language that executes one task at a


time.

 It is an Interpreted language which means it executes the code line by


line.

 The data type of the variable is decided at run-time in JavaScript that’s


why it is called dynamically typed.

“Hello, World!” Program in Browser Console

A “Hello, World!” program is the simplest way to get started with any
programming language. Here’s how you can write one using JavaScript.

<html>
<head></head>
<body>
<h1>Check the console for the message!</h1>
<script>
// This is our first JavaScript program
[Link]("Hello, World from console..!");
alert("Hello, World from alert..!");
</script>
</body>
</html>

In this example

The <script> tag is used to include JavaScript code inside an HTML


document.

[Link]() prints messages to the browser’s developer console. Open the


browser console to see the “Hello, World!” message.
“Hello World” Program in Server Console

We can also print the “Hello World” program directly into the console
terminal without embedded it into HTML. Create an [Link] file and add the
code to it.

/* This is a multi-line comment.

It can span several lines. */

[Link]("Hello, World from the console..!"); // Prints Hello, World! to the


console

In this example

[Link](): The [Link]() method is used to print messages to the


browser’s developer console. Open the console (usually with F12 or Ctrl +
Shift + J) to see the message “Hello, World!” displayed.

Comments in the Code:

 Multi-line Comment: The /*…… */ syntax is used to write a comment


spanning multiple lines.
 Single-line Comment: The // syntax is used for short, inline
comments, like the one explaining the [Link] function.

Key Features of JavaScript

 Client-Side Scripting: JavaScript runs on the user’s browser, so has a


faster response time without needing to communicate with the server.

 Versatile: JavaScript can be used for a wide range of tasks, from


simple calculations to complex server-side applications.

 Event-Driven: JavaScript can respond to user actions (clicks,


keystrokes) in real-time.

 Asynchronous: JavaScript can handle tasks like fetching


data from servers without freezing the user interface.
 Rich Ecosystem: There are numerous libraries and frameworks built
on JavaScript, such as React, Angular, and [Link], which make
development faster and more efficient.

Client Side and Server Side nature of JavaScript

 Client-side: Involves controlling the browser and its Document Object


Model (DOM), handling user events like clicks and form inputs.
Libraries such as AngularJS, ReactJS, and VueJS are commonly used.

 Server-side: Involves interacting with databases, manipulating files,


and generating responses. With [Link] and frameworks like
[Link], JavaScript is also widely used on the server side.

 Imperative Programming: Focuses on how to perform tasks,


controlling the flow of computation. It includes approaches like
procedural and object-oriented programming, often using constructs
like async/await to handle actions.

 Declarative Programming: Focuses on what should be done rather


than how it’s done. It emphasizes describing the desired result, like
with arrow functions, without detailing the steps to achieve it.

Applications of JavaScript

 Web Development: JavaScript adds interactivity and dynamic


behavior to static websites, with popular frameworks
like AngularJS enhancing development.

 Web Applications: JavaScript powers robust web applications,


leveraging APIs, React, and Electron to create dynamic user
experiences like Google Maps.

 Server Applications: [Link] brings JavaScript to the server side,


enabling powerful server applications and full-stack development.

 Game Development: JavaScript, combined with HTML5 and libraries


like Ease JS, enables the creation of interactive games for the web.

 Smartwatches: Pebble JS allows JavaScript to run on smartwatches,


supporting apps that require internet connectivity.
Limitations of JavaScript

 Security Risks : JavaScript can be used for attacks like Cross-Site


Scripting (XSS), where malicious scripts are injected into a website to
steal data by exploiting elements like <img>, <object>, or <script>
tags.

 Performance : JavaScript is slower than traditional languages for


complex tasks, but for simple tasks in a browser, performance is
usually not a major issue.

 Complexity : To write advanced JavaScript, programmers need to


understand core programming concepts, objects, and both client- and
server-side scripting, which can be challenging.

 Weak Error Handling and Type Checking : JavaScript is weakly


typed, meaning variables don’t require explicit types. This can lead to
issues as type checking is not strictly enforced.

Why JavaScript is known as a lightweight programming language ?

 JavaScript is considered a lightweight language due to its low CPU


usage, minimalist syntax, and ease of implementation.
 With no explicit data types and a syntax similar to C++ and Java, it’s
easy to learn and runs efficiently in browsers.
 Unlike heavier languages like Dart or Java, JavaScript, especially
with [Link], performs faster and uses fewer resources.
 While it has fewer built-in libraries, this makes it more flexible,
though external libraries are often needed for advanced functionality.
 JavaScript’s efficiency and simplicity make it a top choice for web
development.

Is JavaScript Compiled or Interpreted or both ?

JavaScript is both compiled and interpreted. The V8 engine improves


performance by first interpreting code and then compiling frequently used
functions for speed. This makes JavaScript efficient for modern web apps. It’s
mainly used for web development but also works in other environments.

Just-In-Time (JIT) compilation is a technique used by JavaScript engines


(like V8) to improve performance. How it works:

 Interpretation: Initially, the code is interpreted line-by-line by the


engine.
 Hot Code Detection: The engine identifies frequently executed code,
such as often-called functions.

 Compilation: The “hot” code is compiled into optimized machine code


for faster execution.

 Execution: The compiled machine code is then executed directly,


improving performance compared to repeated interpretation.

 JIT compilation balances between interpretation (for quick startup) and


compilation (for faster execution).

Discuss JavaScript Versions, features and their year of release?

JavaScript Syntax

JavaScript syntax refers to the rules and conventions dictating how code is
structured and arranged within the JavaScript programming language. This
includes statements, expressions, variables, functions, operators and control
flow constructs.

Syntax meaning in coding

In coding, “syntax” refers to the set of rules that defines the structure and
format of the code in a programming language. It dictates how code should
be written so that it can be correctly interpreted and executed by the
compiler or interpreter.

Adding JavaScript in HTML Document

To add JavaScript in HTML document, several methods can be used. These


methods include embedding JavaScript directly within the HTML file or
linking an external JavaScript file.

JavaScript code is embedded in HTML using the <script> tag. The script can
be added using several methods i.e.

1. Inline JavaScript

Writing JavaScript code directly inside the HTML element using the onclick,
onmouseover, or other event handler attributes. E.g.

<html>
<head></head>
<body>
<h2> Adding JavaScript in HTML Document </h2>
<button onclick="alert('JavaScript Button Clicked..!')"> Click Here
</button>
</body>
</html>

2. Internal JavaScript (Within <script> Tag)

You can write JavaScript code inside the <script> tag within the HTML file.
This is known as internal JavaScript and is commonly placed inside the
<head> or <body> section of the HTML document.

i. JavaScript Code Inside <head> Tag

Placing JavaScript within the <head> section of an HTML document ensures


that the script is loaded and executed as the page loads. This is useful for
scripts that need to be initialized before the page content is rendered.

<html>
<head>
<script>
function myFun() {
[Link]("demo")
.innerHTML = "This content is from JavaScript Code Inside
head Tag..!";
}
</script>
</head>
<body>
<h2>Add JavaScript Code inside Head Section </h2>
<h3 id="demo" style="color:green;"> To demostrate JavaScript
Code Inside head Tag </h3>
<button type="button" onclick="myFun()"> Click Here </button>
</body>
</html>

ii. JavaScript Code Inside <body> Tag


JavaScript can also be placed inside the <body> section of an HTML page.
Typically, scripts placed at the end of the <body> load after the content,
which can be useful if your script depends on the DOM being fully loaded.

<html>
<head></head>
<body>
<h2> Add JavaScript Code inside Body Section </h2>
<h3 id="demo" style="color:green;"> To demostrate JavaScript Code
Inside body Tag </h3>
<button type="button" onclick="myFun()"> Click Here </button>
<script>
function myFun() {
[Link]("demo")
.innerHTML = " This content is from JavaScript Code Inside body
Tag..!";
}
</script>
</body>
</html>

iii. External JavaScript (Using External File)

For larger projects or when reusing scripts across multiple HTML files, you
can place your JavaScript code in an external .js file. This file is then linked to
your HTML document using the src attribute within a <script> tag.

HTML:

<html>
<head>
<script src="[Link]"></script>
</head>
<body>
<h2> External JavaScript </h2>
<h3 id="demo" style="color:green;"> To demonstrate External
JavaScript </h3>
<button type="button" onclick="myFun()"> Click Here </button>
</body>
</html>
JavaScript:

/* Filename: [Link]*/

function myFun () {

[Link]('demo')

.innerHTML = 'This content is from external JavaScript'

Advantages of External JavaScript

 Faster Page Load Times: Cached external JavaScript files don’t need
to be reloaded every time the page is visited, which can speed up
loading times.

 Improved Readability and Maintenance: Keeping HTML and


JavaScript separate makes both easier to read and maintain.

 Separation of Concerns: By separating HTML (structure) and


JavaScript (behavior), your code becomes cleaner and more modular.

 Code Reusability: One external JavaScript file can be linked to


multiple HTML files, reducing redundancy and making updates easier.

Asynchronous and Deferred JavaScript

JavaScript can be loaded asynchronously or deferred to optimize page


performance, especially for larger scripts.
By default, JavaScript blocks the rendering of the HTML page until it is fully
loaded, but using async or defer can help improve load times.

1. async Attribute
This attribute loads the script asynchronously, i.e. the script will be
downloaded and executed as soon as it is available, without blocking the
page.
<script src="[Link]" async></script>

2. defer Attribute
This attribute delays the execution of the script until the entire HTML
document has been parsed. This is particularly useful for scripts that
manipulate the DOM.
<script src="[Link]" defer></script>
Referencing External JavaScript Files
There are three ways to reference an external script in JavaScript:
 By using a full URL: src = "[Link]
 By using a file path: src = "/js/[Link]"
 Without using any path: src = "[Link]"

JavaScript Output:

JavaScript can "display" data in different ways:

 Writing into an HTML element, using innerHTML.

 Writing into the HTML output using [Link]().

 Writing into an alert box, using [Link]().

 Writing into the browser console, using [Link]().

1. Using innerHTML

To access an HTML element, JavaScript can use the [Link](id)


method.

 The id attribute defines the HTML element.


 The innerHTML property defines the HTML content:

<!DOCTYPE html>
<html>
<body>
<h2>Inner HTML output</h2>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
2. Using [Link]()

For testing purposes, it is convenient to use [Link]():

<!DOCTYPE html>
<html>
<body>
<h2>Using [Link]</h2>
<script> [Link](5 + 6); </script>
</body>
</html>
Note: Using [Link]() after an HTML document is loaded, will delete
all existing HTML. Thus [Link]() method should only be used for
testing. E.g.

<!DOCTYPE html>
<html>
<body>
<h2>Using [Link] - deletes html </h2>
<p>Other html data that will be deleted also </p>
<button type="button" onclick="[Link](5 + 6)">Click Here
</button>
</body>
</html>

3. Using [Link]()

You can use an alert box to display data:

<!DOCTYPE html>
<html>
<body>
<h2>Using windows alert </h2>
<script>
[Link](5 + 6);
//alert(5 + 6);
</script>
</body>
</html>
You can skip the window keyword as shown under the commented line.
The window object is the global scope object. This means that variables,
properties, and methods by default belong to the window object. This
also means that specifying the window keyword is optional.

4. Using [Link]()

For debugging purposes, you can call the [Link]() method in the
browser to display data.

<!DOCTYPE html>

<html>

<body>

<h2>Using console </h2>

<script> [Link](5 + 6); </script>

</body>

</html>

JavaScript Print

JavaScript does not have any print object or print methods; thus you cannot
access output devices from JavaScript.

The only exception is that you can call the [Link]() method in the
browser to print the content of the current window.

<!DOCTYPE html>
<html>
<body>
<h2>Using windows print function: </h2>
<p>This will print the <b> current page </b> to either device, pdf
format etc.</p>
<button onclick="[Link]()">Print this page</button>
</body>
</html>

JavaScript Statements/code
JavaScript statements are programming instructions that a computer
executes. They are composed of:
 Values
 Operators
 Expressions
 Keywords
 Comments
This statement tells the browser to write a given data/ statement inside an
HTML element id. E.g.
[Link]("demo").innerHTML = "Internet application
Programming.";

The statements are executed, one by one, in the same order as they are
written.

JavaScript statements are separated by Semicolons. E.g.

 let x, y, z; // Declare 3 variables


 x = 5; // Assign the value 5 to x

Ending statements with semicolon is not required, but highly recommended.

JavaScript Keywords/Reserved words:

JavaScript statements often start with a keyword to identify the JavaScript


action to be performed. E.g.

Keyword Description
var Declares a variable
let Declares a block variable
const Declares a block constant
if Marks a block of statements to be executed on a condition
switch Marks a block of statements to be executed in different cases
for Marks a block of statements to be executed in a loop
function Declares a function
return Exits a function
try Implements error handling to a block of statements
Note: Reserved words cannot be used as names for variables.
Giving examples, discuss various types of JavaScript statements?

JavaScript Events:

JavaScript Events are actions or occurrences that happen in the


browser. They can be triggered by various user interactions or by the
browser itself. E.g.

<html>
<script>
function myFun() {
[Link](
"iap").innerHTML = "Click event triggered, for Internet
Application Programming";
}
</script>
<body>
<button onclick="myFun()">Click me </button>
<p id="iap"></p>
</body>
</html>
 The onclick attribute in the <button> calls the myFun() function
when clicked.

 The myFun() function updates the <p> element with id=”iap” by


setting its innerHTML to “Click event triggered, for Internet Application
Programming”.

 Initially, the <p> is empty, and its content changes dynamically on the
button click.
Event Types:

JavaScript supports a variety of event types. Common categories include:

 Mouse Events: click, dblclick, mousemove, mouseover, mouseout

 Keyboard Events: keydown, keypress, keyup

 Form Events: submit, change, focus, blur

 Window Events: load, resize, scroll

Common JavaScript Events

Event Description
Attribute
onclick Triggered when an element is clicked.
onmouseover Fired when the mouse pointer moves over an
element.
onmouseout Occurs when the mouse pointer leaves an
element.
onkeydown Fired when a key is pressed down.
onkeyup Fired when a key is released.
onchange Triggered when the value of an input element
changes.
onload Occurs when a page has finished loading.
onsubmit Fired when a form is submitted.
onfocus Occurs when an element gets focus.
onblur Fired when an element loses focus.

Event Handling Methods

1. Inline HTML Handlers

<button onclick="alert('Button clicked!')">Click Me</button>

Full code below:

<html>
<body>
<h2> Inline HTML Handlers </h2>
<button onclick="alert('Button clicked!')">Click Me</button>
</body>
</html>
2. DOM Property Handlers

let btn = [Link]("myButton");


[Link] = () => {
alert("Button clicked!");
};

3. addEventListener() (Preferred)

[Link]("click", () => {
alert("Button clicked using addEventListener!");
});

addEventListener() is the most versatile and recommended method as it


supports multiple event listeners and removal of listeners.

Practical Applications

1. Form Validation

<html>
<body>
<h2>Form Validation</h2>
<form id="formval">
<input type="text" placeholder="Enter some values"
id="formInput" />
<button type="submit">Submit</button>
</form>
<script>
[Link]("#formval").addEventListener("submit",
(e) => {
let input = [Link]("#formInput");
if (![Link]) {
[Link]();
alert("Input cannot be empty");
}
else{
alert("Something inserted into database.");
}
});
</script>
</body>
</html>

JavaScript Variables

You might also like