Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Lecture 2 - Basic JavaScript

The document is a lecture on Basic JavaScript, covering essential topics such as variables, data types, operators, control-flow, functions, arrays, and objects. It introduces JavaScript as a scripting language for web development, explains how to place scripts in HTML, and discusses the syntax and structure of JavaScript code. Additionally, it highlights the capabilities and limitations of JavaScript in the browser environment, along with practical examples and best practices.

Uploaded by

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

Lecture 2 - Basic JavaScript

The document is a lecture on Basic JavaScript, covering essential topics such as variables, data types, operators, control-flow, functions, arrays, and objects. It introduces JavaScript as a scripting language for web development, explains how to place scripts in HTML, and discusses the syntax and structure of JavaScript code. Additionally, it highlights the capabilities and limitations of JavaScript in the browser environment, along with practical examples and best practices.

Uploaded by

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

Data1700 – Web Programming

Lecture 2: Basic JavaScript


Akif Q. Khan
Outline
• Introduction
• Fundamentals
• Variables and data types
• Operators and expressions
• Control-flow
• Functions
• Arrays
• Objects
• Classes
• Before we end
Introduction
• JavaScript is originally introduced to make web pages alive;
supported by all browsers and enabled by default.

• The programs developed in this language are referred as scripts.

• Scripts could be simply written right into HTML in plain text and
are executed automatically when page loads.

• JavaScript has standard specification called ECMAScript (ES5,


ES6, ES2016, 2018, 2020).
Introduction: Engines
• There is no need for a pre-compilation and could be run on any device
that has a JavaScript engine (e.g., browsers, servers etc.).

• There are different engines available such as V8 (Chrome, Opera,


Edge), SpiderMonkey (Firefox), Chakra (IE), SquirrelFish (Safari) etc.

• Different engines are important to be aware of to check whether certain


features are supported or not.

• Engines parse scripts, compile them to the machine code, and


optimize and run the code.
Introduction: JavaScript can (in browser)
• Add and remove HTML and new content and modify styles.
• Respond to user actions such as mouse clicks, key press, pointer
movement etc.
• Send network requests and download and upload files.
• Open dialogs with the visitors, display messages, and set and get
cookies.
• Store and access data locally (i.e., local storage).
• etc.
Introduction: JavaScript can not (in browser)
• Reading and writing files on local machine arbitrarily (possible
with certain actions such as dropping a file into browser window).

• Executing programs and accessing OS functions (possible with


explicit user permission).

• Getting information from other tabs/windows and other domains


unless there is a specific agreement (i.e., due to same origin
policy).
Fundamentals: Placing scripts
<!DOCTYPE HTML> • JavaScript code can be inserted almost
<html>
<body>
anywhere into an HTML document using
the <script> tag.
<p>Before ... </p>

<script> • We can put it into a separate file attached to


alert( 'Hello, world!' ); HTML with the src attribute. Good for
</script>
separation, easier to maintain, and allows
<p> After … </p> caching for quicker page loads:
</body>
</html> <script src="/path/to/script.js"></script>
Fundamentals: Output
<!DOCTYPE html>
• JavaScript can display <html>
output in several ways: <body>

<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>

<p>Before ... </p> • Multi-line comments start with /* and


<script> end with */.
Example code:
Simple script
*/ • It is most common to use single line
// a statement comments.
alert( 'Hello, world!' );
</script>
<p> After … </p>
• Block comments are often used for
</body> formal documentation.
</html>
Variables and data types
• A variable is a container for // automatically declared
a = 5;
storing data and could be b = 6;
declared using var, let, const c = a + b;
keywords.
• var is used in code for older // good practice to declare
let a = 5;
browsers; otherwise, we use let let b = 6;
to declare variables. let c = a + b;

• const is used if the value of the const a = 5;


variable is not to be changed. const b = 6;
const c = a + b;
Variables and data types (2)
• JavaScript has 8 data types
• String, let input= "It's alright";
• Number, let x = 36.00; let y = 36; (as decimal numbers, accurate until 15 digits).
• Bigint, let x = BigInt("82345678901230111");
• Boolean, let isEmployed = true; let isRetired = false;
• Undefined, a variable without a value has the value undefined.
• Null, a special value which represents “nothing”, “empty” or “value unknown”.
• Object: provide a way to group and organize related data and functionalities.
• Symbol, primarily used to create unique identifiers for object properties.
Variables and data types (3)
<script>
• Types in JavaScript are let x = 5;
dynamic, that is a console.log(typeof x);
x = "akif";
variable can hold console.log(typeof x);
different data types. </script>

• typeof operator could be


used to find out the type
of a variable.
Operators and expressions: Arithmetic

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

let x = 2 < 3 ? "a" : "b";


console.log(x);

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);

• else if statement: a new if (time < 10) {


condition if the first condition greeting = "Good morning";
} else {
is false. greeting = "Good day";
}
console.log(greeting);
Control-flow: switch-case statements
const fruit = 'apple';
• switch-case is used to perform let color;

different actions based on different // expression inside switch


conditions. switch (fruit) {
case 'apple':
• The switch expression is color = 'red';
break;
evaluated once and compared case 'banana':
with the values of each case. color = 'yellow';
break;
• break stops the executing of case 'grape':
switch and default specifies the color = 'purple';
break;
code to run if there is no case default:
match. color = 'unknown';
}
console.log('The color of the ' + fruit + ' is ' + color);
Control-flow: Loops
for (let i = 0; i < 2; i++) {
console.log('Number ' + i);
• for repeatedly executes a block of code as }
long as a specified condition is true, with
three optional expressions to initialize, let i = 0;
check, and update the loop variable. while (i < 2) {
console.log('Number ' + i);
• while repeatedly executes a code block as i++;
}
long as a specified condition evaluates to
true. let i = 0;

• do-while executes a block of code once, do {


console.log('Number ' + i);
and then repeatedly executes it as long as a i++;
specified condition evaluates to true. }
while (i < 2);
Functions
• A function is a code block <script>
let x = myFunction(4, 3);
designed for a specific task. console.log("Result is: " + x);
• Functions are executed when console.log(y);

they are called (i.e., invoked). function myFunction(a, b) {


// local variable
• Variables declared within a let y = 3;
JavaScript function are called return y * a * b;
}
local variables can only be </script>
accessed from within the
function.
Functions: Function expressions
• Functions can be defined // anonymous function expression
within expressions. const greet = function() {
console.log('Hello!');
• Function expressions are not };
hoisted, so they cannot be greet(); // Output: Hello!
called before they are assigned
(contrary to function
declarations). // named function expression
const greet = function greetings() {
• Useful for assigning functions console.log('Hello!');
to variables, passing functions };
as arguments, returning greet(); // Output: Hello!
functions.
Functions: Arrow function
// before arrow
const add = function(a, b){
• Arrow functions are a concise return a + b;
way to write functions in };
JavaScript, introduced in // basic arrow function:
ECMAScript 6. const add2 = (a, b) => {
return a + b;
• Arrow functions use the => };
syntax.
// single expression arrow function (implicit return)
• Arrow functions in JavaScript const add3 = (a, b) => a + b;
are a type of function // arrow function with no parameters
expression. const greet = () => "Hello!";

// arrow function with one parameter


const square = x => x * x;
Arrays
• In JavaScript, an array is a data // using array literals
structure that allows you to store const numbers = [1, 2, 3, 4, 5];
multiple values in a single variable. const fruits = ['apple', 'banana', 'cherry'];

• Arrays can grow or shrink in size // using the array constructor


const numbers = new Array(1, 2, 3, 4, 5);
dynamically (i.e., dynamic size). const fruits = new Array('apple', 'banana', 'cherry');
• Arrays can store elements of
// creating an empty array:
different types (numbers, strings, const emptyArray = [];
objects, other arrays, etc.). const anotherEmptyArray = new Array();

• There are multiple ways to create


arrays.
Arrays: Accessing and modifying
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits[0]); // Output: apple Accessing elements
console.log(fruits[2]); // Output: cherry

fruits[1] = 'blueberry';
Modifying elements
console.log(fruits); // Output: ['apple', 'blueberry', 'cherry']

fruits.push('date'); // Adds 'date' to the end


Adding elements
console.log(fruits); // Output: ['apple', 'blueberry', 'cherry', 'date']

fruits.pop(); // Removes the last element


console.log(fruits); // Output: ['apple', 'blueberry', 'cherry']
Removing elements
fruits.shift(); // Removes the first element
console.log(fruits); // Output: ['blueberry', 'cherry']
Arrays: Methods
• forEach: Executes a provided const numbers = [1, 2, 3, 4, 5];
numbers.forEach(number => console.log(number));
function once for each array
element.
const numbers = [1, 2, 3, 4, 5];
• map: Creates a new array with const doubled = numbers.map(number => number * 2);
the results of calling a provided console.log(doubled); // Output: [2, 4, 6, 8, 10]
function on every element.
• filter: Creates a new array with const numbers = [1, 2, 3, 4, 5];
all elements that pass the test const even = numbers.filter(number => number % 2 === 0);
implemented by the provided console.log(even); // Output: [2, 4]

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);
}
};

// using the object constructor


• Using new keyword one can create a
const person = new Object(); new object as well. One could use
person.name = 'John Doe',
person.age = 30;
const person = {}; instead.
person.greet = function() {
console.log('Hello, ' + this.name);
};
Objects: Creation (2)

• Create method allows // using Object.create:


you to create new objects const Employee = {
dept: 'Sales',
based on an existing floor: 3,
object. greet: function() {
console.log('Hello, ' + this.name);
}
};
• The existing object used
as base becomes new const tommy = Object.create(Employee);
tommy.name = 'Tommy Green';
object’s prototype.
Objects: Creation (3)

• Using object constructor, one function Person(name, age) {


this.name = name;
can define an object type and this.age = age;
create objects from that type. this.greet = function() {
console.log('Hello, ' + this.name);
};
}
• This is useful when you need to
have multiple objects from the const person = new Person('John Doe', 30);
same base or want to create
objects programmatically.
Objects: Inheritance and prototypes
• JavaScript objects can inherit both types and properties from
parent objects (i.e., object create and constructor).

• Every JavaScript object references another object called its


prototype.

• 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.

• Objects can access properties from their prototype chains. When


you try to access a property, JavaScript first looks at the object
itself. If the property isn't found there, it searches through each
prototype in the chain until it either finds the property or reaches
the end of the chain.
Objects: Accessing and modifying properties
• Accessing a property with
const person = {
• dot notation firstName: "John",
lastName : "Doe",
• bracket notation age : 50
• an expression };

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());

// returns the function definition


console.log(person.fullName);
Objects: Getters and setters
• Getters and setters are special methods that provide a way to
access and update the properties of an object.
• Encapsulation: hide the internal representation of an object's
properties.
• Validation and constraints: Ensure that the data being assigned
to a property meets certain criteria.
• Computed properties: Allow properties to be computed
dynamically.
• Debugging and logging: Facilitate debugging and logging
whenever a property is accessed or modified.
Objects: Getters and setters (2)
const student = {
firstName: 'Monica',
• When accessing the value, get getName() {
we access the value as a },
return this.firstName;

property. set changeName(newName) {


this.firstName = newName;
}
• An error occurs, when you try };

to access the value as a console.log(student.firstName); // Output: Monica


method. console.log(student.getName); // Output: Monica
student.changeName = 'Sarah';
console.log(student.firstName); // Output: Sarah
console.log(student.getName()); // Output: error
Objects: Modifying constructors
// constructor function for Person objects
function Person(name) {
this.name = name;
}
• You can NOT add a
new property or // create a Person object
method to an object const myMother = new Person("Sally");
console.log(myMother.name);
constructor.
Person.prototype.nationality = "English";
Person.prototype.changeName = function (name) {
this.name = name;
• You must add it to the }
constructor function
prototype. // change Name
myMother.changeName("Lisa");
console.log(myMother.name + " is " + myMother.nationality);
Objects: Display // build a text
let text = "";
for (let x in person) {
text += person[x] + " ";
• The properties of an };
object can be console.log(text);

collected in a loop and // ['name', 'age']


could accessed using const keysArray = Object.keys(person);
// ['John Doe', 30]
keys, values, and const valuesArray = Object.values(person);
entries methods. // [['name', 'John Doe'], ['age', 30]]
const entriesArray = Object.entries(person);

// create an Object let text2 = "";


const person = { for (let [name, age] of Object.entries(person)) {
name: "John", text2 += name + " " + age + " ";
age: 30 }
}; console.log(text2);
Objects: Destructuring
• Object destructuring is a
const person = {
convenient way to extract values name: 'John Doe',
from objects and assign them to age: 30,
email: 'john.doe@example.com'
variables. };

const { name, age, email } = person;


• It allows you to unpack
console.log(name); // Output: John Doe
properties from objects into console.log(age); // Output: 30
distinct variables, making your console.log(email); // Output: john.doe@example.com
code cleaner and more
readable.
Objects: By reference or by value
// create an Object
const person = {
• Objects are mutable, that is they firstName: "Akif",
are addressed by reference, not by lastName: "Khan",
age: 40
value. };
• In the example, if person is an console.log(person.age);

object, x is not copy of person. // create a copy


let x = person;
• They both share the same memory
address and any changes to x will // change age
also change person. x.age = 2;
console.log(person.age);
Classes
• ES6 (ECMAScript 2015) introduced classes providing a more structured
and clearer syntax for creating objects and handling inheritance.
• Although JavaScript is a prototype-based language, classes offer a
more traditional way to work with objects.
• Objects: Best for simple data structures, configuration settings, state
management, dynamic property assignment, and data transfer objects.
• Classes: Ideal for creating reusable components, modeling real-world
entities, encapsulating and abstracting complexity, implementing
inheritance and polymorphism, and managing related data and
behavior.
Classes: Key features
• Class definition: A class is defined using the class keyword.

• Constructor method: The constructor method is a special


method for creating and initializing objects created within a class.

• Methods: Functions defined within a class.

• Inheritance: Classes can extend other classes, inheriting their


properties and methods.
Classes: Syntax
• The class keyword is used to class Person {
define a class. constructor(name, age) {
this.name = name;
• The class name should start with this.age = age;
an uppercase letter by }
convention.
• The constructor method is called greet() {
when a new instance of the class console.log(`${this.name} is ${this.age} years old.`);
is created. }
}
• Methods defined within the class
are shared by all instances of the const person1 = new Person('John Doe', 30);
class. person1.greet(); // John Doe is 30 years old.
• Use the new keyword to create a
new instance of the class.
Classes: Inheritance class Animal {
constructor(name) {
this.name = name;
• Classes can inherit from other }
classes using the extends keyword. speak() {
• The child class inherits all }
console.log(`${this.name} makes a noise.`);

properties and methods from the }


parent class.
class Dog extends Animal {
• Inheritance is useful for code speak() {
console.log(`${this.name} barks.`);
reusability: reuse properties and }
methods of an existing class when }
you create a new class.
const dog = new Dog('Rex');
dog.speak(); // Output: Rex barks.
Classes: Static methods
• Static methods are defined on the
class itself, not on instances of the
class. They are called directly on the class MathUtility {
class. static add(a, b) {
return a + b;
• In other words, you cannot call }
a static method on an object, only on }
an object class. console.log(MathUtility.add(5, 3)); // Output: 8
• Static methods are typically used for
utility functions, helper functions, or
methods that do not require access
to instance-specific data.
Classes: Private fields and methods
class Person {
#privateField;
• Private fields and methods are
only accessible within the constructor(name) {
class. this.name = name;
• They are used to encapsulate this.#privateField = 'This is private';
data and implementation }
details, ensuring that they are
not accessible or modifiable #privateMethod() {
from outside the class. console.log('This is a private method');
}
• This helps to maintain the
integrity of the data and getPrivateField() {
prevents unintended return this.#privateField;
interference or misuse by other }}
parts of the code.
const person = new Person('John Doe', 30);
console.log(person.getPrivateField()); // Output: This is private
Classes: Getters and setters
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}

get area() {
return this.width * this.height;
}

set area(value) {
console.log('Area cannot be directly set. Use width and height properties.');
}
}

const rect = new Rectangle(10, 5);


console.log(rect.area); // Output: 50
rect.area = 100; // Output: Area cannot be directly set. Use width and height properties.
Before we end
• Use consistent naming conventions: camelCase for variable
names and UPPER_SNAKE_CASE for constants.
• Convert types explicitly using functions like Number(), String(),
and Boolean() to avoid unexpected results from type coercion.
• Always initialize variables to avoid undefined values and potential
bugs.
• Be aware of operator precedence to avoid unexpected behavior
and use parentheses to make expressions clear.
• Avoid deeply nested code by using early returns or breaking
complex logic into smaller functions.
Before we end (2)
• Always include a default case in switch statements to handle
unexpected values.
• Name functions clearly and descriptively to indicate their
purpose.
• Use default parameters to handle optional arguments.
• Use built-in array methods like map, filter, reduce, forEach for
better readability and performance.
• Use Object.keys, Object.values, Object.entries for iterating over
object properties.
Resources
• https://javascript.info/
• https://www.w3schools.com/js/
• https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference
• https://ecma-international.org/publications-and-
standards/standards/ecma-262/
• https://www.linode.com/docs/guides/javascript-objects-tutorial/
Questions?

You might also like