






















































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
A comprehensive introduction to fundamental javascript concepts, including data types, methods, control flow, and object-oriented programming. It covers essential topics such as string manipulation, array operations, function definitions, and event handling. The document also explores advanced concepts like closures, higher-order functions, and promises, providing a solid foundation for building interactive web applications.
Typology: Study notes
1 / 62
This page cannot be seen from the preview
Don't miss anything!
JavaScript is a case-sensitive language, meaning that variables and function names are distinguished by their capitalization. For example, myVariable and myvariable would be treated as two separate identifiers.
Statements in JavaScript are terminated by a semicolon (;). However, JavaScript has automatic semicolon insertion (ASI), which means that semicolons are often optional. It is generally recommended to include them for better code readability.
Comments in JavaScript can be single-line or multi-line. Single-line comments start with //, while multi-line comments are enclosed between /* and */. Comments are ignored by the JavaScript interpreter and are useful for adding explanations or disabling code temporarily.
JavaScript code can be included directly in an HTML file using <script> tags, either in the <head> section or just before the closing </body> tag. Alternatively, JavaScript code can be placed in an external file with a .js extension and linked to the HTML file using the <script src="filename.js"></script> tag.
JavaScript has several primitive data types: ● Number: Represents both integer and floating-point numbers. For example, age = 25; or let pi = 3.14;. ● ● String: Represents a sequence of characters enclosed in single quotes ('') or double quotes (""). For example, let name = ‘John’; or let message = “Hello, world!”;. ● ● Boolean: Represents either true or false. It is commonly used for logical operations and conditional statements. For example, let isTrue = true; or let isFalse = false;. ● ● Null: Represents the intentional absence of any object value. It is often used to indicate the absence of a meaningful value. For example, let data = null;. ● ● Undefined: Represents a variable that has been declared but has not been assigned a value. For example, let x; will result in x being undefined. ● ● Symbol: Represents a unique identifier. Symbols are often used as keys for object properties to avoid naming collisions. Symbols are created using the Symbol() function. For example, let id = Symbol(); ●
● String indices refer to the position of individual characters within a string. ● ● In JavaScript, strings are zero-indexed, meaning the first character has an index of 0. ● ● Accessing a specific character is done using square brackets [] with the index value.
● - let str = "Hello";
const text =
Line 1 Line 2;
+
concatenation for strings without expressions.const name = 'John'; const age = 25; const message = My name is ${name} and I'm ${age} years old.
; console.log(message); ●.
JavaScript also has several object data types, which are created using the syntax. Object data types can contain properties and methods, which are accessed using dot notation.
let person = { name: ‘John Doe’;, age: 30, job: “Software Engineer”; }; person.name; // "John Doe" person.age; // 30 person.job; // "Software Engineer"
● var was the original way to declare variables but has some quirks related to scope. It is function-scoped, meaning that variables declared with var are accessible throughout the entire function in which they are defined. ● ● let and const were introduced in ECMAScript 6 and provide block-scoping. Variables declared with let are limited to the block they are defined in (e.g., within an if statement or loop). const creates a read-only variable with block scope that cannot be reassigned.
let age = 25; // Declares a variable 'age' and assigns the value 25 to it. age = 30; // Modifies the value of 'age' to 30.
Perform mathematical operations on numbers, such as addition (+), subtraction (-), multiplication (*), division (/), modulus (%), increment (++), and decrement (--).
Assign values to variables. The most common assignment operator is the equals sign (=), but there are also compound assignment operators like +=, -=, *=, /=, and more.
Compare values and return a Boolean result. They include == (equal to), === (strictly equal to), != (not equal to), !== (strictly not equal to), >, <, >=, and <=.
let isFalse = !isTrue; // isFalse is now false
Returns the type of the operand as a string. let value = 10; let type = typeof value; // type is "number" Using these unary operators, you can perform specific operations on individual operands to manipulate values and obtain desired results.
let x = 10 + 5;
let y = 10 - 5;
let z = 10 * 5;
let w = 10 / 5;
let remainder = 10 % 3;
let increment = x++;
let decrement = y--;
x
: let x = 10;
x = x + 5
: x += 5;
(x is now 15)x = x - 3
: x -= 3;
(x is now 12)x = x * 2
: x *= 2;
(x is now 24)x = x / 4
: x /= 4;
(x is now 6)x = x % 5
: x %= 5;
(x is now 1)console.log(x === y);
console.log(x !== y);
console.log(x > y);
console.log(x < y);
console.log(x >= y);
console.log(x <= y);
console.log(x && y);
console.log(x || y);
console.log(!x);
There are many more operators in JavaScript, including bitwise, string concatenation, ternary, and more. Understanding and utilizing operators is fundamental for performing various computations and making logical decisions in JavaScript. Identifier Rules in JavaScript ● Identifiers (variable names, function names, etc.) must follow specific rules:Array methods are used to manipulate and retrieve information from arrays. ● .push Adds one or more elements to the end of an array. ● .pop Removes the last element from an array. ● .join Joins all elements of an array into a string. ● .indexOf Returns the index of the first occurrence of a specified element in an array. ● .splice() Modifies an array by adding/removing elements at specified index.
Math methods provide mathematical operations and functions in JavaScript. ● .random Returns a random number between 0 and 1. ● .floor Rounds a number down to the nearest integer. ● .ceil Rounds a number up to the nearest integer. ● .sqrt Returns the square root of a number.
Date methods allow you to work with dates and times. ● .getFullYear Returns the year of a Date object. ● .getMonth Returns the month (0-11) of a Date object. ● .getDate Returns the day of the month (1-31) of a Date object. ● .toISOString Converts a Date object to a string in ISO format.
Object methods are functions that are associated with objects and allow you to perform operations on those objects. ● .toString Converts an object to a string representation. ● .hasOwnProperty Returns true if an object has a specified property. ● .keys Returns an array containing the property names of an object. By using methods, you can perform various operations and retrieve information from di erent data types in JavaScript. Understanding and utilising these methods is essential for e cient coding and manipulating data e ectively. Please note that the code examples provided here are brief and simplified. For detailed syntax and additional parameters of each method, it is recommended to refer to the o cial JavaScript documentation or relevant resources.
● The if statement is used to execute a block of code if a specified condition evaluates to true. ● ● The else if statement can be used to specify additional conditions to check if the preceding conditions are false. ● ● The switch statement allows the execution of di erent code blocks based on di erent cases.
● The for loop is commonly used when the number of iterations is known or determined in advance. ● ● The while loop executes a block of code as long as a specified condition is true. ● ● The do-while loop is similar to the while loop but guarantees that the code block is executed at least once, even if the condition is initially false.
● The break statement is used to exit the loop immediately, skipping any remaining iterations. ● ● The continue statement is used to skip the current iteration and move to the next iteration of the loop. Control structures are essential for controlling the flow of execution in JavaScript, making decisions, and performing iterative operations.
javascript const fruits = ['apple', 'banana', 'orange']; fruits[1] = 'grape'; // Modify 'banana' to 'grape' console.log(fruits); // Output: ['apple', 'grape', 'orange']
javascript const fruits = ['apple', 'banana', 'orange']; console.log(fruits.length); // Output: 3
javascript const fruits = ['apple', 'banana']; fruits.push('orange'); // Add 'orange' to the end fruits.unshift('grape'); // Add 'grape' to the beginning console.log(fruits); // Output: ['grape', 'apple', 'banana', 'orange']
javascript const fruits = ['apple', 'banana', 'orange']; const removedLast = fruits.pop(); // Remove 'orange' const removedFirst = fruits.shift(); // Remove 'apple' console.log(fruits); // Output: ['banana'] console.log(removedLast); // Output: 'orange' console.log(removedFirst); // Output: 'apple'
javascript const fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi']; const slicedFruits = fruits.slice(1, 4); // Extract from index 1 to index 3 (not inclusive) console.log(slicedFruits); // Output: ['banana', 'orange', 'grape']
Conclusion
Objects are collections of key-value pairs. They are used to represent more complex data structures than primitive data types like strings, numbers, and booleans.
Objects can be created using object literal notation (enclosed in curly braces) or the new keyword.
let person = { name: “John”;, age: 30, city: “New York”; }; Or:
let person = new Object( ); person.name = “John”; person.age = 30; person.city = “New York”;
Object properties and methods can be accessed using dot notation (object.property) or bracket notation (object.property').
console.log(person.name); // Output: John console.log(person.age); // Output: 30
Objects can contain properties of any data type, including primitive types, arrays, and even other objects.
let person = { name: “John”, age: 30, hobbies:“reading”, “painting”, address: { Street: “123 Main St”, City: ”New York”, }
● TAN: The tangent of a number. ● ASIN: The inverse sine of a number. ● ACOS: The inverse cosine of a number. ● ATAN: The inverse tangent of a number. ● POW: The power of a number to a given exponent. ● EXP: The exponential function. ● ROUND: The function that rounds a number to a given number of decimal places. ● FLOOR: The function that rounds a number down to the nearest integer. ● CEILING: The function that rounds a number up to the nearest integer. ● RANDOM: The function that returns a random number between 0 and 1. Some of the methods of the Math object include: ● abs(): The absolute value of a number. ● acos(): The inverse cosine of a number. ● asin(): The inverse sine of a number. ● atan(): The inverse tangent of a number. ● ceil(): The ceiling of a number. ● cos(): The cosine of a number. ● exp(): The exponential function. ● floor(): The floor of a number. ● log(): The logarithm of a number. ● max(): The maximum of two numbers. ● min(): The minimum of two numbers. ● pow(): The power of a number to a given exponent. ● random(): A random number between 0 and 1. ● round(): The rounded value of a number. ● sin(): The sine of a number. ● sqrt(): The square root of a number. ● tan(): The tangent of a number.
Objects are a fundamental concept in JavaScript and are widely used to represent and manipulate complex data structures.
A function is a reusable block of code that performs a specific task. How to define a function Functions can be defined using the function keyword followed by a name, a set of parentheses, and a block of code enclosed in curly braces. For example: function greet() { console.log(“Hello!”); }
Parameters can be passed into functions to provide inputs for the function's logic. Parameters are listed inside the parentheses when defining the function. For example: function greet(name) { console.log(“Hello”, + name + “!”); }
Functions can return a value using the return statement. The return value can be assigned to a variable or used directly. For example: function add(a, b) { return a + b; } let sum = add(3, 5); console.log(sum); // Output: 8
Functions can also be assigned to variables. These are known as function expressions. For example: let greet = function() {