JS Basics
JS Basics
1. Introduction to Scripting
2. Client Side scripting & Server Side Scripting
3. Introduction to Javascript
4. Structure of a Program
5. Data types
6. Variables
7. Constants
8. Operators
9. Unary
10. Binary
11. Statements: Assignment, Conditional, Control.
12. Functions: Functions, Pass by Value, Call by Value, Overloading,
Overriding,
13. Recursive.
14. Derived data types
15. Object oriented programming.
Introduction to Scripting
● Scripting languages are programming languages designed for automating the
execution of tasks.
● Typically interpreted rather than compiled, meaning the code is executed
line-by-line.
● Often used for rapid development due to their concise syntax.
● Popular scripting languages include Python, JavaScript, Perl and PHP.
● Versatile and can handle a wide range of tasks, from simple to complex web
applications.
● Known for their ease of learning and readability, making them accessible to
beginners and experienced developers.
● Client-side scripting refers to code that is executed on the client's browser. When a
user visits a website, the HTML, CSS, and JavaScript files are downloaded to the
client's browser and runs, which allows for dynamic interactions and modifications to
the webpage without needing to reload the entire page.
● Server-side scripting refers to code that is executed on the server instead of the
client's browser. In this context, the code is used to handle server-side logic, process
incoming requests, interact with databases, and generate dynamic content that is
then sent to the client.
Introduction to Javascript
● JavaScript is a high-level, interpreted programming language primarily used for
making web pages interactive.
● It was created to add dynamic and interactive elements to web pages, allowing them
to respond to user actions
● JavaScript can be embedded directly into HTML code and executed by web browsers,
or written externally by adding the source file on script tag making it an essential
component of web development.
Structure of a Program
● Literals represent fixed values directly in code. They include numeric literals eg: 10,
string literals eg: "hello", boolean literals eg: true, object literals eg: {keyvalue}, array
literals eg: [1, 2, 3]. They are constant and cannot be changed during execution.
● Variables are containers for storing data values. They are declared using keywords
like ‘var’ and ‘let’. Variables can hold various data types, such as numbers, strings,
booleans, objects, and functions. They can be assigned values and their contents can
be modified during runtime, depending on their declaration type.
● Camel case is a naming convention where multiple words are joined together
without spaces, and each word after the first begins with a capital letter. For
example, "camelCaseVariable". It's commonly used for naming variables, functions,
and to enhance readability in code.
● Unicode allows us to use a wide range of characters, including letters from different
languages, emojis, symbols, and more, in your code and text making it versatile for
international use.
● Semicolons are used to terminate statements. While they are often optional due to
automatic semicolon insertion by the parser. Semicolons signify the end of a line of
code, helping in code readability.
● Indentation refers to the practice of adding spaces or tabs at the beginning of lines
of code to organise it visually like creating paragraphs in writing. It makes the code
easier to read by showing the structure and hierarchy of the program.
● Whitespace refers to spaces, tabs, and line breaks that don't affect the code's
functionality but improve readability. It's used for formatting and separating code
elements.
● Commenting involves adding notes within the code that are ignored during
execution. Comments start with //. They document code, explain functionality,
and improve readability. They're important for collaboration, debugging, and
understanding code.
● Identifiers are names used to identify variables, functions, objects, and other
elements within code. They follow specific naming rules: starting with a letter,
underscore, or dollar sign, followed by letters, digits, underscores, or dollar signs.
Identifiers cannot be reserved keywords and must be unique within their scope.
● Case sensitivity means that identifiers are distinguished by their case. For
example, "myVar" and "myvar" are considered different. It's important to maintain
consistency in casing to avoid errors when referencing identifiers within the code.
● Reserved words are predefined keywords that have special meanings and
purposes within the language. They cannot be used as identifiers. Examples
include "if," "else," "while," "function," "var," and "return." They are part of the
language syntax and serve specific roles in programming constructs.
● Operators are symbols used to perform operations on operands, such as variables
or values. They include arithmetic operators (+, -, *, /), assignment operators (=,
+=, -=), comparison operators (==, ===, !=, !==), logical operators (&&, ||, !),
and more.
● Expressions are combinations of values that produce a resulting value. They can
be simple (e.g., 5 + 3) or complex (e.g., (x * 2) + (y / 3)). Expressions can be
used in assignments, function calls, conditions, and more.
Data types
Data types define the data type that a variable can store and tell a computer system
how to interpret its value.
String
Represents text data enclosed in single ('') or double ("") quotes.
let name = "John";
String methods
● charAt( ): Returns the character at the specified index.
let str = "hello";
let char = str.charAt(0); // Output: "h"
● lastIndexOf( ): Returns the index within the calling string object of the last
occurrence of the specified value.
let str = "hello";
let lastIndex = str.lastIndexOf("l"); // Output: 3
● subString(): Returns the part of the string between the start and end
indexes, or to the end of the string.
let str = "hello world";
let newStr = str.substring(6); // Output: "world"
● localeCompare(): Compares two strings in the current locale and returns -1, 0,
or 1. (-1) indicates whether the string comes before, (0) is equal to, (1)
comes after the compared string in sort order.
let str1 = "apple";
let str2 = "banana";
let comparison = str1.localeCompare(str2); // Output: -1
Number object
The Number object created using new Number(), is a tool for handling numbers
in code. It offers special functions for tasks like number formatting and complex
calculations.
let num = new Number(42);
console.log(num); // Output: 42
Number properties
● Number.MAX_VALUE: The largest representable number.
console.log(Number.MAX_VALUE);
// Output: 1.7976931348623157e+308
let base = 2;
let exponent = 3;
let result = Math.pow(base, exponent); // result: 8
Boolean object
Boolean object, created with the new keyword, are rarely used because boolean
values are primitive types.
let bool = new Boolean(true);
console.log(bool); // Output: [Boolean: true]
Boolean methods
● toString(): Returns string of boolean value.
var result = (1 > 2); result.toString();
// returns "false"
Object literals
Objects declared by { } curly braces
● Keys: Labels for organising and accessing data stored within the object structure.
const obj = { a: 1, b: 2, c: 3 };
console.log(Object.keys(obj)); //array of keys
const obj = { a: 1, b: 2, c: 3 };
console.log(Object.values(obj)); //array of values
Date
Represents dates and times. It allows for creating, manipulating, and formatting dates
and times. It's used for tasks like tracking events, scheduling, and handling time-related
operations in web applications.
Syntax
Following syntaxes to create a Date object using Date() constructor.
● new Date( ): Representing the current date and time.
● new Date(milliseconds): Representing a specific point in time based on milliseconds.
● new Date(datestring): Date object from a date string, parsing it according to the
specified format.
● new Date(year,month,date[,hour,minute,second,millisecond]): Creates a Date object
with the specified year, month, date, and optional time components.
Parameters
● NoArgument: With no arguments, the Date() constructor creates a Date object set to
the current date and time.
● datestring − When one string argument is passed, it is a string representation of a
date, in the format accepted by the Date.parse() method.
● year − Integer value representing the year. Always specify the year in full - use 1998,
instead of 98.
● month − Integer value representing the month, beginning with 0 for January to 11 for
December.
● date − Integer value representing the day of the month
● hour− Integer value representing the hour of the day (24-hour scale).
● minute − Integer value representing the minute segment of a time reading
● second − Integer value representing the second segment of a time reading.
● millisecond − Integer value representing the millisecond segment of a time reading.
Array
An ordered collection of values, accessed by numeric indices from 0,1,2… declared
using square brackets [ ] and separated by commas.
let numbers = [1, 2, 3, 4, 5];
Array methods
● Push( ): Adds one or more elements to the end of an array and returns the new
length of the array.
● pop( ): Removes the last element from an array and returns that element.
arr.reverse();
console.log(arr); // Output: ['orange', 'banana', 'apple']
● shift( ): Method used to remove the first element from an array and return that
removed element.
● every( ): Tests whether all elements in the array pass the provided function.
● filter( ): Creates a new array with all elements that pass the test implemented
by the provided function.
● lastIndexOf( ): Returns the last index at which a given element can be found in
the array, or -1 if it is not present.
● sort( ): Sorts the elements of an array in place and returns the sorted array.
● toString( ): Returns a string representing the specified array and its elements.
Variables
Variables are used to store data that can be changed or reassigned during the
execution of a program.
Declaration: let and var
‘=’ assignment operator for assigning values
let
● ‘Let’ is a keyword used to declare variables.
● Variables declared with ‘let’ are limited in scope to the expression in which they are
declared.
● This means they are not accessible outside of their containing block.
function example2() {
console.log(y); // Error: Cannot access 'y' before
initialization
let y = 20;
console.log(y); // Output: 20
}
example2();
var
● Variables declared with ‘var’ have global scope, depending on where they are
declared.
● Variables declared with ‘var’ are hoisted on top of their containing function.
● This means they are accessible throughout the entire function
function example() {
console.log(x); // Output: undefined
var x = 10;
console.log(x); // Output: 10
}
example();
Constants
Constants are similar to variables, but their values cannot be changed once they
are assigned.
Declaration: const
‘=’ assignment operator for assigning values
Const
● ‘Const’ is a keyword used to declare constants.
● Value cannot be changed or reassigned after initialization.
● They are limited in scope to the block, statement, or expression in which they
are declared.
const PI = 3.14159;
console.log(PI); // Output: 3.14159
Operators
Operators are symbols or keywords that perform operations on one or more operands
to produce a result. They are used to manipulate data, perform calculations, compare
values, and control the flow of execution in a program.
Arithmetic operators
● Addition (+): produce their sum.
● Subtraction (-): difference between two values.
● Multiplication (*): to get their product
● Division (/): to get the quotient
● Modulus (%): remainder of dividing values
● Increment (++): Adds 1 to the value.
● Decrement (--): Subtracts 1 from value.
let a = 5;
let b = 2;
Comparison operators
● Equal to (==): Checks if two values are equal, performing type coercion
● Not equal to (!=): Checks if two values are not equal, performing type coercion
● Strict equal to (===): Checks if two values and data types are equal
● Strict not equal to (!==): Checks if two values and data types are not equal
● Greater than (>): Checks if the left operand is greater than the right operand
● Less than (<): Checks if the left operand is less than the right operand.
● Greater than or equal to (>=): Checks if the left operand is greater than or
equal to right operand.
● Less than or equal to (<=): Checks if the left operand is lesser than or equal to
right operand.
let x = 5;
let y = 10;
Assignment operators
● Assignment (=): Assigns the value of the right operand to the left operand.
● Addition assignment (+=): Adds the value of the right operand to the left
operand and assigns the result to the left operand.
● Subtraction assignment (-=): Subtracts the value of the right operand from the
left operand and assigns the result to the left operand.
● Multiplication assignment (*=): refer above with multiplication keyword
● Division assignment (/=): refer above with division keyword
● Modulus assignment (%=): refer above with remainder keyword
let x = 5;
x += 3; // equivalent to x = x + 3
console.log(x); // Output: 8
Conditional operator
● Conditional operator (?:) It evaluates a condition and returns one of two
expressions depending on whether the condition is true or false.
Unary
operators that work with only one operand. They perform operations like negation,
increment, decrement, and type conversion.
let x = 5;
let y = -x; // Negation operator
let z = ++x; // Increment operator
Binary
operators that work with two operands. They perform operations like addition,
subtraction, multiplication, division, comparison, and logical operations.
let a = 5;
let b = 3;
let sum = a + b; // Addition operator
let product = a * b; // Multiplication operator
typeOf operator
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a
number, string, or boolean value and returns true or false based on the evaluation.
let x = 10;
console.log(typeof x); // Output: "number"
[Refer assignment statements from assignment operators both are more
or less the same]
Conditional statements
allow you to execute different blocks of code based on certain conditions.
● Else if: Allows you to check additional conditions if the previous condition is false.
● Switch statement:
switch (day) {
case "Monday":console.log("It's the start of the
week.");
case "Tuesday":console.log("It's Tuesday!");
case "Wednesday":console.log("It's midweek.");
default:console.log("It's some other day."); // output
}
Control statements
Loop statements
Used to execute a block of code repeatedly until the certain condition is met.
They provide a way to auto-execute repetitive tasks and repeat over collections of
data.
● Do-While Loop: Executes a block of code once, then repeats the loop as long as a
specified
let i = 0;
do {
console.log(i); // Output: 0, 1, 2, 3, 4
i++;
} while (i < 5);
● For in Loop: Iterates over the properties of an object, allowing you to access the
keys or indices.
let obj = {a: 1, b: 2, c: 3};
for (let key in obj) {
console.log(key, obj[key]);
}
// output: a 1, b 2, c 3
● For of Loop: Iterates over iterable objects like arrays, strings, maps, sets, etc.,
allowing you to access the values directly.
let arr = [1, 2, 3];
for (let value of arr) {
console.log(value);
}
// output: 1,2,3
Other statements
● break: Terminates the current loop, switch, or label statement.
for (let i = 0; i < 5; i++) {
if (i === 3) {
break;
}
console.log(i);
}
// output: 0,1,2
● continue: Skips the current iteration of a loop and continues with the next
iteration.
for (let i = 0; i < 5; i++) {
if (i === 2) {
continue;
}
console.log(i);
}
//output: 0,1,3,4
Functions
A function is a named block of code that performs a specific task and can be
reused by callbacks.
function greet(name) {
console.log("Hello " + name + "!");
}
Return
Used within a function to specify the value that the function should return
when it is called. It can be used to return a specific value, or to terminate the
function execution early.
function add(a, b) {
return a + b;
}
let result = add(3, 4); // result will be 7
Pass by value
When you pass a primitive value (like a number, string, or boolean) as an
argument to a function, it is passed by value. This means that a copy of the
primitive value is created and passed to the function. Any modifications made
to the parameter within the function do not affect the original value outside
the function.
function changeValue(x) {
x = 10; // Changing the value of 'x'
}
let num = 5;
changeValue(num);
console.log(num);
// Output will be 5, because 'num' remains unchanged
outside the function
Call by value
function arguments are passed by value when the argument is a primitive type
(numbers, strings, booleans). When a primitive value is passed to a function, a
copy of that value is made and passed into the function. Any changes made
to the parameter inside the function do not affect the original value outside
the function.
function modifyArray(arr) {
arr.push(4); // Modifying the array 'arr'
}
Function overloading
Function overloading refers to the ability to define multiple functions with the
same name but different parameter lists. Can replicate function overloading by
checking the number and types of arguments passed to a function and
performing different actions based on these conditions.
function greet(name) {
console.log("Hello, " + name + "!");
}
Function overriding
Function overriding occurs when a subclass provides a specific implementation
for a method that is already defined in its superclass. This allows the subclass
to customise or extend the behaviour of the inherited method.
// Define a superclass
function Animal() {}
Animal.prototype.speak = function() {
return "Animal sound";
};
// Define a subclass
function Dog() {}
Dog.prototype = Object.create(Animal.prototype);
// Inherit from Animal
Dog.prototype.constructor = Dog; // Set the constructor
Dog.prototype.speak = function() {
return "Woof!";
};
function factorial(n) {
// Base case: if n is 0 or 1, return 1
if (n === 0 || n === 1) {
return 1;
}
// Recursive case: n * factorial(n - 1)
else {
return n * factorial(n - 1);
}
}
Derived datatypes
data types that are derived from the primitive data types. They are more complex
data structures and can hold multiple values or other data types. Examples of
derived data types include objects, arrays, functions, and dates.
Encapsulation
Bundling data and methods into a single unit (object) to hide implementation
details and ensure modularity
// Define a Person object using a constructor function
function Person(name, age) {
this.name = name;
this.age = age;
// Encapsulated method
this.greet = function() {
console.log("Hello, my name is " + this.name + "
and I am " + this.age + " years old.");
};
}
// Create an instance of Person
let person1 = new Person("John", 30);
person1.greet();
// Output: "Hello, my name is John and I am 30 years
old."
Inheritance
Mechanism allowing objects to inherit properties and methods from other
objects, facilitating code reuse and hierarchy.
// Define a Student object that inherits from Person
function Student(name, age, grade) {
Person.call(this, name, age);
// Call the parent constructor
this.grade = grade;
}
// Set up prototype chain for inheritance
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
// Extend the inherited method
Student.prototype.study = function() {
console.log(this.name + " is studying.");
};
// Create an instance of Student
let student1 = new Student("Alice", 25, "A");
student1.greet();
// Output: "Hello, my name is Alice and I am 25 years
old."
student1.study(); // Output: "Alice is studying."
Polymorphism
Polymorphism allows objects of different types to be treated as objects of a
common superclass, enabling flexibility and dynamic behaviour.