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

JS Basics

javascript basics

Uploaded by

anjanashri108
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

JS Basics

javascript basics

Uploaded by

anjanashri108
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Javascript

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 & Server Side Scripting

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

Primitive Data Types


1. String
2. Number
3. Boolean
4. Null
5. Undefined
Non-primitive Data Types
1. Object
2. Date
3. Array

String
Represents text data enclosed in single ('') or double ("") quotes.
let name = "John";

Concatenation: Concatenation involves combining multiple strings into a single string.


This is achieved using + operator or the concat() method.
let str1 = "Hello";
let str2 = "world!";

let result = str1 + " " + str2; // Using the + operator


console.log(result); // Output: "Hello world!"

let result2 = str1.concat(" ", str2); // Using the concat()


console.log(result2); // Output: "Hello world!"
Quotation for string declaration
Single Quotes ('):
● Encloses string using single quotes.
● Can be used to create simple strings without any special characters
let message = 'Hello, World!';

Double Quotes ("):


● Encloses string using double quotes.
● Similar to single quotes, can be used for simple strings without any special
characters.
let message = "Hello, World!";
Backticks (`):
● Used for template literals.
● Allow embedding expressions and variables within the string using ${ }
syntax.
let message =
`Hello, my name is ${name}.My age is ${age}.`;

String methods
● charAt( ): Returns the character at the specified index.
let str = "hello";
let char = str.charAt(0); // Output: "h"

● charCodeAt( ): Returns the Unicode value of the character at the specified


index.
let str = "hello";
let charCode = str.charCodeAt(0); // Output: 104

● concat( ): Combines two or more strings and returns a new string.


let str1 = "hello";
let str2 = "world";
let newStr = str1.concat(" ", str2);
// Output: "hello world"
● indexOf( ): Returns the index within the calling string object of the first
occurrence of the specified value..
let str = "hello";
let index = str.indexOf("l"); // Output: 2

● 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

● length(): Returns the length of the string.


let str = "hello";
let length = str.length; // Output: 5

● slice(): Extracts a section of a string and returns it as a new string.


let str = "hello world";
let newStr = str.slice(6); // Output: "world"

● split(): Splits a string into an array of substrings based on a specified


separator.
let str = "hello world";
let arr = str.split(" "); // Output: ["hello", "world"]

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

● toLowerCase(): Converts all the alphabetic characters in a string to lowercase.


let str = "HELLO";
let lowerStr = str.toLowerCase(); // Output: "hello"

● toUpperCase(): Converts all the alphabetic characters in a string to uppercase.


let str = "hello";
let upperStr = str.toUpperCase(); // Output: "HELLO"
● replace(): Searches a string for a specified value or a regular expression, and
returns a new string where the specified values are replaced.
let str = "hello world";
let newStr = str.replace("world", "universe");
// Output: "hello universe"

● 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

● match(): Searches a string for a specified value or a regular expression and


returns an array of matches.
let str = "Hello, world!";
let matches = str.match(/o/g); // Output: ["o", "o"]

● search(): Searches a string for a specified value or a regular expression and


returns the index of the first match, or -1 if not found.
let str = "Hello, world!";
let index = str.search("world"); // Output: 7

● toString(): Returns a string representing the specified object.


let num = 123;
let str = num.toString(); // Output: "123"

● valueOf(): Returns the primitive value of the specified object.


let str = new String("hello");
let value = str.valueOf(); // Output: "hello"
Number
Represents numeric values, both integers and decimals.
let age = 30;

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

● Number.MIN_VALUE: The smallest positive representable number.


console.log(Number.MIN_VALUE); // Output: 5e-324

● Number.NaN: Represents "Not-a-Number" value.


console.log(Number.NaN); // Output: NaN

● Number.POSITIVE_INFINITY: Represents positive infinity.


console.log(Number.POSITIVE_INFINITY);
// Output: Infinity

● Number.NEGATIVE_INFINITY: Represents negative infinity.


console.log(Number.NEGATIVE_INFINITY);
// Output: -Infinity
Number methods
● toFixed(): Formats a number using fixed-point notation with 1 or 2 number of
digits after the decimal point.
let num = 10.3456;
console.log(num.toFixed(2)); // Output: "10.35"

● toString(): Converts number to string.


let num = 42;
console.log(num.toString()); // Output: "42"

● parseInt(): Parses a string argument and returns an integer of the specified


base.
let str = "42px";
console.log(parseInt(str)); // Output: 42

● parseFloat(): Parses a string argument and returns a floating-point number.


let str = "3.14";
console.log(parseFloat(str)); // Output: 3.14

● toExponential(): Converts a number into exponential notation with a specified


no.of digits.
let num = 12345;
console.log(num.toExponential(2)); // Output: "1.23e+4"

● toLocaleString(): Returns a string representing the number formatted


according to the locale-specific conventions.
let num = 123456.789;
console.log(num.toLocaleString('en-US'));
// Output: "123,456.789"

● toPrecision(): Formats a number to a specified precision.


let num = 12345.6789;
console.log(num.toPrecision(5)); // Output: "12345"
● valueOf(): Returns the primitive value of a Number object.
let num = new Number(42);
console.log(num.valueOf()); // Output: 42

● floor(): Returns an integer less than or equal to a given number.

let num = 5.8;


let roundedNum = Math.floor(num); // roundedNum: 5

● ceil(): Returns an integer greater than or equal to a given number.

let num = 5.2;


let roundedNum = Math.ceil(num); // roundedNum: 6

● sqrt(): Returns the square root of a number.

let num = 25;


let squareRoot = Math.sqrt(num); // square Root: 5

● round(): Returns the value of a number rounded to the nearest integer.

let num = 5.4;


let roundedNum = Math.round(num); // roundedNum: 5

● pow(): Returns the value of base to the exponent power. (base^exponent)

let base = 2;
let exponent = 3;
let result = Math.pow(base, exponent); // result: 8

● random(): Returns a random floating-point number between 0 (inclusive) and 1


(exclusive).

let randomNumber = Math.random(); // Generates a random


number between 0 and 1
Boolean
Represents a logical value, either true or false.
let isStudent = true;

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"

● valueOf(): Returns the value of the Boolean object.


var result = (1 > 2); result.valueOf();
// returns false

Null & Undefined


null: Represents the intentional absence of any object value.
let myVar = null;
console.log(myVar); // Output: null
undefined: Indicates that a variable has been declared but not assigned a value.
let myVar;
console.log(myVar); // Output: undefined
Object
Represents a collection of key-value pairs, where keys are strings and values can
be any data type.
let person = { name: "Alice", age: 25 };

Object literals
Objects declared by { } curly braces

Object keys and values

● 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

● Values: Data associated with keys, representing properties, characteristics, or


information stored within the object structure.

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.

let fruits = ['apple', 'banana'];


fruits.push('orange');
// fruits: ['apple', 'banana', 'orange']

● pop( ): Removes the last element from an array and returns that element.

let fruits = ['apple', 'banana', 'orange'];


let removedFruit = fruits.pop();
// removedFruit: 'orange', fruits: ['apple', 'banana']

● reverse( ): method used to reverse the order of elements in an array.

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.

let fruits = ['apple', 'banana', 'orange'];


let removedFruit = fruits.shift();
console.log(removedFruit); // Output: 'apple'
console.log(fruits); // Output: ['banana', 'orange']

● unshift( ): Method used to add one or more elements to the beginning of an


array and returns the new length of the array.

let newLength = fruits.unshift('grape');


console.log(newLength); // Output: 3
console.log(fruits);
// Output: ['grape', 'banana', 'orange']
● length( ): Returns the number of elements in an array or the number of
characters in a string.

let fruits = ['apple', 'banana', 'orange'];


let fruitsLength = fruits.length; // fruitsLength: 3

● concat( ): Combines two or more arrays and returns a new array.

let arr1 = [1, 2];


let arr2 = [3, 4];
let newArr = arr1.concat(arr2); // Output: [1, 2, 3, 4]

● join( ): Joins all elements of an array into a string

let arr = ["Hello", "World"];


let str = arr.join(", "); // Output: "Hello, World"

● slice( ): Returns a shallow copy of a portion of an array into a new array.

let arr = [1, 2, 3, 4, 5];


let newArr = arr.slice(1, 3); // Output: [2, 3]

● splice( ): Changes the contents of an array by removing or replacing existing


elements and/or adding new elements..

let arr = [1, 2, 3, 4, 5];


arr.splice(2, 1, "a", "b");
// Output: [1, 2, "a", "b", 4, 5]
● indexOf( ): Returns the first index at which a given element can be found in the
array, or -1 if it is not present.

let arr = [1, 2, 3, 4, 5];


let index = arr.indexOf(3); // Output: 2

● forEach( ): Calls a function for each element in the array.

let arr = [1, 2, 3];


arr.forEach(item => console.log(item)); // Output: 1, 2, 3

● every( ): Tests whether all elements in the array pass the provided function.

let arr = [2, 4, 6];


let allEven = arr.every(item => item % 2 === 0);
// Output: true

● filter( ): Creates a new array with all elements that pass the test implemented
by the provided function.

let arr = [1, 2, 3, 4, 5];


let evenNumbers = arr.filter(item => item % 2 === 0);
// Output: [2, 4]

● lastIndexOf( ): Returns the last index at which a given element can be found in
the array, or -1 if it is not present.

let arr = [1, 2, 3, 4, 2];


let lastIndex = arr.lastIndexOf(2); // Output: 4
● map( ): Creates a new array populated with the results of calling a provided
function on every element in the calling array.

let arr = [1, 2, 3];


let doubled = arr.map(item => item * 2);
// Output: [2, 4, 6]

● reduce( ): Applies a function against an accumulator and each element in the


array (from left to right) to reduce it to a single value.

let arr = [1, 2, 3, 4, 5];


let sum = arr.reduce((acc, cur) => acc + cur, 0);
// Output: 15

● sort( ): Sorts the elements of an array in place and returns the sorted array.

let arr = [3, 1, 2];


arr.sort(); // Output: [1, 2, 3]

● toString( ): Returns a string representing the specified array and its elements.

let arr = [1, 2, 3];


let str = arr.toString(); // Output: "1,2,3"

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

// Attempting to reassign a constant will result in an


error
PI = 3.14; // Error

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;

console.log(a + b); // Output: 7


console.log(a - b); // Output: 3
console.log(a * b); // Output: 10
console.log(a / b); // Output: 2.5
console.log(a % b); // Output: 1

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;

console.log(x === y); // Output: false


console.log(x !== y); // Output: true
console.log(x > y); // Output: false
console.log(x < y); // Output: true
Logical operators
● Logical AND (&&): true if both operands are true, otherwise false.
● Logical OR (||): true if at least one of the operands is true, otherwise false.
● Logical NOT (!): Returns the opposite boolean value of the operand; true
becomes false, and false becomes true.
let isAdult = true;
let hasLicense = true;

console.log(isAdult && hasLicense); // Output: true


console.log(isAdult || hasLicense); // Output: true
console.log(!isAdult); // Output: false

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.

let age = 20;


let message = (age >= 18) ? "Adult" : "Minor";
console.log(message); // Output: "Adult"

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.

● If: Executes a block of code if a specified condition is true.

let temperature = 25;

if (temperature > 20) {


console.log("It's a warm day!"); // Output: It's a warm
day!
}

● Else: Executes a block of code if the if condition is false.

let age = 20;


if (age >= 18) {
console.log("You are an adult."); // Output
} else {
console.log("You are a minor.");
}

● Else if: Allows you to check additional conditions if the previous condition is false.

let score = 75;


if (score >= 90) {
console.log("You got an A!");
} else if (score >= 80) {
console.log("You got a B!");
} else {
console.log("You need to study harder!");
}

● Switch statement:

Switch statements provide a way to execute different blocks of code based on


the value of a variable or expression.

It's an alternative to using multiple if statements .

let day = "friday";

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.

● For Loop: Executes a block of code a specified number of times.

for (let i = 0; i < 5; i++) {


console.log(i); // Output: 0, 1, 2, 3, 4
}
● While Loop: Executes a block of code while a specified condition is true.
let i = 0;
while (i < 5) {
console.log(i); // Output: 0, 1, 2, 3, 4
i++;
}

● 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

● return: Exits the current function and optionally returns a value.


function add(x, y) {
return x + y;
}

console.log(add(3, 4)); // Output: 7

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 + "!");
}

Parameters & Arguments

● Parameters: Variables listed in the function definition.


● Arguments: Values passed to the function when it is called.

function greet(name) { // 'name' is a parameter


console.log("Hello, " + name + "!");
}
greet("Alice"); // 'Alice' is an argument

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

let myArray = [1, 2, 3];


modifyArray(myArray);
console.log(myArray);
// Output will be [1, 2, 3, 4], because 'myArray' was
modified inside the function

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 greetWithSalutation(name, salutation) {


console.log("Hello, " + salutation + " " + name +
"!");
}

// Call the appropriate function based on the number of


arguments
greet("John"); // Output: "Hello, John!"
greetWithSalutation("John", "Mr.");
// Output: "Hello, Mr. John!"

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!";
};

let dog = new Dog();


console.log(dog.speak()); // Output: "Woof!"
Recursive function
● function that calls itself within its own definition.
● This technique is often used to solve problems that can be broken down into
smaller, similar sub-problems.
● Recursive functions typically have a base case to prevent infinite recursion.

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

// Testing the factorial function


console.log(factorial(5));
// Output will be 120 (5 * 4 * 3 * 2 * 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.

(Ref again in datatypes)


OOP- Object Oriented Programming
OOP programming paradigm that allows you to model real-world entities as objects
with properties and methods. JavaScript supports OOP principles such as
encapsulation, inheritance, and polymorphism.

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.

// Define a Teacher object


function Teacher(name, age, subject) {
Person.call(this, name, age);
this.subject = subject;
}
// Set up prototype chain for inheritance
Teacher.prototype = Object.create(Person.prototype);
Teacher.prototype.constructor = Teacher;
// Override the greet method
Teacher.prototype.greet = function() {
console.log("Hello, my name is " + this.name + " and
I teach " + this.subject + ".");
};
// Create an instance of Teacher
let teacher1 = new Teacher("Smith", 40, "Math");
teacher1.greet();
// Output: "Hello, my name is Smith and I teach Math."

You might also like