Java Script (1)
- Created by Brendan Eich , in Netscape (Mozilla) [ 1995 ]
- JS is not Java , and hence cant be used to develop applets
- Originally named Mocha
- Used mainly in client side scripting but lately being used in server side scripts also.
-
Variables - Something to hold data
var first = 'hello world'; console.log(first); // will print the content of variable first //
-
Using computations:
var a = 1; var b = 2; var total = a+b; total // will give output as 3 //
-
HTML integration :
Java script comes inside the script tag in html
<!DOCTYPE html>
<html>
<body>
<script>
var first = function() {
console.log('hello world');
alert('hello world1');
};
//calling function
first();
</script>
OMG!!!
</body>
</html>Java script can be included as a separate file outside html
👉🏻 using external JS will help the website to load faster-
External js
sample.js
function first() { console.log('hello world'); alert('hello world1'); };
sample.html
<!DOCTYPE html> <html> <body> <script src ="sample.js"> </script> <script> first(); </script> OMG!!! </body> </html>
-
Getting input via STDIN
const readline = require ("readline"); const inp = readline .createInterface({ input: process.stdin }); inp.on("line",(data) => { console.log(data) });
- The
&&operator returnstrueif both operands aretrue. Otherwise, it returnsfalse.
let a = true;
let b = false;
console.log(a && b); // false
console.log(a && true); // true
console.log(false && b); // false
console.log(true && true); // true- The
||operator returnstrueif at least one of the operands istrue. If both arefalse, it returnsfalse.
let a = true;
let b = false;
console.log(a || b); // true
console.log(a || true); // true
console.log(false || b); // false
console.log(false || false); // falseChecks if two values are equal. It performs type conversion if necessary.
console.log(5 == '5'); // true
console.log(5 == 5); // true
console.log(5 == 6); // falseChecks if two values are equal and of the same type.
console.log(5 === '5'); // false
console.log(5 === 5); // true
console.log(5 === 6); // falseChecks if two values are not equal. It performs type conversion if necessary.
console.log(5 != '5'); // false
console.log(5 != 5); // false
console.log(5 != 6); // trueChecks if two values are not equal or not of the same type.
javascriptCopy code
console.log(5 !== '5'); // true
console.log(5 !== 5); // false
console.log(5 !== 6); // trueChecks if the value on the left is greater than the value on the right.
javascriptCopy code
console.log(5 > 3); // true
console.log(3 > 5); // false
console.log(5 > 5); // falseChecks if the value on the left is greater than or equal to the value on the right.
javascriptCopy code
console.log(5 >= 3); // true
console.log(3 >= 5); // false
console.log(5 >= 5); // trueChecks if the value on the left is less than the value on the right.
javascriptCopy code
console.log(5 < 3); // false
console.log(3 < 5); // true
console.log(5 < 5); // falseChecks if the value on the left is less than or equal to the value on the right.
javascriptCopy code
console.log(5 <= 3); // false
console.log(3 <= 5); // true
console.log(5 <= 5); // trueThe increment operator (++) is used to increase the value of a variable by 1. There are two types of increment operators in JavaScript:
When the increment operator is placed after the variable (x++), it increases the value of the variable by 1 but returns the original value before the increment.
Example:
let x = 5;
console.log(x++); // Output: 5 (original value before increment)
console.log(x); // Output: 6 (value after increment)When the increment operator is placed before the variable (++x), it increases the value of the variable by 1 and returns the new value after the increment.
Example:
let y = 5;
console.log(++y); // Output: 6 (value after increment)
console.log(y); // Output: 6 (value after increment)Here is an example demonstrating both postfix and prefix increment operators:
let a = 10;
let b = 10;
console.log("Postfix Increment:");
console.log(a++); // Output: 10 (original value before increment)
console.log(a); // Output: 11 (value after increment)
console.log("Prefix Increment:");
console.log(++b); // Output: 11 (value after increment)
console.log(b); // Output: 11 (value after increment)JavaScript uses the + operator for string concatenation and arithmetic addition. When used with strings or mixed with numbers, it concatenates them.
let name = "John";
let age = 30;
// String concatenation
let message = "Hello, " + name + "! You are " + age + " years old.";
console.log(message); // Output: Hello, John! You are 30 years old.
// Mixing string and number
let info = "Name: " + name + ", Age: " + age;
console.log(info); // Output: Name: John, Age: 30Template literals (${}) provide a more flexible and readable way to concatenate strings and include expressions.
let name = "Jane";
let age = 25;
// String concatenation with template literals
let greeting = `Hello, ${name}! You are ${age} years old.`;
console.log(greeting); // Output: Hello, Jane! You are 25 years old.
// Mixing string and number with template literals
let details = `Name: ${name}, Age: ${age}`;
console.log(details); // Output: Name: Jane, Age: 25-
Implicit Conversion: JavaScript converts numbers to strings when using
+with strings. -
Template Literals: Introduced in ES6, provide easier string interpolation and multiline strings with backticks (``).
let firstName = "Alice"; let lastName = "Smith"; let age = 28; // Using template literals for complex concatenation let fullName = `${firstName} ${lastName}`; let profile = `${fullName} is ${age} years old.`; console.log(fullName); // Output: Alice Smith console.log(profile); // Output: Alice Smith is 28 years old.
Loops in JavaScript are used to repeatedly execute a block of code until a condition is met. There are several types of loops:
The for loop executes a block of code a specified number of times.
for (let i = 0; i < 5; i++) {
console.log(i); // Outputs: 0, 1, 2, 3, 4
}The while loop executes a block of code as long as a specified condition is true.
let i = 0;
while (i < 5) {
console.log(i); // Outputs: 0, 1, 2, 3, 4
i++;
}The do...while loop is similar to while, but it always executes the block of code once before checking the condition.
let i = 0;
do {
console.log(i); // Outputs: 0, 1, 2, 3, 4
i++;
} while (i < 5);You can iterate over arrays using loops or array methods like forEach, map, filter, etc.
let numbers = [1, 2, 3, 4, 5];
for (let number of numbers) {
console.log(number); // Outputs: 1, 2, 3, 4, 5
}
// Using forEach method
numbers.forEach(function(number) {
console.log(number); // Outputs: 1, 2, 3, 4, 5
});break: Terminates the loop immediately.continue: Skips the current iteration and continues to the next iteration.
for (let i = 0; i < 10; i++) {
if (i === 3) {
continue; // Skips printing 3
}
if (i === 8) {
break; // Stops loop at 8
}
console.log(i); // Outputs: 0, 1, 2, 4, 5, 6, 7
}- Loops are fundamental for iterating over data structures like arrays or performing repetitive tasks.
- Choose the appropriate loop type (
for,while,do...while) based on the condition and requirements.
The break statement terminates the current loop execution and resumes execution at the next statement after the loop.
Example:
for (let i = 1; i <= 5; i++) {
if (i === 3) {
break;
}
console.log(i);
}-
Output:
1 2
The continue statement skips the current iteration of the loop and proceeds to the next iteration.
Example:
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue;
}
console.log(i);
}-
Output:
1 2 4 5
Usage Scenarios:
break: Used to exit a loop early based on a condition.continue: Used to skip an iteration based on a condition and continue with the next iteration.
These are reserved words that are part of the language syntax.
break
case
catch
class
const
continue
debugger
default
delete
do
else
enum
export
extends
false
finally
for
function
if
import
in
instanceof
new
null
return
super
switch
this
throw
true
try
typeof
var
void
while
with
yield
implements
interface
let
package
private
protected
public
static
JavaScript arrays are used to store multiple values in a single variable. They can hold any combination of values—strings, numbers, objects, or even other arrays.
You can create arrays in JavaScript in several ways:
-
Using Array Literal Syntax:
let fruits = ["Apple", "Banana", "Mango"];
-
Using the Array Constructor:
let fruits = new Array("Apple", "Banana", "Mango");
Array elements can be accessed using their index, starting from 0.
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]); // Output: Apple
console.log(fruits[1]); // Output: Banana-
Length Property:
- The
lengthproperty returns the number of elements in an array.
let fruits = ["Apple", "Banana", "Mango"]; console.log(fruits.length); // Output: 3
- The
-
push() Method:
- Adds one or more elements to the end of an array and returns the new length of the array.
let fruits = ["Apple", "Banana"]; fruits.push("Mango"); console.log(fruits); // Output: ["Apple", "Banana", "Mango"]
-
pop() Method:
- Removes the last element of an array and returns that element.
let fruits = ["Apple", "Banana", "Mango"]; let lastFruit = fruits.pop(); console.log(lastFruit); // Output: Mango console.log(fruits); // Output: ["Apple", "Banana"]
-
shift() Method:
- Removes the first element of an array and returns that element.
let fruits = ["Apple", "Banana", "Mango"]; let firstFruit = fruits.shift(); console.log(firstFruit); // Output: Apple console.log(fruits); // Output: ["Banana", "Mango"]
-
unshift() Method:
- Adds one or more elements to the beginning of an array and returns the new length of the array.
let fruits = ["Banana", "Mango"]; fruits.unshift("Apple");
In JavaScript, functions are blocks of reusable code designed to perform a particular task. They are fundamental to structuring and organizing code for better maintainability and reusability.
There are a few ways to create functions in JavaScript:
-
Function Declaration:
function greet(name) { return "Hello, " + name + "!"; }
-
Function Expression (Anonymous Function):
let greet = function(name) { return "Hello, " + name + "!"; };
-
Arrow Function (ES6+):
let greet = (name) => { return "Hello, " + name + "!"; };
Once defined, functions are called or invoked by using their name followed by parentheses containing any arguments (if required).
let message = greet("Alice");
console.log(message); // Output: Hello, Alice!-
Parameters: These are placeholders listed in the function definition.
function greet(name) { // `name` is a parameter return "Hello, " + name + "!"; }
-
Arguments: These are the actual values passed to the function when calling it.
let message = greet("Alice"); // "Alice" is an argument
Functions can return values using the return statement. If no return statement is specified, the function returns undefined.
function add(a, b) {
return a + b;
}
let result = add(3, 4);
console.log(result); // Output: 7Variables declared inside a function are local to that function (function scope), meaning they are not accessible from outside the function.
function sayHello() {
let message = "Hello!";
console.log(message); // Output: Hello!
}
// console.log(message); // Error: message is not defined outside sayHello()In JavaScript, function declarations are hoisted to the top of their scope, which allows you to call a function before it's declared in the code.
console.log(add(2, 3)); // Output: 5
function add(a, b) {
return a + b;
}-
Named Function:
function greet(name) { return "Hello, " + name + "!"; }
-
Anonymous Function (Function Expression):
let greet = function(name) { return "Hello, " + name + "!"; };
Functions play a crucial role in JavaScript for code organization, encapsulation, and modularity, making it easier to manage and scale applications.
JavaScript objects are collections of key-value pairs, where the keys are strings (or Symbols) and the values can be any type, including other objects. Objects are used to store data and functionality in a structured way.
-
Object Literal Syntax:
let person = { firstName: "John", lastName: "Doe", age: 30, isEmployed: true };
-
Using the
ObjectConstructor:let person = new Object(); person.firstName = "John"; person.lastName = "Doe"; person.age = 30; person.isEmployed = true;
You can access object properties using dot notation or bracket notation.
-
Dot Notation:
console.log(person.firstName); // Output: John console.log(person.age); // Output: 30
-
Bracket Notation:
console.log(person["firstName"]); // Output: John console.log(person["age"]); // Output: 30
You can add or modify properties of an object using dot notation or bracket notation.
person.middleName = "Michael"; // Adding a new property
person.age = 35; // Modifying an existing propertyYou can remove a property from an object using the delete operator.
delete person.isEmployed;
console.log(person.isEmployed); // Output: undefinedMethods are functions that are stored as object properties.
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
console.log(person.fullName()); // Output: John DoeYou can iterate over the properties of an object using a for...in loop.
for (let key in person) {
if (person.hasOwnProperty(key)) {
console.log(key + ": " + person[key]);
}
}JavaScript objects come with several built-in methods and properties that make working with objects easier.
-
Object.keys():- Returns an array of the object's own property names (keys).
console.log(Object.keys(person)); // Output: ["firstName", "lastName", "age", "fullName"]
-
Object.values():- Returns an array of the object's own property values.
console.log(Object.values(person)); // Output: ["John", "Doe", 30, function() { return this.firstName + " " + this.lastName; }]
-
Object.entries():- Returns an array of the object's own key-value pairs.
console.log(Object.entries(person)); // Output: [["firstName", "John"], ["lastName", "Doe"], ["age", 30], ["fullName", function() { return this.firstName + " " + this.lastName; }]]
-
Object.assign():- Copies the values of all enumerable own properties from one or more source objects to a target object.
let additionalInfo = { isEmployed: true, nationality: "American" }; Object.assign(person, additionalInfo); console.log(person); // Output: { firstName: "John", lastName: "Doe", age: 30,
Anonymous functions in JavaScript are functions that are defined without a name. They are often used for short-term tasks that don’t require a separate, named function. They can be assigned to variables, passed as arguments to other functions, or used in places where functions are expected but don't need to be reused.
Basic Anonymous Function
let sum = function(a, b) {
return a + b;
};
console.log(sum(5, 3)); // Output: 8In this example, an anonymous function is assigned to the variable sum. The function takes two parameters, a and b, and returns their sum.
Anonymous Function as an Argument
setTimeout(function() {
console.log("This message is displayed after 2 seconds");
}, 2000);Here, an anonymous function is passed as an argument to the setTimeout function. It will be executed after a delay of 2000 milliseconds (2 seconds).
Immediately Invoked Function Expression (IIFE)
(function() {
console.log("This is an immediately invoked function expression");
})();An IIFE is an anonymous function that is executed immediately after it is defined. This is useful for creating a new scope and avoiding polluting the global scope.
Anonymous Function in Event Handling
document.getElementById('myButton').addEventListener('click', function() {
console.log("Button was clicked!");
});An anonymous function is used as an event handler for a button click event. This function will execute whenever the button with the ID myButton is clicked.
Arrow Functions
Arrow functions are a shorter syntax for writing anonymous functions and were introduced in ES6.
let multiply = (a, b) => {
return a * b;
};
console.log(multiply(4, 7)); // Output: 28Arrow functions can also be written in a more concise form if they contain only a single expression.
let divide = (a, b) => a / b;
console.log(divide(10, 2)); // Output: 5- Callbacks: When passing a function as an argument to another function, such as in event handlers or asynchronous operations.
- IIFE: To create a new scope and avoid variable name conflicts.
- Short-Term Usage: For functions that are used only once and don’t need a name.