Lecture 2 - Basic JavaScript
Lecture 2 - Basic JavaScript
• Scripts could be simply written right into HTML in plain text and
are executed automatically when page loads.
<h1>Output</h1>
• writing into HTML element or
HTML output, <script>
• alert box, document.write(5 + 6);
alert(5 + 6);
• browser console. console.log(5 + 6);
</script>
</body>
</html>
Fundamentals: Syntax
<!DOCTYPE HTML> • A JavaScript program is list of statements
<html>
<body> (instructions).
<p>Before ... </p>
<script>
• Semicolons separate JavaScript statements.
alert( 'Hello, world!' );
</script>
• JavaScript statements are composed of
<p> After … </p>
values, operators, expressions, keywords, and
</body> comments.
</html>
Fundamentals: Syntax (2)
• Values: fixed values called literals (e.g., 10, "John") and variable
values called variables (x = 6;).
• Operators: this include such as arithmetic and assignment
operators to compute and assign values (e.g., +, -, =, etc.).
• Expressions: combination of values, variables, and operators,
which computes to a value (e.g., 5 * 10).
• Keywords are used to identify actions to be performed (e.g., to
define variables, let x, y;)
Fundamentals: Syntax (3)
• Identifiers: used to name variables and keywords, and functions.
• A name must begin with a letter, a dollar sign ($) or an underscore
(_) and following characters may be letters, digits, underscores, or
dollar signs.
• JavaScript is case sensitive; therefore, for example variables
firstName and firstname are different variables. LET or Let is not
the keyword let.
• Hypens are not allowed, but you can use underscore (first_name),
upper camel case (FirstName), or lower camel case (firstName) to
join multiple words.
Fundamentals: Comments
<!DOCTYPE HTML>
<html>
• Single line comments start with //.
<body>
let x = 5;
let y = (40 + 50) * y;
source:
https://www.w3schools.com/js/js_o
perators.asp
Operators and expressions: Assignment
source:
https://www.w3schools.com/js/js_o
perators.asp
Operators and expressions: Comparison
source:
https://www.w3schools.com/js/js_o
perators.asp
Operators and expressions: Logical and type
source:
https://www.w3schools.com/js/js_o
perators.asp
Control-flow: if-else statements
const time = 9; const time = 9;
• if statement: a block of code let greeting; let greeting;
to be executed if a condition is
true. // condition inside if if (time < 10) {
if (time < 10) { greeting = "Good morning";
greeting = "Good morning"; } else if (time < 20) {
• else statement: a block of } greeting = "Good day";
console.log(greeting); } else {
code to be executed if the greeting = "Good evening";
condition is false. const time = 9; }
let greeting; console.log(greeting);
fruits[1] = 'blueberry';
Modifying elements
console.log(fruits); // Output: ['apple', 'blueberry', 'cherry']
function.
Arrays: Methods (2)
const numbers = [1, 2, 3, 4, 5];
• reduce: Executes a reducer const sum = numbers.reduce((accumulator, currentValue)
function on each element of => accumulator + currentValue, 0);
the array, resulting in a single console.log(sum); // Output: 15
output value.
• find: Returns the value of the const numbers = [1, 2, 3, 4, 5];
const found = numbers.find(number => number > 3);
first element that satisfies the console.log(found); // Output: 4
provided testing function.
• some and every: Tests whether const numbers = [1, 2, 3, 4, 5];
some or all elements in the const someEven = numbers.some(number => number % 2
=== 0);
array pass the provided const allEven = numbers.every(number => number % 2 ===
function. 0);
console.log(someEven); // Output: true
console.log(allEven); // Output: false
Arrays: Multi-dimensional
• JavaScript arrays can also contain other arrays, creating multi-
dimensional arrays.
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[0][1]); // Output: 2
Objects
const person = {
name: 'John Doe',
• In JavaScript, an object is a data age: 30,
greet: function() {
structure (a variable) storing collections console.log('Hello!');
of related data in form of properties. }
};
• A property is a key-value pair holding
primitive values (string, number etc.),
functions, or even other objects.
• In JavaScript, almost "everything" is an
object: functions, dates, arrays etc.
• Objects can be modified at any time by
adding, updating, or removing properties.
Objects: Creation
// object literal notation • Using object literal notation one can
const person = {
name: 'John Doe', directly create an object as a variable.
age: 30,
greet: function() {
console.log('Hello, ' + this.name);
}
};
• Even the simplest object has Object as its prototype and other
objects can inherit prototypes from parent objects or constructor
functions.
Objects: Inheritance and prototypes (2)
• Each object references its parent prototype, forming a prototype
chain that links back through successive prototypes until it
reaches the Object prototype. The chain ends with Object, whose
prototype is null.
let x = "age";
• Bracket notation is useful
when the property name is console.log(person.firstName);
dynamic or contains console.log(person["lastName"]);
console.log(person[x]);
characters not valid in a
variable name.
Objects: Methods
const person = {
firstName: "Akif",
lastName: "Khan",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
• Methods are actions that
can be performed on // adding a new method to an object
objects. person.fullNameUpper = function () {
// using JavaScript methods
return (this.firstName + " " + this.lastName).toUpperCase();
};
• In JavaScript a method is a
// execute as a function
function definition stored console.log(person.fullName());
as a property value. console.log(person.fullNameUpper());
get area() {
return this.width * this.height;
}
set area(value) {
console.log('Area cannot be directly set. Use width and height properties.');
}
}