0% found this document useful (0 votes)
4 views

cs

The document provides an overview of JavaScript, covering its syntax, variable declaration, data types, operations, and event handling. It explains how to embed JavaScript in HTML, the importance of placement for performance, and various output methods. Additionally, it discusses coding conventions, comments, and practical examples for using functions and handling user interactions.

Uploaded by

azarethwrath
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

cs

The document provides an overview of JavaScript, covering its syntax, variable declaration, data types, operations, and event handling. It explains how to embed JavaScript in HTML, the importance of placement for performance, and various output methods. Additionally, it discusses coding conventions, comments, and practical examples for using functions and handling user interactions.

Uploaded by

azarethwrath
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

8.

1 JavaScript Syntax

1. What is JavaScript?
●​ JavaScript is a client-side scripting language that adds interactivity to web pages.
●​ It is loosely typed, meaning variables do not require explicit data types.
●​ Initially called LiveScript, later renamed JavaScript.

2. Using JavaScript in HTML


JavaScript can be embedded inside an HTML document using the <script> tag.

Embedded JavaScript
<script>
document.write("Hello World!");
</script>

External JavaScript
<script src="script.js"></script>

●​ Allows reuse across multiple web pages.


●​ Improves maintainability but adds HTTP requests.

Inline JavaScript
<a href="#" onclick="alert('Hello World!')">Click Me</a>

●​ Not recommended for complex scripts.

3. Where to Place JavaScript?


●​ Inside <head> → Loads before page content (used for setup scripts).
●​ At the end of <body> (recommended) → Ensures HTML loads first, improving
performance.

4. Basic JavaScript Syntax Rules


●​ Case-sensitive (myVar ≠ Myvar).
●​ Whitespace is ignored unless inside strings.
●​ Statements end with ; (good practice).
●​ Block {} groups multiple statements (e.g., functions, loops).

Example: Basic JavaScript Code


<script>
var score1 = 10;
var score2 = 20;
var total = score1 + score2;
document.write("Total: " + total);
</script>

5. JavaScript Output Methods


Method Description Example

document.writ Writes directly to the page (not document.write("Hello


e() recommended for permanent output). World!");

console.log() Logs output to the browser console. console.log("Debug


message");

alert() Displays a popup alert box. alert("Hello!");

Tip: Open the console using F12 → Select the "Console" tab.

6. JavaScript Coding Conventions


Convention Example

CamelCase for variables let firstName = "Juan";

Use spaces around let total = fee + (fee *


operators tax);

Keep line length ≤ 80 chars Split long lines after


commas/operators.

Use lowercase filenames script.js, app.js


7. JavaScript Comments
Comment Type Synta Example
x

Single-line // // This is a comment

Multi-line /* */ /* This is a multi-line


comment */

8. Example: JavaScript Function with Syntax Rules


<script>
function computeTotal() {
let fee = 20.00;
let tax = 0.21;
let total = fee + (fee * tax);
return total;
}
document.write("Total Fee: " + computeTotal());
</script>

●​ Uses camelCase for function and variable names.


●​ Spaces around operators improve readability.
●​ Function follows proper bracket placement.

●​ JavaScript enhances web interactivity and is loosely typed.


●​ Can be embedded via <script> tags (internal, external, or inline).
●​ Recommended placement is before </body> for better performance.
●​ Follows syntax rules: case-sensitive, semicolons, brackets, comments.
●​ Use document.write(), console.log(), alert() for output.

8.2 JavaScript Variable Declaration and Data Types

1. What is a Variable?
●​ A variable is a container for storing data.
●​ It can hold different values (numbers, strings, etc.).
●​ In JavaScript, variables can be declared using var, let, and const.
2. Declaring Variables
Using var (Global or Function Scope, Hoisted)
●​ Can be reassigned.
●​ Hoisted (can be used before declaration).

var x; // Declaration
var x = 5; // Initialization
x = 6; // Reassignment

Using let (Block Scope, No Hoisting)


●​ Cannot be redeclared in the same scope.

let y = 10;

// let y = 20; //❌


y = 15; // Allowed
Error (cannot redeclare)

Using const (Block Scope, Immutable)


●​ Must be initialized and cannot be reassigned.

const z = 25;
// z = 30; //❌Error (cannot reassign)

3. Naming Variables (Identifiers)


●​ Can contain letters, numbers, $, and _, but cannot start with a number.
●​ Reserved words cannot be used as variable names.
●​ Case-sensitive (var myVar ≠ var Myvar).
●​ Naming convention: camelCase (myVariableName).

4. JavaScript Data Types


Data Type Description

String Text enclosed in quotes ("Hello" or


'World').
Number Whole numbers or decimals (42, 3.14).

Boolean true or false.

Undefined A declared variable with no assigned value.

Null Represents "nothing" (intentional empty value).

Symbol Unique, immutable value (introduced in ES6).

Example of Data Types


let str = "Hello"; // String
let num = 42; // Number
let isTrue = true; // Boolean
let notDefined; // Undefined
let empty = null; // Null
let uniqueSym = Symbol("id"); // Symbol

5. String Operations
Concatenation (+ operator)
let message = "Oh hi, " + "Pisay!";
console.log(message); // "Oh hi, Pisay!"

Template Literals (Backticks `` `)


let name = "Pisay";
console.log(`Hello ${name}!`); // "Hello Pisay!"

String Methods
Method Description Example Output

.length Returns string length "Hello".length → 5

.concat() Joins strings "Hello".concat(" World") →


"Hello World"

.toUpperCas Converts to "hello".toUpperCase() → "HELLO"


e() uppercase
6. Number Operations
Basic Arithmetic
let sum = 5 + 3; // 8
let difference = 10 - 4; // 6
let product = 2 * 3; // 6
let quotient = 10 / 2; // 5

Scientific Notation (E-notation)


let largeNum = 7.215e7; // 72150000

Special Number Types


Type Description Example Output

NaN "Not a Number" 5 / "five" →


NaN

Infini Result of dividing by 0 1 / 0 →


ty Infinity

7. Boolean Data Type


●​ Represents true or false.
●​ Often used in conditions.

let isChecked = true;


console.log(7 > 8); // false
console.log("blue" === "blue"); // true

8. Undefined vs Null
Type Description Example Output

undefin A variable that has been declared but not let x; console.log(x); →
ed assigned a value. undefined

null An intentional empty value. let y = null;


console.log(y); → null
9. Practice Exercise
Create a JavaScript program that calculates the lifetime supply of your favorite snack.

1.​ Declare a variable for your current age.


2.​ Declare a maximum age.
3.​ Declare a daily consumption amount.

Compute the total required using:​


totalRequired = (numPerDay * 365) * (maxAge - age);

4.​
5.​ Display: "You will need NN to last you until the age of X".

●​ Variables store data and can be declared using var, let, or const.
●​ Data types include String, Number, Boolean, Undefined, Null, and Symbol.
●​ Strings can be concatenated using +, .concat(), or template literals ` `.
●​ Numbers support arithmetic and scientific notation.
●​ Booleans store true or false values.
●​ Undefined means a variable has no value, while null is an intentional empty value.

8.3 JavaScript Operations

Types of JavaScript Operators:


1.​ Arithmetic Operators
2.​ 8.2Comparison Operators
3.​ Logical Operators
4.​ Assignment Operators
5.​ Ternary Operators

1. Arithmetic Operators
Given: a = 20, b = 30

●​ Addition (+) → a + b = 50
●​ Subtraction (-) → a - b = -10
●​ Multiplication (*) → a * b = 600
●​ Division (/) → b / a = 1.5
●​ Modulus (%) → a % b = 20
●​ Increment (++)
○​ ++x → returns new value after increment
○​ x++ → returns current value, then increments
●​ Decrement (--)
○​ --x → returns new value after decrement
○​ x-- → returns current value, then decrements
●​ String Concatenation (+) → 5 + "Hello" → "5Hello"

Comparison Operators
Given: a = 20, b = 30

●​ Equal (==) → a == b → false


●​ Not Equal (!=) → a != b → true
●​ Greater Than (>) → a > b → false
●​ Less Than (<) → a < b → true
●​ Greater Than or Equal (>=) → a >= b → false
●​ Less Than or Equal (<=) → a <= b → true
●​ Strictly Equal (===) → a === "20" → false
●​ Strictly Not Equal (!==) → a !== "20" → true

Logical Operators
●​ Logical AND (&&)
○​ true && true → true
○​ "cat" && "dog" → "dog"
●​ Logical OR (||)
○​ false || false → false
○​ "cat" || "dog" → "cat"
●​ Logical NOT (!)
○​ !(5 == "5") → false
●​ Falsy values: null, 0, NaN, "", undefined

Assignment Operators
●​ Basic Assignment (=) → x = y
●​ Addition Assignment (+=) → x += y → x = x + y
●​ Subtraction Assignment (-=) → x -= y → x = x - y
●​ Multiplication Assignment (*=) → x *= y → x = x * y
●​ Division Assignment (/=) → x /= y → x = x / y
●​ Modulo Assignment (%=) → x %= y → x = x % y

Evaluation Practice
Given: var a = 10, b = 5, c = "10"​
Find x:

1.​ x = a + c; → "1010"
2.​ x = (a === c); → false
3.​ x = a / c; → 1
4.​ x = (a === b) || !c; → false
5.​ x = a * b; → 50
6.​ x = "hello" && a; → 10
7.​ x = c % a; → 0
8.​ x = !b && !a; → false
9.​ x = a * 6; → 60
10.​x = a + "Hi"; → "10Hi"

8.4 JavaScript Basic Statements

Input/Output (I/O) Statements in JavaScript


There are four main ways to display output and two ways to get input in JavaScript:

Ways to Display Output


1.​ console.log()​

○​ Displays output in the browser’s console.


○​ Used for debugging.
○​ Accessed through Developer Tools → Console tab.
2.​ alert()​

○​ Displays an alert dialog box.


○​ Used to show important messages to the user.
○​ Example: alert("Hello World!");
○​ Can use \n for line breaks.
3.​ document.write()​

○​ Writes output directly into the HTML document.


○​ If used after page load, it overwrites the entire page.
4.​ document.getElementById(id).innerHTML​

○​ Inserts output into a specific HTML element.

Example:​
document.getElementById("demo").innerHTML = "Hello World!";

○​ The script must be placed after the selected element to avoid errors.

Ways to Get Input


1.​ prompt()​

○​ Displays a dialog box with a text input field.


○​ Returns the input as a string.

Example:​
let name = prompt("Enter your name:");
alert("Hello, " + name);

○​ Can convert input to a number using parseInt(), parseFloat(), or Number().


2.​ confirm()​

○​ Displays a dialog box with “OK” and “Cancel” buttons.


○​ Returns true if “OK” is clicked and false if “Cancel” is clicked.

Example:​
let result = confirm("Do you agree?");
if (result) {
alert("You agreed!");
} else {
alert("You canceled!");
}

Note that:
●​ window.alert(), window.prompt(), and window.confirm() are valid but window is
optional.
●​ innerHTML is case-sensitive.
●​ document.write() is only recommended for testing purposes.

9.2 JavaScript Event Handlers

What are HTML Events?


HTML events occur when users interact with a webpage (e.g., clicking a button, loading a
page). These events can trigger JavaScript functions.

Event Handlers
Event handlers detect and respond to events. They are placed inside an HTML element’s
opening tag:

<element eventhandler="JavaScript code">

This reviewer covers onclick and onload event handlers.

1. onclick Event Handler


●​ Detects when an element is clicked.
●​ Can be used to change text, replace images, or call a function.

Examples
Alert Message on Click​

<p onclick="alert('So I click you, now what?')">Click Me.</p>

1.​
○​ Clicking the text will display an alert box.

Changing Text on Click​



<p onclick="this.innerHTML = 'It had been clicked'">Click Me.</p>

2.​
○​ this.innerHTML updates the element’s content.

Changing an Image on Click​


Inline JavaScript:​

<img onclick="this.src='img_girl.jpg'" src="smiley.gif" width="100">

3.​
○​ Clicking the image will replace it with img_girl.jpg.

Using a Function:​

<img id="image" onclick="changeImage()" src="smiley.gif" width="100">

<script>

function changeImage() {

document.getElementById("image").src = 'img_girl.jpg';

</script>

4.​
○​ Uses document.getElementById("image") to change the image.

2. onload Event Handler


●​ Triggers when a webpage or an HTML object loads.
●​ Often used for browser tests or styling changes.

Example: Changing Background Color on Page Load


<body id="dBody" onload="changeColor()">

<h1>Changing Color for Each Load</h1>


<script>

function changeColor() {

var red = Math.random() * 255;

var green = Math.random() * 255;

var blue = Math.random() * 255;

var dColor = "rgb(" + red + ","+green+","+blue+")";

document.getElementById("dBody").style.backgroundColor = dColor;

</script>

</body>

●​ The Math.random() function generates random RGB values.


●​ The background color changes every time the page loads

●​ HTML events occur when users interact with a webpage.


●​ Event handlers detect these events and trigger functions.
●​ onclick detects clicks and is used to change content, images, or trigger actions.
●​ onload executes functions when a webpage loads or refreshes.

9.3 Processing Function Output

How to Process Function Outputs in JavaScript


Functions allow reusable blocks of code, but their outputs need to be handled correctly to be
useful in the main program.

1. Printing a Function Output


Function outputs can be displayed using JavaScript I/O statements:

●​ document.getElementById(id).innerHTML
●​ alert()

Example: Printing Inside an HTML Element


<div id="div1"></div>

<script>

function getSum(a, b) {

sum = a + b;

document.getElementById('div1').innerHTML = sum;

getSum(1,2);

</script>

●​ Displays the sum inside div1.

Example: Displaying in an Alert Box

<script>

function getSum(a, b) {

sum = a + b;

window.alert(sum);

getSum(1,2);

</script>

●​ Displays the sum in an alert box.

Note: Variables inside a function are local variables and can only be accessed
within the function block.

2. Using the return Statement


●​ return passes a function’s output to a variable outside the function.

Example: Storing Output in a Variable

<script>

function getSum(a, b) {
sum = a + b;

return sum;

x = getSum(1,2);

</script>

●​ return sum; sends the result to x.

Note: The return statement can also end a function early.

Example: Using return to Stop Execution

<p id="demo"></p>

<script>

function myFunction() {

while (true) {

var number = prompt("Please enter a letter");

if (isNaN(number)) {

document.getElementById("demo").innerHTML = "It is a letter!";

return false;

myFunction();

</script>

●​ The loop continues until a letter (non-numeric input) is entered, then it stops execution.

3. Directly Printing Function Output


Instead of storing in a variable, a function can be called directly inside a print statement.
Example: Directly Printing to an HTML Element

<div id="demo"></div>

<script>

function getSum(a, b) {

sum = a + b;

return sum;

document.getElementById("demo").innerHTML = getSum(1,2);

</script>

●​ Calls getSum(1,2) and prints the output inside div.

Summary:
●​ Function outputs can be displayed using alert(),
document.getElementById(id).innerHTML, etc.
●​ The return statement passes function output to a variable outside the function.
●​ return can also be used to stop function execution.
●​ Function outputs can be directly used in print statements or operations.

9.4 Commonly Used JavaScript Objects

1. JavaScript Objects
●​ Objects store multiple values (properties).
●​ Objects have methods, which are functions specific to them.

2. Math Object and Methods


The Math object provides constants and methods for mathematical operations.

Mathematical Constants

Name Value Numerical Value


Math.E Euler’s number 2.718…
(e)

Math.PI Pi (π) 3.141…

Math.SQRT √2 1.414…
2

Math.SQRT √(1/2) 0.707…


1_2

Math.LN2 ln(2) 0.693…

Math.LN10 ln(10) 2.302…

Math.LOG2 log₂(e) 1.442…


E

Math.LOG10 log₁₀(e) 0.434…


E

Common Math Methods

Method Description Example Output

Math.round(x) Rounds to nearest Math.round(3.14) → 3


integer

Math.pow(x, y) Raises x to power y Math.pow(3, 4) → 81


Math.sqrt(x) Square root of x Math.sqrt(4) → 2

Math.abs(x) Absolute value Math.abs(-3) → 3

Math.ceil(x) Rounds up Math.ceil(3.14) → 4

Math.floor(x) Rounds down Math.floor(3.14) → 3

Math.sin(x), Math.cos(x) Trigonometric functions Math.sin(60 * Math.PI / 180)


(radians) → 0.866

Math.min(x, y, ...), Finds min/max value Math.min(6, 3, 1) → 1


Math.max(x, y, ...)

Math.random() Generates random Math.random() → 0.435…


number [0,1]

Example: Distance Formula Implementation


function getDistance(x1, y1, x2, y2) {

let d = Math.sqrt(Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2));

alert(d);

getDistance(2, 3, 3, 5);

Output: 2.236

3. String Methods and Properties


A string is a sequence of characters. Each character has an index, starting from 0.

Accessing Characters
let name = "Uzumaki Naruto";

console.log(name[0]); // "U"

console.log(name[7]); // " " (space)

console.log(name[20]); // undefined

Common String Methods

Method Description Example Output

.length Returns string length "Naruto".length → 6

.indexOf(str) Returns index of first "Naruto".indexOf("ru") → 2


occurrence of str

.slice(start, end) Extracts part of a string "Naruto".slice(2, 4) → "ru"

.replace(old, new) Replaces substring "Naruto".replace("ru", "tu") →


"Natuto"

.toUpperCase() Converts to uppercase "Naruto".toUpperCase() → "NARUTO"

.toLowerCase() Converts to lowercase "Naruto".toLowerCase() → "naruto"

.concat(str2) Joins strings "Naruto".concat(" Uzumaki") →


"Naruto Uzumaki"
.trim() Removes leading/trailing " Naruto ".trim() → "Naruto"
spaces

.charAt(index) Returns character at "Naruto".charAt(1) → "a"


index

.split(separator) Splits into array "Naruto Uzumaki".split(" ") →


["Naruto", "Uzumaki"]

Example: Replacing Vowels with _ and Uppercasing Consonants


function solveProblem(name) {

name = name.toUpperCase();

for (let i = 0; i < name.length; i++) {

if ("AEIOU".includes(name[i])) {

name = name.replace(name[i], "_");

alert(name);

solveProblem("Uzumaki Naruto");

Output: _Z_M_K_ N_R_T_

9.5 Commonly Used JavaScript Objects: Date and Number

1. The Number Object


JavaScript treats numbers as objects through the Number() object, allowing them to have
properties and methods.

Number Properties
Property Description Example Output

Number.MAX_VALUE Largest possible number in 1.7976931348623157


JS e+308

Number.MIN_VALUE Smallest possible number in 5e-324


JS

NaN "Not a Number" Number("Hi") → NaN

Number.POSITIVE_INF Values beyond MAX_VALUE Infinity


INITY

Number.NEGATIVE_INF Values below MIN_VALUE -Infinity


INITY

Number Methods
Method Description Example Output

Number(x) Converts x to a number Number("10") → 10

toString() Converts number to string (501).toString() → "501"

toFixed(x) Formats number to x decimal (4.567).toFixed(2) →


places "4.57"

toPrecision( Formats number to x total digits (4.567).toPrecision(2) →


x) "4.6"

parseInt(str Extracts integer from str parseInt("31.22") → 31


)

parseFloat(s Extracts floating number from parseFloat("31.22") →


tr) str 31.22

2. The Date Object


The Date() object allows manipulation of dates and times.

Creating Dates
let d = new Date(); // Current date and time
let d = new Date(2021, 0, 4, 10, 3, 59); // Jan 4, 2021, 10:03:59

Note:
●​ Months start from 0 (January = 0, December = 11).
●​ If only one argument is provided, it's treated as milliseconds since Jan
1, 1970, 00:00:00 UTC.

Example: Adjusting Time for Another Time Zone


let d = new Date();
let difference = 16 * 60 * 60 * 1000; // Convert 16 hours to milliseconds
let timeSF = new Date(d - difference);
alert(timeSF.toString()); // Displays adjusted time

Sample Output:

Current Time: Wed Jan 06 2021 11:15:43 GMT+0800


San Francisco Time: Tue Jan 05 2021 19:15:43 GMT+0800

10.1 Control Statements

1. What are Control Statements?


Control statements direct the flow of a program based on given conditions.

Types of Control Statements in JavaScript


1.​ if-else [if] statements
2.​ switch statements
3.​ for loops

2. Conditional Statements (if-else [if])


●​ Used to execute different actions based on conditions.

Syntax:
if (condition) {
// Executes if condition is true
}
else if (another condition) {
// Executes if first condition is false but second is true
}
else {
// Executes if all previous conditions are false
}

Example: Checking if a Number is Even or Odd


let x = 5;
if (x % 2 == 0) {
alert("The number is EVEN");
} else {
alert("The number is ODD");
}

3. Comparison & Logical Operators


Comparison Operators
Operator Description Example (if a =
2)

== Equal to a == 2 → TRUE

=== Equal value & type a === "2" →


FALSE

!= Not equal a != 3 → TRUE

!== Not equal in value & type a !== "2" →


TRUE

> Greater than a > 3 → FALSE

< Less than a < 3 → TRUE

>= Greater than or equal a >= 2 → TRUE

<= Less than or equal a <= 1 → FALSE

Logical Operators
Operator Description Example (a = 1, Output
b = 2)

&& (AND) True if both conditions are (a < b && a > TRUE
true 0)
` ` (OR) True if at least one condition
is true

! (NOT) Reverses condition’s !(a > 0) FALSE


result

4. Switch Statement
●​ Used when multiple conditions exist instead of using multiple if-else statements.

Syntax:
switch(expression) {
case value1:
// Executes if expression == value1
break;
case value2:
// Executes if expression == value2
break;
default:
// Executes if none of the cases match
}

Example: Grade to Letter Conversion


let grade = 75;
switch (true) {
case (grade < 60):
alert("E");
break;
case (grade < 70):
alert("D");
break;
case (grade < 80):
alert("C");
break;
default:
alert("B or A");
}

Note: break prevents further cases from executing if one case is met.

5. Loops (for loop)


●​ Used for repetitive tasks (e.g., printing numbers, iterating arrays).

Syntax:
for (start; condition; increment) {
// Code block to be executed
}

●​ start → Initial value of loop counter


●​ condition → Loop runs while this is true
●​ increment → Updates loop counter

Example: Sum of Numbers from 1 to a Given Number


function getSum(a) {
let sum = 0;
for (let i = 1; i <= a; i++) {
sum += i;
}
return sum;
}
alert(getSum(4)); // Output: 10

You might also like