Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

JavaScript Fundamentals: Data Types, Methods, and Control Flow, Study notes of Javascript programming

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

2021/2022

Uploaded on 11/13/2024

abhay-tiwari-4
abhay-tiwari-4 🇮🇳

5 documents

1 / 62

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
JavaScript
Certainly! Let's dive into each of the topics in more
detail, providing comprehensive explanations and
examples.
1. Syntax
Case Sensitivity
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
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
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.
Code Formatting
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.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e

Partial preview of the text

Download JavaScript Fundamentals: Data Types, Methods, and Control Flow and more Study notes Javascript programming in PDF only on Docsity!

JavaScript

Certainly! Let's dive into each of the topics in more

detail, providing comprehensive explanations and

examples.

1. Syntax

Case Sensitivity

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

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

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.

Code Formatting

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.

  1. Data Types

Primitive Data Types

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:

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.

● Example:

- let str = "Hello";

  • Multiline strings: const text =Line 1 Line 2;
  • Use + concatenation for strings without expressions.
  • Benefits: Readable, ecient, and maintainable code.

● Example:

const name = 'John'; const age = 25; const message = My name is ${name} and I'm ${age} years old.; console.log(message); .

Object Data Types

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.

For example:

let person = { name: ‘John Doe’;, age: 30, job: “Software Engineer”; }; person.name; // "John Doe" person.age; // 30 person.job; // "Software Engineer"

  1. Variables

Variables are declared using the var, let, or const keyword.

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.

Variables can store values of any data type, and their values can be

assigned and modified using the assignment operator (=).

For example:

let age = 25; // Declares a variable 'age' and assigns the value 25 to it. age = 30; // Modifies the value of 'age' to 30.

  1. Operators JavaScript supports a wide range of operators that perform various operations on operands.

Arithmetic operators

Perform mathematical operations on numbers, such as addition (+), subtraction (-), multiplication (*), division (/), modulus (%), increment (++), and decrement (--).

Assignment operators

Assign values to variables. The most common assignment operator is the equals sign (=), but there are also compound assignment operators like +=, -=, *=, /=, and more.

Comparison operators

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

Typeof

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.

Examples

Arithmetic Operators

  • Addition: let x = 10 + 5;
  • Subtraction: let y = 10 - 5;
  • Multiplication: let z = 10 * 5;
  • Division: let w = 10 / 5;
  • Modulo (remainder of division): let remainder = 10 % 3;
  • Post-increment: let increment = x++;
  • Post-decrement: let decrement = y--;

Assignment Operators

  • Assigns the value 10 to x: let x = 10;
  • Equivalent to x = x + 5: x += 5; (x is now 15)
  • Equivalent to x = x - 3: x -= 3; (x is now 12)
  • Equivalent to x = x * 2: x *= 2; (x is now 24)
  • Equivalent to x = x / 4: x /= 4; (x is now 6)
  • Equivalent to x = x % 5: x %= 5; (x is now 1)

Comparison Operators

  • Strict equality comparison (false): console.log(x === y);
  • Strict inequality comparison (true): console.log(x !== y);
  • Greater than (false): console.log(x &gt; y);
  • Less than (true): console.log(x &lt; y);
  • Greater than or equal to (false): console.log(x &gt;= y);
  • Less than or equal to (true): console.log(x &lt;= y);

Logical Operators

  • Logical AND (false): console.log(x &amp;&amp; y);
  • Logical OR (true): console.log(x || y);
  • Logical NOT (false): 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

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

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

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 dierent data types in JavaScript. Understanding and utilising these methods is essential for ecient coding and manipulating data eectively. 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 ocial JavaScript documentation or relevant resources.

  1. Control Structures

Conditional statements

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 dierent code blocks based on dierent cases.

Loops

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.

Break and continue statements

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.

  1. Arrays (Data Structure)
  2. Introduction to Arrays

javascript const fruits = ['apple', 'banana', 'orange']; fruits[1] = 'grape'; // Modify 'banana' to 'grape' console.log(fruits); // Output: ['apple', 'grape', 'orange']

  1. Array Length
● The length property of an array gives the number of elements it
contains.
● Example:

javascript const fruits = ['apple', 'banana', 'orange']; console.log(fruits.length); // Output: 3

  1. Adding Elements
● Use the .push() method to add elements to the end of an array.
● Use the .unshift() method to add elements to the beginning of an
array.
● Example:

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

  1. Removing Elements
● Use the .pop() method to remove the last element from an array and
return it.
● Use the .shift() method to remove the first element from an array and
return it.
● Example:

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'

  1. Slicing Arrays
● The .slice() method extracts a portion of an array into a new array
without modifying the original.
● Example:

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

  1. Combining Arrays

Conclusion

Arrays are versatile data structures in JavaScript, oering powerful
capabilities to store and manipulate collections of data. With arrays, you
can easily access, modify, add, and remove elements as needed. By
understanding array methods and iterating techniques, you can
eciently work with arrays in your JavaScript programs and build
complex data-driven applications.
  1. Objects

What are objects?

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.

How to create objects?

Objects can be created using object literal notation (enclosed in curly braces) or the new keyword.

For example:

let person = { name: “John”;, age: 30, city: “New York”; }; Or:

let person = new Object( ); person.name = “John”; person.age = 30; person.city = “New York”;

How to access object properties and methods?

Object properties and methods can be accessed using dot notation (object.property) or bracket notation (object.property').

For example:

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

What kind of data can objects contain?

Objects can contain properties of any data type, including primitive types, arrays, and even other objects.

For example:

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 fundamental in JavaScript

Objects are a fundamental concept in JavaScript and are widely used to represent and manipulate complex data structures.

  1. Functions (Most IMP)

What is a function?

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

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

Return value

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

Function expressions

Functions can also be assigned to variables. These are known as function expressions. For example: let greet = function() {