















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!
















Introduction to JavaScript arrays In JavaScript, an array is an ordered list of values. Each value is called an element specified by an index : A JavaScript array has the following characteristics:
In case you are in a rush, here is what an array looks like declared both ways: // Using array constructor let array = new array("John Doe", 24 , true); // Using the literal notation let array = ["John Doe", 24 , true]; How to Declare an Array with Literal Notation This is the most popular and easiest way to create an array. It is a shorter and cleaner way of declaring an array. To declare an array with literal notation you just define a new array using empty brackets. It looks like this: let myArray = []; You will place all elements within the square brackets and separate each item or element with a comma. let myArray = ["John Doe", 24 , true]; Arrays are zero-indexed, meaning you can access each element starting from zero or output the entire array. console.log(myArray[ 0 ]); // 'John Doe' console.log(myArray[ 2 ]); // true console.log(myArray); // ['John Doe', 24, true] How to Declare an Array with the Array Constructor You can also use the array constructor to create or declare an array. There are a lot of technicalities to declaring an array with the Array() constructor. Just as you can store multiple values with diverse data types in one variable with the array literal notation, you can do the same with the array constructor. let myArray = new Array(); console.log(myArray); // [] The above will create a new empty array. You can add values to the new array by placing them in between the brackets, separated by a comma. let myArray = new Array("John Doe", 24 , true); REFERENCE AND REFERENCE PARAMETERS IN JAVASCRIPT
javascript let a = 10; function changeValue(val) { val = 20; } changeValue(a); console.log(a); // 10 In this example, the original value of a remains 10, even after calling changeValue because a is passed by value. PASSING ARRAYS TO FUNTION Passing arrays to functions in JavaScript is a common practice, as arrays are one of the fundamental data structures. Here’s a detailed explanation along with examples to help you understand how it works. How It Works When you pass an array to a function in JavaScript, you are passing a reference to the array. This means that any changes made to the array within the function will affect the original array outside the function. Example javascript // Define a function that modifies an array function modifyArray(arr) { arr.push('new item'); } // Create an array let myArray = ['item1', 'item2']; // Pass the array to the function modifyArray(myArray); console.log(myArray); // Output: ['item1', 'item2', 'new item'] In this example, the modifyArray function adds a new item to the myArray. Since arrays are passed by reference, the original myArray gets modified. Using Arrays as Parameters You can also perform various operations on arrays within functions, such as iterating, filtering, or mapping:
Iterating over an Array javascript function printArray(arr) { for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } } let myArray = ['apple', 'banana', 'cherry']; printArray(myArray); // Output: apple, banana, cherry Filtering an Array javascript function filterArray(arr, callback) { return arr.filter(callback); } let numbers = [1, 2, 3, 4, 5, 6]; let evenNumbers = filterArray(numbers, function(num) { return num % 2 === 0; }); console.log(evenNumbers); // Output: [2, 4, 6] In this example, the filterArray function takes an array and a callback function to filter out even numbers. Mapping an Array javascript function mapArray(arr, callback) { return arr.map(callback); } let numbers = [1, 2, 3, 4, 5]; let squaredNumbers = mapArray(numbers, function(num) { return num * num; }); console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25] Here, the mapArray function takes an array and a callback function to return an array with squared numbers. MULTIDIMENSIONAL ARRAYS
This code will print all the elements of the array, one by one. Modifying Elements in a Two-Dimensional Array You can also modify elements in a two-dimensional array using their indices: javascript let array = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; array[1][1] = 42; console.log(array[1][1]); // Output: 42 console.log(array); // Output: [ [ 1, 2, 3 ], [ 4, 42, 6 ], [ 7, 8, 9 ] ] Higher-Dimensional Arrays You can create higher-dimensional arrays by adding more levels of nesting: Example of a Three-Dimensional Array javascript let threeDimensionalArray = [ [ [1, 2, 3], [4, 5, 6] ], [ [7, 8, 9], [10, 11, 12] ] ]; console.log(threeDimensionalArray); Accessing Elements in a Three-Dimensional Array To access elements in a three-dimensional array, you need three indices: javascript console.log(threeDimensionalArray[1][0][2]); // Output: 9 EVENTS IN JAVA SCRIPT
The change in the state of an object is known as an Event. In html, there are various events which represents that some activity is performed by the user or by the browser. When javascript code is included in HTML, js react over these events and allow the execution. This process of reacting over the events is called Event Handling. Thus, js handles the HTML events via Event Handlers. For example , when a user clicks over the browser, add js code, which will execute the task to be performed on the event. Event Handler Uses: It can be used directly within HTML elements by adding special attributes to those elements. They can also be used within the finishes the loading of the page unload onunload When the visitor leaves the current webpage, the browser unloads it resize onresize When the visitor resizes the window of the browser reset onreset When the window size is resized scroll onscroll When the visitor scrolls a scrollable area Common Event Handlers
**
event.stopPropagation() line in the example, and the alert for "Div clicked!" will not appear when the button is clicked. JAVA SCRIPT OBJECTS – INTRODUCTION TO OBJECT TECHNOLOGY What is an Object? An object in JavaScript is a collection of properties, where each property is defined as a key- value pair. The key is a string (also called a property name), and the value can be any data type, including other objects, functions, or arrays. Creating an Object There are several ways to create objects in JavaScript:
Accessing and Modifying Object Properties You can access or modify the properties of an object using either dot notation or bracket notation: javascript // Dot notation console.log(person.firstName); // Outputs: John person.age = 31; // Bracket notation console.log(person["lastName"]); // Outputs: Doe person["occupation"] = "Senior Developer"; Adding and Deleting Properties You can dynamically add or delete properties from an object: javascript // Adding a property person.gender = "male"; // Deleting a property delete person.occupation; Methods in Objects A method is a function that is a property of an object. Methods allow objects to exhibit behavior: javascript let person = { firstName: "John", lastName: "Doe", age: 30, occupation: "Developer", getFullName: function() { return this.firstName + " " + this.lastName; } }; console.log(person.getFullName()); // Outputs: John Doe Math Methods
Output ABS Test Value : 20 ACOS Test Value : 3. ASIN Test Value : 1. ATAN Test Value : 0.
● Date is a data type. ● Date object manipulates date and time. ● Date() constructor takes no arguments. ● Date object allows you to get and set the year, month, day, hour, minute, second and millisecond fields. Syntax: var variable_name = new Date(); Example: var current_date = new Date(); Date Methods Methods Description Date() Returns current date and time. getDate() Returns the day of the month. getDay() Returns the day of the week. getFullYear() Returns the year. getHours() Returns the hour. getMinutes() Returns the minutes.
getSeconds() Returns the seconds. getMilliseconds() Returns the milliseconds. getTime() Returns the number of milliseconds since January 1, 1970 at 12:00 AM. getTimezoneOffset() Returns the timezone offset in minutes for the current locale. getMonth() Returns the month. setDate() Sets the day of the month. setFullYear() Sets the full year. setHours() Sets the hours. setMinutes() Sets the minutes. setSeconds() Sets the seconds. setMilliseconds() Sets the milliseconds. setTime() Sets the number of milliseconds since January 1, 1970 at 12:00 AM. setMonth() Sets the month. toDateString() Returns the date portion of the Date as a human-readable string. toLocaleString() Returns the Date object as a string. toGMTString() Returns the Date object as a string in GMT timezone. valueOf() Returns the primitive value of a Date object.
length It returns the length of the string. prototype It allows you to add properties and methods to an object. constructor It returns the reference to the String function that created the object. String Methods Methods Description charAt() It returns the character at the specified index. charCodeAt() It returns the ASCII code of the character at the specified position. concat() It combines the text of two strings and returns a new string. indexOf() It returns the index within the calling String object. match() It is used to match a regular expression against a string. replace() It is used to replace the matched substring with a new substring. search() It executes the search for a match between a regular expression. slice() It extracts a session of a string and returns a new string. split() It splits a string object into an array of strings by separating the string into the substrings. toLowerCase() It returns the calling string value converted lower case. toUpperCase() Returns the calling string value converted to uppercase.
Output: Boolean Object The Boolean object is an object wrapper for a boolean value. Boolean objects are rarely used in practice; instead, the primitive boolean values true and false are more commonly utilized. Example: javascript let boolObj = new Boolean(true); console.log(boolObj); // Output: [Boolean: true] Primitive boolean: javascript let isTrue = true; let isFalse = false; console.log(isTrue); // Output: true console.log(isFalse); // Output: false Number Object The Number object is a wrapper object allowing you to work with numerical values. It has properties and methods to help manipulate numbers.