KEMBAR78
JavaScript Basics | PDF | Parameter (Computer Programming) | Data Type
0% found this document useful (0 votes)
12 views18 pages

JavaScript Basics

Basics of js frontend for lab

Uploaded by

shuklavyom12
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)
12 views18 pages

JavaScript Basics

Basics of js frontend for lab

Uploaded by

shuklavyom12
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/ 18

JavaScript Data Types

JavaScript has several built-in data types:

 Number: Represents numeric values.

o Example: let age = 25;

 String: Represents sequences of characters.

o Example: let name = "Alice";

 Boolean: Represents true or false.

o Example: let isActive = true;

 Undefined: A variable that has been declared but not assigned a value.

o Example: let value; // undefined

 Null: Intentional absence of any object value.

o Example: let result = null;

 Object: Collections of properties.

o See below for details.

 Symbol: Unique and immutable data type (used for object property keys).

o Example: let sym = Symbol('unique');

 BigInt: For large integers.

o Example: let bigNumber = 12345678901234567890n;


Arrays in JavaScript
 Array: A special object for storing ordered collections.

 Arrays can hold elements of any type, including mixed types.

Example:

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


console.log(fruits[1]); // Output: banana

 Arrays are zero-indexed (fruits is 'apple').

 You can add elements using push, remove with pop, and access length via fruits.length.

Other Examples:

let mixedArr = [1, 'hello', true, null];


mixedArr.push('new item'); // adds to end
let last = mixedArr.pop(); // removes last item

JavaScript Array Methods (with Examples)


JavaScript arrays come with many built-in methods that allow you to add, remove, search, iterate, and transform
elements. Here are some of the most commonly used methods with examples:

Array Methods & Examples

 push(): Adds one or more elements to the end of an array.

let arr = [1, 2, 3];


arr.push(4);
// arr = [1, 2, 3, 4]

 pop(): Removes the last element from an array and returns it.

let arr = [1, 2, 3];


arr.pop(); // returns 3, arr = [1, 2]

 shift(): Removes the first element from an array and returns it.

let arr = [1, 2, 3];


arr.shift(); // returns 1, arr = [2, 3]

 unshift(): Adds one or more elements to the front of an array.

let arr = [1, 2];


arr.unshift(0);
// arr = [0, 1, 2]

 concat(): Combines two or more arrays.

let a = [1, 2], b = [3, 4];


let merged = a.concat(b);
// merged = [1, 2, 3, 4]

 join(): Combines all elements of an array into a string, with a specified separator.

let arr = ['a', 'b', 'c'];


arr.join('-');
// returns "a-b-c"

 slice(): Returns a shallow copy of a portion of an array.

let arr = ['a', 'b', 'c', 'd'];


arr.slice(1, 3); // ['b', 'c']

 splice(): Adds/removes elements to/from an array.

let arr = ['a', 'b', 'c'];


arr.splice(1, 1, 'x');
// arr = ['a', 'x', 'c']

 forEach(): Executes a function for each array element.

let arr = [1, 2, 3];


arr.forEach(el => console.log(el));
// logs 1, 2, 3

 map(): Creates a new array populated with the results of calling a function on every element.

let arr = [1, 2, 3];


let squared = arr.map(x => x * x);
// squared = [1, 4, 9]

 filter(): Creates a new array filled with elements that pass a test.

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


arr.filter(x => x % 2 === 0);
// returns [2, 4]

 reduce(): Reduces the array to a single value.

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


arr.reduce((sum, x) => sum + x, 0);
// returns 10

 find(): Returns the first element that matches the condition.

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


arr.find(x => x > 2);
// returns 3

 findIndex(): Returns the index of the first element that matches the condition.

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


arr.findIndex(x => x > 2);
// returns 2

 includes(): Checks if an array contains a specified value.

let arr = [1, 2, 3];


arr.includes(2); // returns true

 sort(): Sorts the array in place.

let arr = [3, 1, 2];


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

 reverse(): Reverses the order of the array.

let arr = [1, 2, 3];


arr.reverse(); // arr = [3, 2, 1]

 flat(): Flattens nested arrays.

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


arr.flat(2); // returns [1, 2, 3, 4]

 toString(): Converts array to string.

let arr = [1, 2, 3];


arr.toString(); // returns "1,2,3"

 at(): Gets the element at a particular index.

let arr = [10, 20, 30];


arr.at(-1); // returns 30

Objects in JavaScript
 Object: Used to store keyed collections of various data and more complex entities.

 Created using curly braces {}.

Example:

let person = {
name: 'John',
age: 30,
isStudent: false
};

console.log(person.name); // Output: John

Object Properties

 Can be accessed using dot notation (person.name) or bracket notation (person['name']).

Nested Example:

let car = {
make: 'Toyota',
model: 'Camry',
specs: {
color: 'blue',
horsepower: 200
}
};

console.log(car.specs.color); // Output: blue

JavaScript Object Methods (with Examples)


JavaScript objects can have methods as property values (functions or built-in statics):

General Object Methods:

 Object.assign(): Copies properties from source to target object.

const p1 = {name: 'John'};


const p2 = {age: 30};
Object.assign(p1, p2);
// p1 = {name: 'John', age: 30}

 Object.entries(): Returns an array of key-value pairs.

const person = {name: 'John', age: 30};


Object.entries(person);
// returns [['name', 'John'], ['age', 30]]

 Object.keys(): Returns an array of object keys.

const person = {name: 'John', age: 30};


Object.keys(person);
// returns ['name', 'age']

 Object.values(): Returns an array of object values.

const person = {name: 'John', age: 30};


Object.values(person);
// returns ['John', 30]

 Object.freeze(): Prevents modification of object properties.

const obj = {name: 'item'};


Object.freeze(obj);
obj.name = 'changed'; // won't change

 Object.hasOwnProperty(): Checks if the object directly contains the specified property.

const obj = {name: 'item'};


obj.hasOwnProperty('name'); // returns true

Defining Methods on Objects

 As a property whose value is a function:

const person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
person.fullName(); // returns "John Doe"

Additional Utility Methods

 Object.create(): Creates a new object using an existing object prototype.

 Object.fromEntries(): Converts key/value pairs to object.

 Object.getOwnPropertyNames(): Gets all properties' names.

Object.getOwnPropertySymbols(): Gets all symbol properties.


Summary Table

Data Example Description


Type

Number let x = 5; Numeric values

String let s = "hi"; Textual data

Boolean let f = false; true or false

Undefined let a; Declared, not


assigned

Null let n = null; Explicit no value

Array let arr = ; List of elements

Object let o = Properties and values


{name:"Tom",age:22};
Operators
JavaScript includes various operators for arithmetic, assignment, comparison, logical operations, bitwise, string
manipulation, and more. Here is a detailed list with examples for each major category.

Arithmetic Operators

Used for mathematical calculations.

let a = 12, b = 5;
a + b; // 17 (Addition)
a - b; // 7 (Subtraction)
a * b; // 60 (Multiplication)
a / b; // 2.4 (Division)
a % b; // 2 (Remainder)
a ** 2; // 144 (Exponentiation)
++a; // 13 (Increment)
--b; // 4 (Decrement)

Assignment Operators

Assign values to variables.

let x = 10; // Simple assignment


x += 5; // x = x + 5 -> 15
x -= 3; // x = x - 3 -> 12
x *= 2; // x = x * 2 -> 24
x /= 4; // x = x / 4 -> 6
x %= 2; // x = x % 2 -> 0
x **= 3; // x = x ** 3 -> 0

Comparison Operators

Compare two values, return boolean (true or false).

a == b; // false (equal to)


a != b; // true (not equal to)
a === b; // false (strict equal: value & type)
a !== b; // true (strict not equal)
a > b; // true
a < b; // false
a >= b; // true
a <= b; // false

Logical Operators
Combine or invert boolean values.

true && false; // false (AND)


true || false; // true (OR)
!true; // false (NOT)

String Operators

Combine strings.

let str = "Hello" + " " + "World"; // "Hello World"

Bitwise Operators

Operate on binary representations.

5 & 1; // 1 (AND)
5 | 1; // 5 (OR)
5 ^ 1; // 4 (XOR)
~5; // -6 (NOT)
5 << 1;// 10 (left shift)
5 >> 1;// 2 (right shift)

Other Operators

 Ternary/Conditional Operator

let result = a > b ? "a is bigger" : "b is bigger";


// result = "a is bigger"

 typeof Operator

typeof 123; // "number"


typeof "hello"; // "string"
typeof true; // "boolean"
typeof []; // "object" (arrays)
typeof {}; // "object"
typeof undefined; // "undefined"

 instanceof Operator

[] instanceof Array; // true

 delete Operator

let obj = {name: "John"};


delete obj.name;
// obj = {}

 void Operator

void(0); // undefined

Table: Operator Types and Examples

Operator Type Example & Description

Arithmetic a + b, a - b, a * b, a / b, a % b, a ** b

Assignment x = 5, x += 2, x *= 4, x %= 3, x **= 2

Comparison x == y, x === y, x > y, x != y

Logical x > 5 && y < 2, x == 2

String "Hello" + "World"

Bitwise x & y, x

Ternary x>y?x:y

Typeof typeof "text"

Instanceof arr instanceof Array

Delete delete obj.prop


Operator Type Example & Description

Void void(0)
Loop
JavaScript provides several types of loops to repeatedly execute a block of code based on conditions or iterate over
collections. Here are the main types of loops with detailed explanations and examples:

1. for Loop

Used to repeat a block of code a specific number of times. It has three parts in one line: initialization, condition, and
increment/decrement.

Syntax:

for (initialization; condition; increment/decrement) {


// code to execute
}

Example:

for (let i = 1; i <= 3; i++) {


console.log("Count:", i);
}
// Output:
// Count: 1
// Count: 2
// Count: 3

 Initializes i to 1

 Runs the loop while i <= 3

 Increments i after each iteration

2. while Loop

Executes the block of code while the specified condition is true. It checks the condition before each iteration.

Syntax:

while (condition) {
// code to execute
}

Example:

let i = 0;
while (i < 3) {
console.log("Number:", i);
i++;
}
// Output:
// Number: 0
// Number: 1
// Number: 2

3. do-while Loop

Similar to while loop but the condition is checked after the code block executes. This guarantees the block runs at
least once.

Syntax:

do {
// code to execute
} while (condition);

Example:

let i = 0;
do {
console.log("Iteration:", i);
i++;
} while (i < 3);
// Output:
// Iteration: 0
// Iteration: 1
// Iteration: 2

4. for...in Loop

Used to iterate over the keys (property names) of an object.

Syntax:

for (let key in object) {


// code to execute
}

Example:
const person = { name: "Alice", age: 22 };
for (let key in person) {
console.log(key + ":", person[key]);
}
// Output:
// name: Alice
// age: 22

5. for...of Loop

Used to iterate over the values of iterable objects like arrays, strings, Maps, Sets.

Syntax:

for (let value of iterable) {


// code to execute
}

Example:

const arr = [1, 2, 3];


for (let value of arr) {
console.log(value);
}
// Output:
// 1
// 2
// 3

6. Array forEach()

An array method to execute a function on each element; limited to arrays.

Example:

const arr = [10, 20, 30];


arr.forEach(function(value, index) {
console.log(index, value);
});
// Output:
// 0 10
// 1 20
// 2 30
Loop Control Statements

 break: Exit the loop immediately.

 continue: Skip the current iteration and continue with the next.

Example:

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


if (i === 3) continue; // Skip when i = 3
if (i === 5) break; // Stop loop when i = 5
console.log(i);
}
// Output:
// 1
// 2
// 4

Summary Table of JavaScript Loops

Loop Purpose Example Use Case


Type

for Repeat code block a fixed number of times Counting iterations

while Repeat while condition is true Unknown number of iterations

do-while Run block at least once, then check Menu-driven loops, at least one
condition run

for...in Iterate over object property keys Enumerate object properties

for...of Iterate over iterable values Array or string value iteration

forEach Run function on every array element Functional array processing


Functions
JavaScript functions are blocks of code designed to perform a specific task. They help organize code, enable reuse,
and accept inputs to produce outputs. Here are detailed notes with examples for key types and concepts of
JavaScript functions:

1. Function Declaration

Defined with the function keyword, a function name, parentheses for parameters, and braces for the function body.

function greet() {
console.log("Hello World!");
}

greet(); // Output: Hello World!

 The function greet when called executes its code.

 No parameters in this example.

2. Function with Parameters and Arguments

Functions can accept input values called parameters. When called, you pass arguments for those parameters.

function greet(name) {
console.log(`Hello, ${name}!`);
}

greet("John"); // Output: Hello, John!


greet("Alice"); // Output: Hello, Alice!

 name is a parameter.

 Passed values like "John" are arguments.

3. Function Returning a Value

Functions can return a value to where they were called using the return statement.
function add(num1, num2) {
return num1 + num2;
}

let result = add(5, 4);


console.log(result); // Output: 9

 The returned sum is stored in result and logged.

4. Function Expressions

Functions can be assigned to variables as expressions, often anonymous (without a name).

const multiply = function(a, b) {


return a * b;
};

console.log(multiply(3, 4)); // Output: 12

 Function stored in multiply.

 Called via the variable name.

5. Arrow Functions (ES6+ Syntax)

A shorter syntax for function expressions, often more concise.

const square = (x) => x * x;

console.log(square(5)); // Output: 25

// For multiple parameters and statements:

const sum = (a, b) => {


const result = a + b;
return result;
};

console.log(sum(3, 7)); // Output: 10

6. Immediately Invoked Function Expression (IIFE)

A function that runs immediately after its definition.


(function() {
console.log("This runs immediately");
})();

7. Functions as First-Class Citizens

Functions can be passed as arguments to other functions or returned from functions.

function sayHello() {
return "Hello!";
}

function callFunction(func) {
console.log(func());
}

callFunction(sayHello); // Output: Hello!

Example Summary Table

Function Type Syntax Example Description

Declaration function greet() { ... } Named function declaration

With Parameters function greet(name) { ... } Takes input parameters

Returns Value function add(a,b) { return a + Returns output value


b; }

Function const x = function() { ... } Anonymous function assigned to


Expression variable

Arrow Function const f = (a) => a * 2; Shorter syntax, ES6

IIFE (function() { ... })(); Runs immediately on creation

You might also like