JAVA SCRIPT
1) What is Java Script :
JavaScript is a programming language used to create interactive and dynamic content on websites. It allows you to add features like animations, form validation, and dynamic updates to web pages without reloading them. JavaScript can be run on both the client-side (in the browser) and the server-side (using environments like Node.js). It's widely used for web development alongside HTML and CSS.[click here]
2) Java Script Variables :(Video Link)
In JavaScript, variables are containers for storing data values. Variables can be declared using `var`, `let`, or `const`. Here's a quick overview:
1. Declaring Variables:
- `var`: Older way to declare variables. It has function scope and can be re-declared.
- `let`: Introduced in ES6 (2015), `let` has block scope and is the recommended way to declare variables when you plan to change the value.
- `const`: Also introduced in ES6, `const` is used to declare variables with a constant value (cannot be reassigned) and also has block scope.
Example:
var x = 10; // Function-scoped variable
let y = 20; // Block-scoped variable (can be changed later)
const z = 30; // Block-scoped constant (cannot be changed)
2. Variable Scope:
- Global scope: Variables declared outside functions are global and accessible from anywhere in the code.
- Function scope: Variables declared with `var` inside a function are only available within that function.
- Block scope: Variables declared with `let` or `const` inside a block `{}` are confined to that block.
3. Hoisting:
- Variables declared with `var` are "hoisted," meaning their declaration is moved to the top of their scope, but not their assignment.
- `let` and `const` are also hoisted but not initialized, meaning they are not accessible before the declaration line.
Example of Hoisting:
console.log(a); // undefined (due to hoisting)
var a = 10;
console.log(b); // ReferenceError (because `let` is not hoisted in the same way)
let b = 20;
4. Variable Naming Rules:
- Variable names can include letters, digits, underscores, and dollar signs.
- They must begin with a letter, underscore (`_`), or dollar sign (`$`).
- Names are case-sensitive (`myVariable` is different from `MyVariable`).
3) Java Script Numbers:
In JavaScript, numbers are one of the fundamental data types and are used to represent both integer and floating-point values. Here’s an overview of how numbers work in JavaScript:
1. Number Type:
- JavaScript has a single type for numbers, which can represent both integers and floating-point values.
- The `Number` type in JavaScript uses 64-bit floating-point format (IEEE 754).
2. Basic Operations:
let a = 10;
let b = 5;
let sum = a + b; // Addition: 15
let difference = a - b; // Subtraction: 5
let product = a * b; // Multiplication: 50
let quotient = a / b; // Division: 2
let remainder = a % b; // Modulus: 0
3. Special Values:
- `NaN`: Stands for "Not-a-Number". It is a special value used to represent a computational error, such as the result of dividing 0 by 0.
let result = 0 / 0; // NaN
- `Infinity`: Represents positive infinity, often used to represent a value that exceeds the largest number JavaScript can handle.
let inf = 1 / 0; // Infinity
`-Infinity`: Represents negative infinity.
let negInf = -1 / 0; // -Infinity
4. Number Methods:
- `toFixed(digits)`: Formats a number to a specified number of decimal places.
let num = 123.456;
let formatted = num.toFixed(2); // "123.46"
- `toExponential([digits])`: Returns a string representing the number in exponential notation.
let exp = 123456;
let expStr = exp.toExponential(2); // "1.23e+5"
- `toPrecision([digits])`: Formats a number to a specified length.
let precise = 123.456;
let preciseStr = precise.toPrecision(4); // "123.5"
5. Number Parsing:
- `parseInt(string, [radix])`: Parses a string and returns an integer. The optional `radix` argument specifies the base of the number system.
let integer = parseInt("123", 10); // 123
- `parseFloat(string)`: Parses a string and returns a floating-point number.
let floating = parseFloat("123.456"); // 123.456
6. Number Conversions:
- `Number(string)`: Converts a string to a number.
let num = Number("123.456"); // 123.456
- `+string`: Unary plus operator also converts a string to a number.
let num = +"123.456"; // 123.456
7. Precision and Rounding:
- JavaScript’s floating-point arithmetic can lead to precision issues.
let sum = 0.1 + 0.2; // 0.30000000000000004 (not exactly 0.3)
Understanding these aspects of JavaScript numbers can help you work with numeric data more effectively in your scripts.
4) Java Script Strings:
In JavaScript, a string is a sequence of characters used to represent text. Strings are typically enclosed in single quotes (`'`) or double quotes (`"`), and they can be manipulated using various methods and properties.
Here are a few examples:
Creating a String:
let str1 = 'Hello, World!';
let str2 = "JavaScript is fun!";
String Concatenation:
You can combine two strings using the `+` operator:
let greeting = 'Hello, ' + 'Manoj!';
console.log(greeting); // Output: Hello, Manoj!
Template Literals:
Strings can also be created using backticks (`` ` ``) to include variables or expressions inside them.
let name = 'Manoj';
let message = `Hello, ${name}!`;
console.log(message); // Output: Hello, Manoj!
String Methods:
- `length`: Returns the length of the string.
let text = 'Hello';
console.log(text.length); // Output: 5
- `toUpperCase()`: Converts the string to uppercase.
console.log(text.toUpperCase()); // Output: HELLO
- `toLowerCase()`: Converts the string to lowercase.
console.log(text.toLowerCase()); // Output: hello
- `slice(start, end)`: Extracts a section of the string.
console.log(text.slice(1, 4)); // Output: ell
These are just a few basic examples of JavaScript string usage. You can perform many more operations like replacing characters, splitting strings, searching, and more.
5) Java Script Objects:
In JavaScript, objects are collections of key-value pairs, where each key is a string (or symbol) and its corresponding value can be any data type, including other objects. Objects are a fundamental part of JavaScript and are used to store data in a structured way.
Creating an Object
You can create an object using curly braces `{}` and define key-value pairs inside:
let person = {
name: 'Manoj',
age: 30,
job: 'Software Developer'
};
Accessing Object Properties
You can access properties of an object in two ways:
1. Dot notation:
console.log(person.name); // Output: Manoj
console.log(person.age); // Output: 30
2. Bracket notation:
console.log(person['name']); // Output: Manoj
Adding or Modifying Properties
You can add new properties or modify existing ones:
person.city = 'Chennai'; // Adding a new property
person.age = 31; // Modifying an existing property
console.log(person.city); // Output: Chennai
console.log(person.age); // Output: 31
Deleting a Property
You can delete a property using the `delete` keyword:
delete person.job;
console.log(person.job); // Output: undefined
Methods in Objects
Objects can also have functions as values, called methods:
let car = {
brand: 'Toyota',
model: 'Camry',
start: function() {
console.log('The car has started.');
}
};
car.start(); // Output: The car has started.
Nested Objects
Objects can contain other objects as values:
let student = {
name: 'Manoj',
marks: {
math: 90,
science: 85
}
};
console.log(student.marks.math); // Output: 90
Looping through Object Properties
You can loop through the properties of an object using the `for...in` loop:
for (let key in person) {
console.log(key + ": " + person[key]);
}
// Output:
// name: Manoj
// age: 31
// city: Chennai
Common Object Methods
- `Object.keys()`: Returns an array of the object's keys.
console.log(Object.keys(person)); // Output: ['name', 'age', 'city']
- `Object.values()`: Returns an array of the object's values.
console.log(Object.values(person)); // Output: ['Manoj', 31, 'Chennai']
- 'Object.entries()`: Returns an array of key-value pairs.
console.log(Object.entries(person)); // Output: [['name', 'Manoj'], ['age', 31], ['city', 'Chennai']]
Objects are very versatile and are used in many areas of JavaScript programming, including data structures, configurations, and more.
6) Java Script Functions:
In JavaScript, a function is a reusable block of code that performs a specific task. Functions are fundamental to structuring and organizing JavaScript code. They allow you to write code once and execute it multiple times with different inputs (called arguments).
Defining a Function
There are several ways to define a function in JavaScript:
1. Function Declaration
A function is declared using the `function` keyword, followed by the name of the function, parentheses `()`, and a block of code `{}`:
function greet() {
console.log('Hello, Manoj!');
}
To call the function, use its name followed by parentheses:
greet(); // Output: Hello, Manoj!
2. Function with Parameters
You can pass values to a function using parameters. These are variables defined within the parentheses.
function greet(name) {
console.log('Hello, ' + name + '!');
}
greet('Manoj'); // Output: Hello, Manoj!
greet('John'); // Output: Hello, John!
3. Function with Return Value
Functions can return a value using the `return` keyword:
function add(a, b) {
return a + b;
}
let result = add(5, 3);
console.log(result); // Output: 8
4. Anonymous Functions
Anonymous functions are functions without a name and are often used with event handlers or in callbacks:
let sayHi = function() {
console.log('Hi there!');
};
sayHi(); // Output: Hi there!
5. Arrow Functions
Arrow functions offer a shorter syntax for writing functions and are especially useful for concise functions:
let multiply = (a, b) => a * b;
console.log(multiply(4, 5)); // Output: 2
If the function body has more than one statement, you need to use curly braces and `return`:
let subtract = (a, b) => {
let result = a - b;
return result;
};
console.log(subtract(10, 4)); // Output: 6
Function Scope
- Local Scope: Variables declared inside a function are only accessible within that function.
function example() {
let localVar = 'I am local';
console.log(localVar);
}
example(); // Output: I am local
console.log(localVar); // Error: localVar is not defined
- Global Scope: Variables declared outside any function are global and can be accessed anywhere in the code.
Function as a Parameter (Callback Function)
Functions can also be passed as arguments to other functions:
function executeCallback(callback) {
callback();
}
function sayGoodbye() {
console.log('Goodbye, Manoj!');
}
executeCallback(sayGoodbye); // Output: Goodbye, Mano
Default Parameters
You can assign default values to function parameters, which will be used if no arguments are passed:
function greet(name = 'Guest') {
console.log('Hello, ' + name + '!');
}
greet(); // Output: Hello, Guest!
greet('Manoj'); // Output: Hello, Manoj!
IIFE (Immediately Invoked Function Expression)
An IIFE is a function that runs immediately after being defined:
(function() {
console.log('This is an IIFE!');
})(); // Output: This is an IIFE!
Recursion
A function can call itself, which is known as recursion:
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(5)); // Output: 120
JavaScript functions are versatile, and mastering them is key to writing efficient and reusable code.
0 Comments